【图像分割

编程入门 行业动态 更新时间:2024-10-18 18:16:12

【<a href=https://www.elefans.com/category/jswz/34/1771430.html style=图像分割"/>

【图像分割

文章目录

  • 一、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)

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)

更多推荐

【图像分割

本文发布于:2024-02-10 21:49:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!