python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图


Posted in Python onAugust 04, 2020

因为最近在做深度学习抠图,正好要用到蒙版进行抠图,所以我将抠图代码进行了封装注释,可以直接使用。可能走了弯路,若有高见请一定提出!

主要代码

import cv2
from PIL import Image
import numpy as np


class UnsupportedFormat(Exception):
 def __init__(self, input_type):
  self.t = input_type

 def __str__(self):
  return "不支持'{}'模式的转换,请使用为图片地址(path)、PIL.Image(pil)或OpenCV(cv2)模式".format(self.t)


class MatteMatting():
 def __init__(self, original_graph, mask_graph, input_type='path'):
  """
  将输入的图片经过蒙版转化为透明图构造函数
  :param original_graph:输入的图片地址、PIL格式、CV2格式
  :param mask_graph:蒙版的图片地址、PIL格式、CV2格式
  :param input_type:输入的类型,有path:图片地址、pil:pil类型、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_graph
   self.img2 = mask_graph
  else:
   raise UnsupportedFormat(input_type)

 @staticmethod
 def __transparent_back(img):
  """
  :param img: 传入图片地址
  :return: 返回替换白色后的透明图
  """
  img = img.convert('RGBA')
  L, H = img.size
  color_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 img

 def save_image(self, path, mask_flip=False):
  """
  用于保存透明图
  :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)

 @staticmethod
 def __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_flip=True) # mask_flip是指蒙版翻转,即把白色的变成黑色的,黑色的变成白色的

效果展示

input.jpg

python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图

mask.jpg

python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图

output.png

python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图

到此这篇关于python利用蒙版抠图(使用PIL.Image和cv2)输出透明背景图的文章就介绍到这了,更多相关python 输出透明背景图内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
简单介绍Python中的JSON模块
Apr 08 Python
Python中Django框架利用url来控制登录的方法
Jul 25 Python
python kmeans聚类简单介绍和实现代码
Feb 23 Python
pandas 取出表中一列数据所有的值并转换为array类型的方法
Apr 11 Python
对python中的xlsxwriter库简单分析
May 04 Python
对pandas数据判断是否为NaN值的方法详解
Nov 06 Python
python制作抖音代码舞
Apr 07 Python
Python数据结构与算法(几种排序)小结
Jun 22 Python
Python3 执行Linux Bash命令的方法
Jul 12 Python
numpy.transpose()实现数组的转置例子
Dec 02 Python
selenium设置浏览器为headless无头模式(Chrome和Firefox)
Jan 08 Python
python 对图片进行简单的处理
Jun 23 Python
Python如何给函数库增加日志功能
Aug 04 #Python
pycharm导入源码的具体步骤
Aug 04 #Python
python根据用户需求输入想爬取的内容及页数爬取图片方法详解
Aug 03 #Python
Python 如何调试程序崩溃错误
Aug 03 #Python
Python 捕获代码中所有异常的方法
Aug 03 #Python
Python连接mysql数据库及简单增删改查操作示例代码
Aug 03 #Python
Python pip使用超时问题解决方案
Aug 03 #Python
You might like
PHP上传图片进行等比缩放可增加水印功能
2014/01/13 PHP
PHP动态生成javascript文件的2个例子
2014/04/11 PHP
php中time()与$_SERVER[REQUEST_TIME]用法区别
2014/11/19 PHP
Yii2框架制作RESTful风格的API快速入门教程
2016/11/08 PHP
彻底搞懂PHP 变量结构体
2017/10/11 PHP
laravel在中间件内生成参数并且传递到控制器中的2种姿势
2019/10/15 PHP
javascript客户端解决方案 缓存提供程序
2010/07/14 Javascript
JavaScript中“+”的陷阱深刻理解
2012/12/04 Javascript
javascript中直接写php代码的方法
2013/07/31 Javascript
Jquery原生态实现表格header头随滚动条滚动而滚动
2014/03/18 Javascript
jquery分割字符串的方法
2015/06/24 Javascript
JavaScript数据类型学习笔记分享
2016/09/01 Javascript
JS对象的深度克隆方法示例
2017/03/16 Javascript
js canvas实现简单的图像扩散效果
2020/06/28 Javascript
javaScript日期工具类DateUtils详解
2017/12/08 Javascript
vue+webpack 打包文件 404 页面空白的解决方法
2018/02/28 Javascript
JS 实现获取验证码 倒计时功能
2018/10/29 Javascript
Layui实现数据表格默认全部显示(不要分页)
2019/10/26 Javascript
javascript实现弹出层效果
2019/12/10 Javascript
JS实现吸顶特效
2020/01/08 Javascript
小程序卡片切换效果组件wxCardSwiper的实现
2020/02/13 Javascript
解决vue props传Array/Object类型值,子组件报错的情况
2020/11/07 Javascript
python爬虫 使用真实浏览器打开网页的两种方法总结
2018/04/21 Python
matplotlib给子图添加图例的方法
2018/08/03 Python
pytorch 利用lstm做mnist手写数字识别分类的实例
2020/01/10 Python
Python3 字典dictionary入门基础附实例
2020/02/10 Python
CSS3实现文本垂直排列的方法
2018/07/10 HTML / CSS
日本最大的眼镜购物网站:Oh My Glasses
2016/11/13 全球购物
英国受欢迎的运动鞋和街头服装商店:Footasylum
2018/06/12 全球购物
MVC的各个部分都有那些技术来实现?如何实现?
2016/04/21 面试题
企划经理的岗位职责
2013/11/17 职场文书
计算机应用专业应届毕业生中文求职信范文
2013/11/29 职场文书
好的演讲稿开场白
2013/12/30 职场文书
市场部岗位职责
2015/02/12 职场文书
考试后的感想
2015/08/07 职场文书
Oracle 多表查询基本语法实例
2022/04/18 Oracle