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

yipeiwu_com5年前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中的index()方法使用教程

 index()方法确定字符串str,如果起始索引beg和结束索引end在末尾给出了找到字符串或字符串的一个子串。这个方法与find()方法一样,只是如果没有找到子符趾会抛出一...

对python特殊函数 __call__()的使用详解

__call__ 在Python中,函数其实是一个对象: >>> f = abs >>> f.__name__ 'abs' >>>...

python 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

Python json 错误xx is not JSON serializable解决办法

Python json 错误xx is not JSON serializable解决办法 在使用json的时候经常会遇到xxx  is not JSON serializab...

python PyTorch预训练示例

前言 最近使用PyTorch感觉妙不可言,有种当初使用Keras的快感,而且速度还不慢。各种设计直接简洁,方便研究,比tensorflow的臃肿好多了。今天让我们来谈谈PyTorch的预...