Pillow怎么对图像执行仿射变换

avatar
作者
猴君
阅读量:4

在Python中,可以使用Pillow库中的Image类来对图像执行仿射变换。下面是一个简单的示例代码,演示如何对图像进行平移、旋转和缩放等仿射变换:

from PIL import Image from PIL import ImageOps from PIL import ImageFilter import numpy as np import 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库来显示原始图像和变换后的图像。您可以根据需要修改仿射变换矩阵来实现不同的变换效果。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!