在Python中调整图像大小并保持其长宽比
这篇Python文章的目的是解释我们如何在Python中调整一个图像的大小,同时保持它的长宽比。在Python中调整图像大小的方法也将用一个适当的例子程序来描述其用法。
在Python中保持图像的长宽比的同时调整图像的大小
在Python中,你可以在一些预定义包的帮助下调整图像的大小。通过导入这些包并使用重要的函数和方法,你可以在Python中调整图像的大小而不损失其长宽比。
使用Python成像库(PIL)
Python的成像库,PIL
,是一个用于成像的Python库。
脚本的目的是使面向系统的任务自动化。脚本是指你为实际任务编写代码,而不需要编译它。
除了强大的图像处理能力外,PIL
还能够处理各种图像格式(包括BMP、DIB、EPS、GIF、ICO、IM、MSP、PCX、PNG、PPM、SGI、TGA、TIFF、WebP、XBM)和图像模式,如RGB、RGBA、B&W和单色。
此外,PIL
与大多数操作系统兼容,包括Windows、Linux和macOS。
Python的标准GUI库是Tkinter
。当Python与Tkinter
结合时,GUI应用程序可以快速而容易地创建。
通过Tkinter
,你可以以面向对象的方式与Tk GUI
工具包进行交互。我们还从Tkinter
中导入PIL。
假设已经选择了一张图片。尺寸和原始图片如下。
示例代码:
# First, we have to import the modules here
from tkinter import *
from PIL import Image, ImageTk
# Now we are creating the object
root = Tk()
# Here, just reading the Image
image = Image.open("koala.png")
# Here now, using resize() method, resizing the image
resize_originalimage = image.resize((140, 80))
img_1 = ImageTk.PhotoImage(orgnlimg)
# creating, add resize image, and labeling it
label1 = Label(image=img_1)
label1.image = img_1
label1.pack()
#finally, executing the Tkinter
root.mainloop()
输出:
无论图像是显示在屏幕上还是存储在图像文件中,它都是由离散的像素表示的。当图像数据的分辨率与屏幕上的表示不一样时,就会出现混叠效应。
子采样通过平滑数据,然后对平滑数据进行子采样来减少混叠。在这种情况下,使用ANTIALIAS
。
Resampling.LANCZOS
是一种对采样数据进行插值以产生新值的方法。该方法常用于多变量插值,如调整数字图像的大小。
原始图像大小为284 x 606,一旦代码执行,我们也能分辨出原始图像和调整后的图像之间的区别。
示例代码:
#Python Code to resize an image while maintaining the original aspect ratio, using the PIL Methods
import PIL
from PIL import Image
#setting the size of resized image
Imagewidth = 80
Imageheight=100
img_2 = Image.open('bear.jpg')
wpercent = (Imagewidth/float(img_2.size[0]))
hsize = int((float(img_2.size[1])*float(wpercent)))
#img = img.resize((mywidth,hsize), PIL.Image.ANTIALIAS)
img_2 = img_2.resize((Imagewidth,Imageheight), PIL.Image.Resampling.LANCZOS)
img_2.save('resizedImage.jpg')
img_2.show()
以下是原始图片。
输出:
当我们运行代码时,你也可以看到调整后的图片,它被保存在目录中,名称为resizedImage.jpg
。
在Python中通过保持其长宽比来裁剪图片
下面是来自PIL
的调整大小和新大小的方法,裁剪图片而不是调整大小。
示例代码:
# Importing Image class from PIL module by maintaining its aspect ratio
from PIL import Image
# Opens an image in RGB mode
#For the external path, we use this :
#img_3 = Image.open(r"Image Path of the Original Image")
#For internal path
img_3 = Image.open("cat.png")
# The size of the image in pixels (size of the original image)
# (This is not mandatory)
width, height = img_3.size
# Setting the cropped image points
left = 4
top = height / 5
right = 154
bottom = 3 * height / 5
# Cropped image of the above dimension
# (It will not change the original image)
img_3 = img_3.crop((left, top, right, bottom))
newsize = (300, 300)
img_3 = img_3.resize(newsize)
#img_3=img_3.save(newsize)
# Shows the image in the image viewer
img_3.show()
下面是原始图片。
输出:
由于我们看到裁剪后的图片是代码的输出,我们可以认为PIL
,不仅仅是通过保持图片的长宽比来调整图片的大小,也可以用于裁剪。
通过Python,我们使用Image.open
,用PIL
来调整图像的大小和读取图像,并保持其长宽比。在计算了新的宽度和高度之后,我们使用调整大小的方法调整了图像的大小,并根据新的宽度使用同样的方法保存了新的图像。
希望这篇文章对你了解如何在Python中调整图像大小有所帮助。