pytohn用Pillow和OpenCV修改图片尺寸

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

修改图片的尺寸大小,一般使用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")


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值