如何按照给定的比例调整图片大小?

3
我有许多不同尺寸的图像文件,但我想将它们全部按照一定比例进行缩放,比如说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),但我找不到一个适合我情况的正确示例。

如果您查看问题,该人使用了OpenCV(cv2)的方法cv2.resize。例如:img2 = cv2.resize(img, (new_w, new_h)) - Scratch'N'Purr
2个回答

3
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')

你选择了PIL - Image.ANTIALIAS是传递给resize函数的一个参数,会导致图像模糊。请参考PIL.Image.Image.resize以及你可以使用的选项。建议使用PIL.Image.BICUBIC或者PIL.Image.LANCZOS代替。 - Patrick Artner
你能否编辑我的答案,使其更简单一些,然后将其发布为你的答案,并让我接受它?先行致谢。 - Jess
不,自己试试吧 ;) 48小时后你可以选择自己的答案作为解决方案。 - Patrick Artner
太晚了 :). 再次感谢。 - Jess

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)

您应该添加一些错误处理,例如:
  • 给定路径中没有图像
  • 图像不可读(文件路径权限)
  • 图像不可写(文件路径权限)

在我回答这个问题的时间里,我已经写出了我的解决方案,但是由于你付出的努力,我会接受你的答案。然而,结果图片很模糊,这正常吗?能修复吗?请参考我下面的答案。 - Jess

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接