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

yipeiwu_com6年前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使用正则搜索字符串或文件中的浮点数代码实例

用python和numpy处理数据次数比较多,写了几个小函数,可以方便地读写数据: # -*- coding: utf-8 -*- #------------------------...

python银行系统实现源码

本文实例为大家分享了python实现银行系统的具体代码,供大家参考,具体内容如下 1、admin.py 定义管理员信息和主界面显示 #!/usr/bin/env python # c...

windows下cx_Freeze生成Python可执行程序的详细步骤

windows下cx_Freeze生成Python可执行程序的详细步骤

目前网上能获取的免费的python打包工具主要有三种:py2exe、PyInstaller和cx_Freeze。 下面简单介绍windows7下cx_Freeze打包python生成可执...

python3 pygame实现接小球游戏

python3 pygame实现接小球游戏

本文实例为大家分享了python3 pygame接小球游戏的具体代码,供大家参考,具体内容如下 操作方法:鼠标操作 截图: 直接放代码: # -*- coding:utf-8 -...

对Python3 pyc 文件的使用详解

什么是pyc文件 pyc是一种二进制文件,是由py文件经过编译后,生成的文件,是一种byte code,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由...