温馨提示×

Pillow如何对图像执行波浪形变扭曲

小亿
84
2024-05-23 11:02:12
栏目: 编程语言

要对图像执行波浪形变扭曲,可以使用Pillow库中的Image类和ImageFilter类来实现。以下是一个示例代码:

from PIL import Image, ImageFilter

# 打开图像文件
img = Image.open('example.jpg')

# 定义波浪形变扭曲函数
def wave_distortion(x, y, amplitude, frequency):
    return x, y + amplitude * math.sin(2 * math.pi * frequency * x / img.width)

# 创建一个新的空白图像
new_img = Image.new('RGB', img.size)

# 扭曲图像
for y in range(img.height):
    for x in range(img.width):
        new_x, new_y = wave_distortion(x, y, amplitude=5, frequency=0.1)
        if 0 <= new_x < img.width and 0 <= new_y < img.height:
            pixel = img.getpixel((int(new_x), int(new_y))
            new_img.putpixel((x, y), pixel)

# 保存扭曲后的图像
new_img.save('distorted_image.jpg')

# 显示扭曲后的图像
new_img.show()

在上面的代码中,我们首先打开了一个图像文件,然后定义了一个波浪形变扭曲函数wave_distortion,接着创建了一个新的空白图像,并在循环中扭曲了原始图像的每个像素。最后,保存和显示了扭曲后的图像。您可以调整amplitudefrequency参数来控制波浪形变扭曲的效果。

0