实现图像水平翻转的Python代码片段:使用HorizontalFlip()函数
发布时间:2024-01-19 12:30:03
以下是实现图像水平翻转的Python代码片段:
from PIL import Image
def horizontal_flip(image_path):
# 打开图像
image = Image.open(image_path)
# 水平翻转图像
flipped_image = image.transpose(Image.FLIP_LEFT_RIGHT)
# 显示翻转后的图像
flipped_image.show()
# 保存翻转后的图像
flipped_image.save("flipped_image.jpg")
# 使用例子
image_path = "example.jpg"
horizontal_flip(image_path)
上述代码片段使用PIL库打开指定路径的图像,然后调用transpose()函数来进行水平翻转。Image.FLIP_LEFT_RIGHT参数表示将图像从左到右水平翻转。接着,使用show()函数来显示翻转后的图像,并使用save()函数将翻转后的图像保存为flipped_image.jpg。
要使用此代码片段,您需要安装PIL库,可以使用以下命令安装:
pip install pillow
请确保将上述代码片段中的example.jpg替换为您自己要水平翻转的图像的路径。
