本文主要是介绍【图像分割_数据集】mask可视化(标签文件png全黑怎么办),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 一、python给图像加上mask,并提取mask区域
- 二、语义分割之图片和 mask 的可视化
- 1、处理单张图片
- 2、批量处理
先上效果:
1、python给图像加上mask,并提取mask区域
2、语义分割之图片和 mask 的可视化
一、python给图像加上mask,并提取mask区域
python给图像加上mask,并提取mask区域_xnholiday的博客-CSDN博客_mask python
import os
import cv2
import numpy as npdef add_mask2image_binary(images_path, masks_path, masked_path):# Add binary masks to imagesfor img_item in os.listdir(images_path):print(img_item)img_path = os.path.join(images_path, img_item)img = cv2.imread(img_path)mask_path = os.path.join(masks_path, img_item[:-4] + '.png') # mask是.png格式的,image是.jpg格式的mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # 将彩色mask以二值图像形式读取masked = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8), mask=mask) # 将image的相素值和mask像素值相加得到结果cv2.imwrite(os.path.join(masked_path, img_item), masked)# 注意使用全局路径,且无中文
images_path = r'/home/root/work/JPEGImages/'
masks_path = r'/home/root/work/Annotations/'
masked_path = r'/home/root/work/masked/'
add_mask2image_binary(images_path, masks_path, masked_path)
【效果展示】:
原数据:
- JPEGImages
- Annotations
提取mask后:
二、语义分割之图片和 mask 的可视化
语义分割之图片和 mask 的可视化 - AI备忘录 (aiuai.cn)
PS:原图片会出现一些色变
1、处理单张图片
import cv2
import numpy as np
import matplotlib.pyplot as pltimgfile = 'JPEGImages/00001.jpg'
pngfile = 'Annotations/00001.png'img = cv2.imread(imgfile, 1)
mask = cv2.imread(pngfile, 0)contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 1)img = img[:, :, ::-1]
img[..., 2] = np.where(mask == 1, 255, img[..., 2])plt.imshow(img)
plt.show()
# cv2.imwrite("visual/00001.jpg", img)
效果展示:
2、批量处理
import cv2
import numpy as np
import osdef get_path(images_path, masks_path, visualized_path):for filename in os.listdir(images_path):img_path = os.path.join(images_path, filename)mask_path = os.path.join(masks_path, filename[:-4] + '.png')img = cv2.imread(img_path, 1)mask = cv2.imread(mask_path, 0)contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(img, contours, -1, (0, 0, 255), 1)img = img[:, :, ::-1]img[..., 2] = np.where(mask == 1, 255, img[..., 2])cv2.imwrite(os.path.join(visualized_path, filename), img)print("{} saved".format(filename))print("finish")images_path = 'JPEGImages/'
masks_path = 'Annotations/'
visualized_path = 'visual/'
get_path(images_path, masks_path, visualized_path)
这篇关于【图像分割_数据集】mask可视化(标签文件png全黑怎么办)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!