图像进行碎片化分割
图像进行碎片化分割
图像进行碎片化分割
import cv2
import numpy as np
# 切割
def make_grid(shape, window=512, min_overlap=32):
"""
Return Array of size (N,4), where N - number of tiles,
2nd axis represente slices: x1,x2,y1,y2
"""
# 获取图像宽:x和长:y
x, y = shape
# 获取宽度可切割个数:宽度除以窗口宽度-overlap
nx = x
# 以切割个数,平均划分图像宽度
x1 = np.linspace(0, x, num=nx, endpoint=False, dtype=np.int64)
# 最后一个横坐标切割点需要置为x-window
# 确定完x1左上点横坐标
x1[-1] = x - window
# 确定x2 右下点横坐标
x2 = (x1 + window).clip(0, x) # .clip(0,x)表示x2的置必须在0到x
# 获取高度可切割个数:宽高度以窗口-overlap
ny = y
# 以切割个数,平均划分图像高度
y1 = np.linspace(0, y, num=ny, endpoint=False, dtype=np.int64)
# 最后一个纵坐标切割点需要置为x-window
# 确定完y1左上点纵坐标
y1[-1] = y - window
# 确定y2 右下点纵坐标
y2 = (y1 + window).clip(0, y) # .clip(0,y)表示y2的置必须在0到y
# 初始化切片存储列表
slices = np.zeros((nx, ny, 4), dtype=np.int64)
# 赋值切边坐标
for i in range(nx):
for j in range(ny):
slices[i, j] = x1[i], x2[i], y1[j], y2[j]
# 获取坐标点
slices = slices.reshape(nx * ny, 4)
# 小于0的置0
slices = np.maximum(slices, 0)
# 去重
uniques = []
for arr in slices:
if not any(np.array_equal(arr, unique_arr) for unique_arr in uniques):
uniques.append(arr)
# print(uniques)
return uniques
if __name__ == '__main__':
img = cv2.imread(r"D:\workplace\python\pythonProject2\SideArray\images\train\E_DRDGQR000BR0000175+5_S3-H-B2-2-Btm_3_1_YS-.bmp", cv2.IMREAD_COLOR)
shape = img.shape[0:2]
shape = (shape[1],shape[0])
res = make_grid(shape=shape,window=1280,min_overlap=100) # shape 宽 高
for index,item in enumerate(res): # item x1,x2,y1,y2
print(item)
block = img[item[2]: item[3],item[0]:item[1]] # 纵坐标 横坐标
cv2.imwrite(str(index)+".jpg", block)
plot_img = cv2.rectangle(img, (item[0],item[2]), (item[1],item[3]), ((100*index)%255, (30*index)%255, (50*index)%255), 20)
cv2.imwrite("Vis.jpg", plot_img)
大型图像的碎片化分割专用库:rasterio
import rasterio
from rasterio.windows import Window