python给图像加上mask,并提取mask区域实例

yipeiwu_com6年前Python基础

python对图像提取mask部分:

代码:

#coding:utf-8
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 = '/home/xinan/cat_test/image/'
masks_path = '/home/xinan/cat_test/catmask/'
masked_path = '/home/xinan/cat_test/masked/'
add_mask2image_binary(images_path, masks_path, masked_path)

效果图:

mask:

image:

result:

以上这篇python给图像加上mask,并提取mask区域实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用POP3和SMTP协议收发邮件的示例代码

Python使用POP3和SMTP协议收发邮件的示例代码

先来了解一下收/发邮件有哪些协议: SMTP协议 SMTP(Simple Mail Transfer Protocol),即简单邮件传输协议。相当于中转站,将邮件发送到客户端。 POP...

python的urllib模块显示下载进度示例

复制代码 代码如下: def report_hook(count, block_size, total_size):...     pr...

Python 3.x基于Xml数据的Http请求方法

Python 3.x基于Xml数据的Http请求方法

1. 前言 由于公司的一个项目是基于B/S架构与WEB服务通信,使用XML数据作为通信数据,在添加新功能时,WEB端与客户端分别由不同的部门负责,所以在WEB端功能实现过程中,需要自己发...

python 正则式 概述及常用字符

1.元字符: . 它匹配除了换行字符外的任何字符,在 alternate 模式(re.DOTALL)下它甚至可以匹配换行 ^ 匹配行首。除非设置 MULTILINE 标志,它只是匹配字符...

Python unittest 简单实现参数化的方法

Python unittest 理论上是不建议参数驱动的,其用例应该专注单元测试,确保每个method的逻辑正确。 引用Stack Overflow的一个答案, “单元测试应该是独立的,...