先上效果:
2、语义分割之图片和 mask 的可视化
python给图像加上mask,并提取mask区域_xnholiday的博客-CSDN博客_mask python
import os
import cv2
import numpy as np
def add_mask2image_binary(images_path, masks_path, masked_path):
# Add binary masks to images
for 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)
【效果展示】:
原数据:
语义分割之图片和 mask 的可视化 - AI备忘录 (aiuai.cn)
PS:原图片会出现一些色变
import cv2
import numpy as np
import matplotlib.pyplot as plt
imgfile = '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)
import cv2
import numpy as np
import os
def 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)