建设网站的情况说明书,档案网站建设视频,网站开发专业简历模板,wordpress 服务器搬家因为最近在做深度学习抠图#xff0c;正好要用到蒙版进行抠图#xff0c;所以我将抠图代码进行了封装注释#xff0c;可以直接使用。可能走了弯路#xff0c;若有高见请一定提出#xff01;主要代码import cv2from PIL import Imageimport numpy as npclass UnsupportedFo…因为最近在做深度学习抠图正好要用到蒙版进行抠图所以我将抠图代码进行了封装注释可以直接使用。可能走了弯路若有高见请一定提出主要代码import cv2from PIL import Imageimport numpy as npclass UnsupportedFormat(Exception):def __init__(self, input_type):self.t input_typedef __str__(self):return 不支持{}模式的转换请使用为图片地址(path)、PIL.Image(pil)或OpenCV(cv2)模式.format(self.t)class MatteMatting():def __init__(self, original_graph, mask_graph, input_typepath):将输入的图片经过蒙版转化为透明图构造函数:param original_graph:输入的图片地址、PIL格式、CV2格式:param mask_graph:蒙版的图片地址、PIL格式、CV2格式:param input_type:输入的类型有path图片地址、pilpil类型、cv2类型if input_type path:self.img1 cv2.imread(original_graph)self.img2 cv2.imread(mask_graph)elif input_type pil:self.img1 self.__image_to_opencv(original_graph)self.img2 self.__image_to_opencv(mask_graph)elif input_type cv2:self.img1 original_graphself.img2 mask_graphelse:raise UnsupportedFormat(input_type)staticmethoddef __transparent_back(img)::param img: 传入图片地址:return: 返回替换白色后的透明图img img.convert(RGBA)L, H img.sizecolor_0 (255, 255, 255, 255) # 要替换的颜色for h in range(H):for l in range(L):dot (l, h)color_1 img.getpixel(dot)if color_1 color_0:color_1 color_1[:-1] (0,)img.putpixel(dot, color_1)return imgdef save_image(self, path, mask_flipFalse):用于保存透明图:param path: 保存位置:param mask_flip: 蒙版翻转将蒙版的黑白颜色翻转;True翻转;False不使用翻转if mask_flip:img2 cv2.bitwise_not(self.img2) # 黑白翻转image cv2.add(self.img1, img2)image Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # OpenCV转换成PIL.Image格式img self.__transparent_back(image)img.save(path)staticmethoddef __image_to_opencv(image):PIL.Image转换成OpenCV格式img cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)return img使用示例mm MatteMatting(input.jpg, mask.jpg)mm.save_image(output.png, mask_flipTrue) # mask_flip是指蒙版翻转即把白色的变成黑色的黑色的变成白色的效果展示input.jpgmask.jpgoutput.png到此这篇关于python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图的文章就介绍到这了,更多相关python 输出透明背景图内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们本文标题: python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图本文地址: http://www.cppcns.com/jiaoben/python/330247.html