脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用PIL(Python-Imaging)反转图像的颜色方法

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

2021-05-21 00:36JohnieLi Python

今天小编就为大家分享一篇使用PIL(Python-Imaging)反转图像的颜色方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

解决方案一:

?
1
2
3
4
5
6
7
8
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透明的,参考如下代码。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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”模式。

?
1
2
3
im = im.convert('L')
im = ImageOps.invert(im)
im = im.convert('1')

以上这篇使用PIL(Python-Imaging)反转图像的颜色方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/JohinieLi/article/details/77448766

延伸 · 阅读

精彩推荐