自定义方法对图像目标物体进行裁剪

图像裁剪

  • 先用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)  # 高斯滤波,(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()

裁剪效果

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值