详解Python PIL logical_xor()和invert()方法

  • Post category:Python

当使用Python进行图像处理时,PIL(Python Imaging Library)是一个非常常用和强大的库。其中,logical_xor()和invert()方法是PIL库中常用的图像处理方法之一。

PIL logical_xor()方法

logical_xor() 方法可以用于将两个输入图像的像素值进行逐像素的逻辑异或操作,返回一个新的图像。

语法格式为:

ImageChops.logical_xor(image1, image2)

其中:

  • image1:第一个输入图像;
  • image2:第二个输入图像。

示例1:

from PIL import Image, ImageChops

#加载2张图片
image1 = Image.open('image1.png')
image2 = Image.open('image2.png')

#进行逻辑异或操作
image_xor = ImageChops.logical_xor(image1, image2)

#保存图像
image_xor.save('image_xor.png')

说明:

  • 通过PIL库中的ImageChops模块的logical_xor()方法,对image1image2进行逻辑异或操作,将结果保存为新的图像image_xor

示例2:

from PIL import Image, ImageChops

#加载1张图片
image = Image.open('image.png')

#创建与image大小相同的黑色底图
background = Image.new('RGB', image.size, (0, 0, 0))

#进行逻辑异或操作
image_xor = ImageChops.logical_xor(image, background)

#保存图像
image_xor.save('image_xor.png')

说明:

  • 先通过Image.new方法创建与image大小相同的黑色底图background
  • 再将imagebackground进行逻辑异或操作,将结果保存为新的图像image_xor

PIL invert()方法

invert() 方法可以用于将输入图像的像素值进行逐像素取反操作,返回一个新的图像。

语法格式为:

ImageOps.invert(image)

其中:

  • image:输入图像。

示例1:

from PIL import Image, ImageOps

#加载1张图片
image = Image.open('image.png')

#进行像素取反操作
image_invert = ImageOps.invert(image)

#保存图像
image_invert.save('image_invert.png')

说明:

  • 通过PIL库中的ImageOps模块的invert()方法,对image进行逐像素取反操作,将结果保存为新的图像image_invert

示例2:

from PIL import Image, ImageOps

#加载1张图片
image = Image.open('image.png')

#创建与image大小相同的灰色底图
background = Image.new('L', image.size, 128)

#将底图与image进行合并,得到新的图像image_with_background
image_with_background = ImageOps.fit(image, background.size, method=Image.ANTIALIAS)
image_with_background.putalpha(background)

#进行像素取反操作
image_invert = ImageOps.invert(image_with_background)

#保存图像
image_invert.save('image_invert.png')

说明:

  • 先通过Image.new方法创建与image大小相同的灰色底图background
  • 再通过ImageOps.fit方法将image缩放为底图大小,并使用background作为底图,将两者合并,得到新的图像image_with_background
  • 最后对image_with_background进行逐像素取反操作,将结果保存为新的图像image_invert