使用python的opencv将图像分割后的mask轮廓叠加在原图上

使用python的opencv将图像分割后的mask轮廓叠加在原图上


问题

  • 原始数据是原图像以及分割后的白色背景黑色mask块,要将mask的轮廓画在原图上,方便可视化分割结果
  • 图像和mask如下:
  • 原图像:0.bmp-586kB
  • mask:0.bmp-257.1kB

实现方法

  • 先将原图和mask分别用cv2库读入,因为这里的数据集mask和原图尺寸不一致,所以需要resize。
  • 读入后使用cv2的轮廓检测函数findContours()检测出mask的轮廓,因为findContours()函数是检测黑底白色对象的轮廓,所以需要转换一波。
  • 转换后的轮廓使用cv2的drawContours()函数画在原图上。
  • 实现代码:
def union_image_mask(image_path, mask_path, num):
    # 读取原图
    image = cv2.imread(image_path)
    # print(image.shape) # (400, 500, 3)
    # print(image.size) # 600000
    # print(image.dtype) # uint8

    # 读取分割mask,这里本数据集中是白色背景黑色mask
    mask_2d = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
    # 裁剪到和原图一样大小
    mask_2d = mask_2d[0:400, 0:500]
    h, w = mask_2d.shape
    cv2.imshow("2d", mask_2d)

    # 在OpenCV中,查找轮廓是从黑色背景中查找白色对象,所以要转成黑色背景白色mask
    mask_3d = np.ones((h, w), dtype='uint8')*255
    # mask_3d_color = np.zeros((h,w,3),dtype='uint8')
    mask_3d[mask_2d[:, :] == 255] = 0
    cv2.imshow("3d", mask_3d)
    ret, thresh = cv2.threshold(mask_3d, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    cv2.drawContours(image, [cnt], 0, (0, 255, 0), 1)
    # 打开画了轮廓之后的图像
    cv2.imshow('mask', image)
    k = cv2.waitKey(0)
    if k == 27:
        cv2.destroyAllWindows()
    # 保存图像
    # cv2.imwrite("./image/result/" + str(num) + ".bmp", image)

实现结果

  • Snipaste_2019-10-22_20-08-17.png-163.9kB

附录

  • 参考资料:opencv python 图像轮廓/检测轮廓/绘制轮廓

  • 有关findContours()和drawContours()两个函数的详情可在上面的参考链接中查看。

  • 可以在cv2.drawContours(image, [cnt], 0, (0, 255, 0), 1)这一行代码中修改函数参数,改动轮廓的颜色和大小。

  • 18
    点赞
  • 127
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霍姆格雷特

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值