图像裁剪
- 先用Otsu方法对图像二值化
- 对二值化后的图像进行边缘搜寻,记下边缘像素的坐标,找到目标物体水平和垂直方向坐标的最大最小值,分别为xmax,xmin,ymax,ymin,以坐标(xmin,xmax,ymin,ymax)来设定裁剪的矩形范围,对原图进行裁剪,以此方法裁剪后的图像可以准确的抠出目标物体
代码
img_coal1 = cv2.imread('E:/EdgeReinforceGlcm/pythonProject1/pytorch_Lenet/image_reinforce/datas_mei/Mei-11.jpg')
img_coal = cv2.cvtColor(img_coal1, cv2.COLOR_BGR2GRAY)
blur1 = cv2.GaussianBlur(img_coal, (5, 5), 0)
ret1, th1 = cv2.threshold(blur1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
img_coal_H = th1.shape[0]
img_coal_W = th1.shape[1]
positions_1 = []
for y in range(img_coal_H):
for x in range(img_coal_W):
if th1[y, x] == 0:
positions_1.append((y, x))
y_max = positions_1[0][0]
y_min = positions_1[0][0]
for y1, x1 in positions_1:
if y1 > y_max:
y_max = y1
for y2, x2 in positions_1:
if y2 < y_min:
y_min = y2
x_max = positions_1[0][1]
x_min = positions_1[0][1]
for y1, x1 in positions_1:
if x1 > x_max:
x_max = x1
for y2, x2 in positions_1:
if x2 < x_min:
x_min = x2
img_coalCropped = img_coal[y_min:y_max, x_min:x_max]
for i in range(3):
plt.subplot(1, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
裁剪效果