将mask显示在原图 发表于 2020-03-22 在深度学习中,如Unet等图像分割生成的mask经常是一个二值化的图像。 为直观表示,可以用如下代码将mask画在原图。 123456789101112131415161718192021222324def draw_mask(img_path,mask_path): # 原图路径,mask路径 image = cv2.imread(img_path) # 原图 mask_2d = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # mask灰度图 cv2.imshow("2d", mask_2d) cv2.imshow("iamge",image) cv2.waitKey() # mask_resize = np.ones((h, w), dtype='uint8') * 255 # 如果mask与原图大小有差,需resize # mask_resize[mask_2d[:, :] == 255] = 0 #如果白色是背景,黑色是分割物体,需反转黑白色 # cv2.imshow("mask_resize", mask_resize) # 利用cv2.findContours()函数找到连通域 ret, thresh = cv2.threshold(mask_2d, 128, 255, 0) contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 利用cv2.drawContours()画连通域边界 for cnt in contours: cv2.drawContours(image, [cnt], 0, (0, 255, 0), 1) # 打开画了轮廓之后的图像 cv2.imshow('image+mask', image) cv2.waitKey(0) # 保存图像 # cv2.imwrite("show/" + os.path.basename(img_path), image) 原图 mask图 效果