如何以一定比例调整图像大小?

时间:2018-04-05 08:08:44

标签: python python-3.x image opencv image-processing

我的目录中有很多不同大小的图像,但是我希望按照一定比例调整它们的大小,比如0.25或0.2,它应该是我可以从我的代码控制的变量,我希望得到的图像到是另一个目录中的输出。

我研究了上一个问题How to resize an image in python, while retaining aspect ratio, given a target size?

提供的这种方法
Here is my approach,

aspectRatio = currentWidth / currentHeight
heigth * width = area
So,

height * (height * aspectRatio) = area
height² = area / aspectRatio
height = sqrt(area / aspectRatio)
At that point we know the target height, and width = height * aspectRatio.

Ex:

area = 100 000
height = sqrt(100 000 / (700/979)) = 373.974
width = 373.974 * (700/979) = 267.397

但它缺少很多细节,例如:如何将这些尺寸转换回图像上使用的库等等。

编辑查看更多文档 img.resize 看起来很理想(虽然我也注意到.thumbnail)但是我找不到像这样的案例的正确例子矿。

2 个答案:

答案 0 :(得分:1)

您可以创建自己的小程序来调整大小和重新保存图片:

import cv2

def resize(oldPath,newPath,factor): 
    """Resize image on 'oldPath' in both dimensions by the same 'factor'. 
    Store as 'newPath'."""
    def r(image,f):
        """Resize 'image' by 'f' in both dimensions."""
        newDim = (int(f*image.shape[0]),int(f*image.shape[1]))
        return cv2.resize(image, newDim, interpolation = cv2.INTER_AREA)

    cv2.imwrite(newPath, r(cv2.imread(oldPath), factor)) 

并按照这样测试:

# load and resize (local) pic, save as new file (adapt paths to your system)
resize(r'C:\Pictures\2015-08-05 10.58.36.jpg',r'C:\Pictures\mod.jpg',0.4)
# show openened modified image
cv2.imshow("...",cv2.imread(r'C:\Users\partner\Pictures\mod.jpg'))
# wait for keypress for diplay to close
cv2.waitKey(0)

你应该添加一些错误处理,例如:

  • 在给定路径上没有图像
  • 图片不可读(文件路径权限)
  • 图片不可写(文件路径权限)

答案 1 :(得分:1)

from PIL import Image


ratio = 0.2
img = Image.open('/home/user/Desktop/test_pic/1-0.png')
hsize = int((float(img.size[1])*float(ratio)))
wsize = int((float(img.size[0])*float(ratio)))
img = img.resize((wsize,hsize), Image.ANTIALIAS)
img.save('/home/user/Desktop/test_pic/change.png')