先上效果:

1、python给图像加上mask,并提取mask区域
在这里插入图片描述

2、语义分割之图片和 mask 的可视化

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nETDo11K-1651327753502)(C:\Users\pc\AppData\Roaming\Typora\typora-user-images\image-20220430213341934.png)]

一、python给图像加上mask,并提取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)

【效果展示】:

原数据:

  • JPEGImages
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tm7buvmx-1651327753502)(C:\Users\pc\AppData\Roaming\Typora\typora-user-images\image-20220430205615573.png)]
  • Annotations
    请添加图片描述

提取mask后:
请添加图片描述

二、语义分割之图片和 mask 的可视化

语义分割之图片和 mask 的可视化 - AI备忘录 (aiuai.cn)

PS:原图片会出现一些色变

1、处理单张图片

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)

效果展示:
在这里插入图片描述

2、批量处理

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)

在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐