修改图片的尺寸大小,一般使用PIL和Opencv两个库,都可以达到目标。实现的代码也都非常简单。直接上代码吧。
from PIL import Image
import cv2
def Resize_Pil(img_file_name):
imgFile = Image.open(img_file_name)
print (imgFile.size) # (828, 1471)
newImg = imgFile.resize((1080, 1080), Image.BILINEAR)
newImg.save("output1.jpg")
newImg = imgFile.resize((1080, int( imgFile.size[1]*1080/imgFile.size[0])), Image.BILINEAR)
newImg.save("output2.jpg")
def Resize_cv2(img_file_name):
imgFile = cv2.imread(img_file_name)
print(imgFile.shape) # (1471, 828, 3) 顺序跟pil打印出来不一样
x, y = imgFile.shape[0:2]
newImg = cv2.resize(imgFile,(1080, 1080)) #nd.array格式矩阵
cv2.imwrite("output3.jpg", newImg)
newImg = cv2.resize(imgFile,(int(y*1080/x),1080))
cv2.imwrite("output4.jpg", newImg)
if __name__ == '__main__':
Resize_Pil("example.jpg")
Resize_cv2("example.jpg")

这篇博客展示了如何使用Python的PIL和OpenCV库来调整图像的尺寸。通过`resize`函数,可以轻松将图片转换为指定分辨率,同时保持原始宽高比。示例代码中给出了两种不同的尺寸调整方法,一种是保持原图宽高比,另一种是强制调整到特定尺寸。
597

被折叠的 条评论
为什么被折叠?



