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之变量命名规则
May 27 Python
Python控制键盘鼠标pynput的详细用法
Jan 28 Python
python实现弹窗祝福效果
Apr 07 Python
Python字符串处理的8招秘籍(小结)
Aug 13 Python
对django layer弹窗组件的使用详解
Aug 31 Python
详解Python图像处理库Pillow常用使用方法
Sep 02 Python
keras tensorflow 实现在python下多进程运行
Feb 06 Python
Python数据正态性检验实现过程
Apr 18 Python
Python是怎样处理json模块的
Jul 16 Python
python线程池 ThreadPoolExecutor 的用法示例
Oct 10 Python
浅谈盘点5种基于Python生成的个性化语音方法
Feb 05 Python
判断Python中的Nonetype类型
May 25 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
BBS(php & mysql)完整版(四)
2006/10/09 PHP
php遍历数组的方法分享
2012/03/22 PHP
thinkPHP模板中函数的使用方法示例
2016/11/30 PHP
浅谈PHP实现大流量下抢购方案
2017/12/15 PHP
php获得刚插入数据的id 的几种方法总结
2018/05/31 PHP
IE 条件注释详解总结(附实例代码)
2009/08/29 Javascript
js(jQuery)获取时间的方法及常用时间类搜集
2013/10/23 Javascript
jQuery子属性过滤选择器用法分析
2015/02/10 Javascript
JavaScript中数据结构与算法(五):经典KMP算法
2015/06/19 Javascript
学习JavaScript设计模式之责任链模式
2016/01/18 Javascript
javascript基本算法汇总
2016/03/09 Javascript
Bootstrap布局之栅格系统详解
2016/06/13 Javascript
NodeJS和BootStrap分页效果的实现代码
2016/11/07 NodeJs
js中的触发事件对象event.srcElement与event.target详解
2017/03/15 Javascript
详解在Vue中有条件地使用CSS类
2017/09/30 Javascript
JavaScript设计模式之建造者模式实例教程
2018/07/02 Javascript
详解webpack-dev-middleware 源码解读
2020/03/23 Javascript
python练习程序批量修改文件名
2014/01/16 Python
Python遍历目录并批量更换文件名和目录名的方法
2016/09/19 Python
手把手教你用python抢票回家过年(代码简单)
2018/01/21 Python
python使用KNN算法手写体识别
2018/02/01 Python
Python设计模式之装饰模式实例详解
2019/01/21 Python
Python3.5 Pandas模块缺失值处理和层次索引实例详解
2019/04/23 Python
python将邻接矩阵输出成图的实现
2019/11/21 Python
Python面向对象程序设计之类和对象、实例变量、类变量用法分析
2020/03/23 Python
Django实现列表页商品数据返回教程
2020/04/03 Python
Python调用飞书发送消息的示例
2020/11/10 Python
Python编写万花尺图案实例
2021/01/03 Python
纯CSS和jQuery实现的在页面顶部显示的进度条效果2例(仿手机浏览器进度条效果)
2014/04/16 HTML / CSS
应届毕业生的个人自我鉴定
2013/10/24 职场文书
自荐信格式简述
2014/01/25 职场文书
理工类毕业自我鉴定
2014/02/20 职场文书
连锁超市项目计划书
2014/09/15 职场文书
六年级学生期末评语
2014/12/26 职场文书
Python基础之常用库常用方法整理
2021/04/30 Python
MySQL系列之十五 MySQL常用配置和性能压力测试
2021/07/02 MySQL