首页 > 编程笔记

Pillow Image图像几何变换操作

图像几何转换的操作主要包括以下几个方面:

1) 改变图像大小

可以使用 resize() 方法改变图像的大小。其法格式如下:

resize((width, height))

2) 旋转图像

可以使用 rotate() 方法旋转图像的角度。其语法格式如下:

 rotate(angle)

3) 颠倒图像

可以使用 transpose() 方法颠倒图像。其语法格式如下:

 transpose(method)

参数 method 可以是 FLIP_LEFT_RIGHT、FLIP_TOP_BOTTOM、ROTATE_90、ROTATE_180 或 ROTATE_270。

下面的示例是创建 4 个图形,从左至右分别是原始图形、使用 rotate() 方法旋转45°、使用 transpose() 方法旋转 90°,以及使用 resize() 方法改变图像大小为原来的1/4。
#图像的几何转换
from tkinter import *
from PIL import Image, ImageTk
#创建主窗口
win = Tk()
win.title(string = "图像的几何转换")
#打开图像文件
path = "D:\\python\\ch14\\"
imgFile1 = Image. open(path + "14.3.gif")
#创建第一个图像实例变量
img1 = ImageTk. PhotoImage (imgFile1)
#创建Label控件,以显示原始图像
label1 = Label (win, width=162, height=160, image= img1)
label1. pack (side=LEFT)
#旋转图像成45
imgFile2 = imgFile1 . rotate(45)
img2 = ImageTk. PhotoImage (imgFile2)
#创建Label控件,以显示图像
label2 = Label (win, width=162, height=160, image=img2)
label2. pack (side=LEFT)
#旋转图像成90°
imgFile3 = imgFile1 . transpose (Image . ROTATE_90)
img3 = ImageTk. PhotoImage (imgFile3)
#创建Label控件,以显示图像
labe13 = Label (win, width=162,height=160,image=img3)
label3. pack (side=LEFT)
#改变图像大小为1 / 4倍
width,height = imgFile1.size
imgFile4 = imgFile1.resize( (int (width/2),int (height/2) ) )
img4 = ImageTk. PhotoImage (imgFile4)
#创建Label控件,以显示原始图像
label4 = Label (win, width=162, height=160, image=img4)
label4.pack (side=LEFT)
#开始程序循环
win . mainloop()
保存并运行程序 demo.py,结果如图 1 所示:

程序运行结果
图1:程序运行结果

优秀文章