在这个实例中,我们将使用Python的PIL库(Pillow库)来添加滤镜效果并修改图像的外观。请确保你已经安装了Pillow库。如果没有安装,可以通过以下命令来安装:
bash Copy code pip install pillow 下面是一个简单的图片滤镜应用的Python程序,我们将使用PIL库来实现滤镜效果:
python Copy code from PIL import Image, ImageFilter
def apply_filter(image_path, filter_name): try: image = Image.open(image_path) filtered_image = None
if filter_name == "BLUR":
filtered_image = image.filter(ImageFilter.BLUR)
elif filter_name == "CONTOUR":
filtered_image = image.filter(ImageFilter.CONTOUR)
elif filter_name == "DETAIL":
filtered_image = image.filter(ImageFilter.DETAIL)
elif filter_name == "EMBOSS":
filtered_image = image.filter(ImageFilter.EMBOSS)
elif filter_name == "SHARPEN":
filtered_image = image.filter(ImageFilter.SHARPEN)
else:
print("无效的滤镜名称。")
return
filtered_image.show()
filtered_image.save(f"filtered_{filter_name.lower()}.png")
print(f"滤镜 '{filter_name}' 已应用并保存为 filtered_{filter_name.lower()}.png。")
except IOError:
print("无法打开图像文件。")
if name == "main": image_path = "example.jpg" # 要应用滤镜的图像文件路径 filter_name = "DETAIL" # 滤镜名称:BLUR, CONTOUR, DETAIL, EMBOSS, SHARPEN
apply_filter(image_path, filter_name)
在上述代码中,我们定义了apply_filter函数,它接受图像文件路径和滤镜名称作为参数。根据滤镜名称,我们使用PIL库的filter方法应用相应的滤镜效果,并显示处理后的图像。处理后的图像也将保存在当前工作目录下,文件名以"filtered_滤镜名称.png"的形式命名。
你需要将image_path变量替换为要处理的图像文件路径,并将filter_name变量替换为你想要的滤镜效果名称。运行程序后,滤镜效果将应用于图像,并且处理后的图像将显示出来。
请注意,滤镜名称不区分大小写,可以使用"DETAIL"或"detail"都是一样的效果。可以尝试不同的滤镜名称来观察图像的不同外观。