
使用Python为图像添加mask并提取指定区域实例
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
本教程详细介绍如何运用Python编程语言处理图像,具体包括创建和应用掩模(mask)以精确选取和分析图片中的特定区域。通过实例演示,帮助读者掌握高效利用Python进行图像处理的核心技术。
Python 对图像提取 mask 部分的代码如下:
```python
# coding:utf-8
import os
import cv2
import numpy as np
def add_mask2image_binary(images_path, masks_path, masked_path):
# 将二值掩模添加到图片中
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_file_name = mask_ + os.path.basename(img_path) # 假设掩模文件名与图片文件名相同,只是前缀不同
mask_path = os.path.join(masks_path, mask_file_name)
if not os.path.exists(mask_path):
print(fMask file {mask_file_name} does not exist.)
continue
mask = cv2.imread(mask_path, 0) # 以灰度模式读取掩模
masked_img = cv2.bitwise_and(img, img, mask=mask)
output_image_filename = os.path.join(masked_path, fmasked_{img_item})
cv2.imwrite(output_image_filename, masked_img)
```
这段代码定义了一个函数 `add_mask2image_binary`,用于将二值掩模添加到图像中,并保存处理后的结果。需要注意的是,该函数假设每个图片对应的掩模文件名与之相同(只是前缀不同),并且会检查并打印不存在的掩模文件信息。
全部评论 (0)


