使用python的opencv将图像分割后的mask轮廓叠加在原图上
问题
- 原始数据是原图像以及分割后的白色背景黑色mask块,要将mask的轮廓画在原图上,方便可视化分割结果
- 图像和mask如下:
- 原图像:
- mask:
实现方法
- 先将原图和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)
实现结果
附录
-
有关findContours()和drawContours()两个函数的详情可在上面的参考链接中查看。
-
可以在
cv2.drawContours(image, [cnt], 0, (0, 255, 0), 1)
这一行代码中修改函数参数,改动轮廓的颜色和大小。