使用PIL(Python-Imaging)反转图像的颜色方法

yipeiwu_com5年前Python基础

利用PIL将图片转换为黑色与白色反转的图片,下面笔者小白介绍如何实现。

解决方案一:

from PIL import Image
import PIL.ImageOps  
#读入图片
image = Image.open('your_image.png')
#反转
inverted_image = PIL.ImageOps.invert(image)
#保存图片
inverted_image.save('new_name.png')

注意:“ImageOps模块包含多个'ready-made'图像处理操作,该模块有些实验性,大多数操作符只适用于L和RGB图像。”

解决方案二:

如果图像是RGBA透明的,参考如下代码。

from PIL import Image
import PIL.ImageOps  

image = Image.open('your_image.png')
if image.mode == 'RGBA':
  r,g,b,a = image.split()
  rgb_image = Image.merge('RGB', (r,g,b))

  inverted_image = PIL.ImageOps.invert(rgb_image)

  r2,g2,b2 = inverted_image.split()

  final_transparent_image = Image.merge('RGBA', (r2,g2,b2,a))

  final_transparent_image.save('new_file.png')

else:
  inverted_image = PIL.ImageOps.invert(image)
  inverted_image.save('new_name.png')

解决方案三:

注:对于使用”1″模式的图像(即,1位像素,黑白色,以每个字节为单位存储的see docs),您需要在调用PIL.ImageOps.invert之前将其转换为”L”模式。

im = im.convert('L')
im = ImageOps.invert(im)
im = im.convert('1')

以上这篇使用PIL(Python-Imaging)反转图像的颜色方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python pickle存储、读取大数据量列表、字典数据的方法

先给大家介绍下python pickle存储、读取大数据量列表、字典的数据 针对于数据量比较大的列表、字典,可以采用将其加工为数据包来调用,减小文件大小 #列表 #存储 li...

利用Python实现在同一网络中的本地文件共享方法

本文利用Python3启动简单的HTTP服务器,以实现在同一网络中共享本地文件。 启动HTTP服务器 打开终端,转入目标文件所在文件夹,键入以下命令: $ cd /Users/zer...

pyshp创建shp点文件的方法

如下所示: # coding:utf-8 import shapefile w = shapefile.Writer() w.autoBalance = 1 w = shapef...

Python判断telnet通不通的实例

这个跟ping那个差不多,ping的那个脚本就是通过这个改了下,大体一致,不过telnet的不需要判断返回的字符串。快一些 这里具体需要telnet的ip是需要自己向定义好的数组中写的...

Python datetime包函数简单介绍

Python datetime包函数简单介绍

一、datetime包(上接连载7内容) 1.函数:datetime (1)用法:输入一个日期,来返回一个datetime类​ (2)格式:datetime.datetime...