Pillow怎么对图像执行仿射变换
在Python中,可以使用Pillow库中的Image类来对图像执行仿射变换。下面是一个简单的示例代码,演示如何对图像进行平移、旋转和缩放等仿射变换:
from PIL import Imagefrom PIL import ImageOpsfrom PIL import ImageFilterimport numpy as npimport matplotlib.pyplot as plt# 打开图像文件image = Image.open("example.jpg")# 定义仿射变换矩阵matrix = [1, 0, 100,# 水平平移100个像素0, 1, 50# 垂直平移50个像素]# 进行仿射变换image_transformed = image.transform(image.size, Image.AFFINE, matrix)# 显示原始图像和仿射变换后的图像plt.figure(figsize=(10, 5))plt.subplot(1, 2, 1)plt.imshow(image)plt.title("Original Image")plt.subplot(1, 2, 2)plt.imshow(image_transformed)plt.title("Transformed Image")plt.show()
在这个示例中,首先使用Image.open()
打开一个图像文件,然后定义一个仿射变换矩阵matrix
,其中前两行表示缩放、旋转和错切,后两行表示水平和竖直平移。最后使用image.transform()
函数对图像进行仿射变换,并使用Matplotlib库来显示原始图像和变换后的图像。您可以根据需要修改仿射变换矩阵来实现不同的变换效果。