【图像分割

【图像分割,第1张

文章目录
  • 一、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 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
  • 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)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/868475.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存