详解Python PIL Image.transform()方法

  • Post category:Python

Python PIL Image.transform()方法详解

方法说明

Image.transform(method, size, data=None, resample=None, fill=None, fillcolor=None)

  • method: 指定要应用的转换方法。转换方法应是像函数(g) = f(x)一样的函数,其中g为输出的像素值,x为输入的像素值。转换方法应该是可逆的,也就是说,应该有一个逆转换方法,以便将输出值返回到输入值。方法可以是字符串、函数或包含函数的元组。
  • size: 要求输入图像较小或较大以进行转换。如果方法需要,将使用此参数来编排输入和输出像素之间的映射。如果为None,则输入图像的大小将保持不变。
  • data: 附加的转换参数。如果方法需要,则可用于传递将在转换中使用的其他参数。此参数应是元组或列表。
  • resample: 可选的重新采样滤波器。如果要更改图像的大小,则会应用该滤波器。应为常量,有以下可选: PIL.Image.NEAREST, PIL.Image.BOX, PIL.Image.BILINEAR, PIL.Image.HAMMING, PIL.Image.BICUBIC 或 PIL.Image.LANCZOS。
  • fill: 可选的遮挡图像。如果指定,该图像将应用作输入图像的剪切掩模。
  • fillcolor: 可选的颜色分量,用于填充剪切区域(默认为0)。

方法示例

示例一

将颜色通道转换为黑白图像,并增加对比度。

from PIL import Image, ImageEnhance

# 打开图像,将其转换为灰度图像
image = Image.open("example.jpg").convert('LA')

# 将灰度图像转换为黑白图像并增加对比度
image = ImageEnhance.Contrast(image.convert('1')).enhance(5)

# 对图像应用像函数(g) = f(x)一样的函数,其中g为输出的像素值
method = lambda x: x + 50

# 运用transform方法,对图像实例进行转换处理
result = image.transform(image.size, Image.PERSPECTIVE, data=(0.5, -0.5, 0, 0.7, 1, 0))

示例二

将图片转为法老王的面具

from PIL import Image, ImageOps

# 读取输入图片
input_img = Image.open('example.jpg')

# 转换为灰度图像
gray_img = ImageOps.grayscale(input_img)

# 将灰度图像的轮廓处涂黑
contour_img = gray_img.filter(ImageFilter.CONTOUR)

# 图像大小缩放
size = (contour_img.size[0]*4, contour_img.size[1]*4)
contour_img = contour_img.resize(size)

# 将黑白轮廓贴到图片中
mask = ImageOps.colorize(contour_img, black='black', white='white')
mask.putalpha(contour_img)

# 图片旋转
rotated_img = input_img.rotate(-10, expand=1)

# 图片剪切
cropped_img = rotated_img.crop((200, 700, 1100, 2200))

# 图片转换为法老王面具
masked_img = Image.composite(cropped_img, Image.new('RGBA', size, (0,0,0,0)), mask)

# 运用transform方法,对图片进行透视变换
result = masked_img.transform(masked_img.size, Image.PERSPECTIVE, data=(60, 0, 200, 0, 50, 0, 0.001, 0))

以上示例均使用transform()对图像进行透视变换,但转换方法不同,来源于不同的需求,方法及其参数的不同也导致了最终得到的结果不同。