在Python PIL中用可设置的中心和比例来裁剪图像

1 人关注

我想用PIL来裁剪图片,尽管它可能是其他的模块。 我需要用一个比例系数来裁剪,即1.5意味着输出是1.5倍的放大。 此外,我还需要设置它放大的中心点。这意味着设置x/2,y/2为中心将直接放大到中心,但其他x,y值将放大到这些像素。

如果有人知道如何做到这一点,我将非常感谢任何帮助。

现在我用ims = im.crop((int((x-x/i)/2), int((y-y/i)/2), int((x+(x/i))/2), int((y+(y/i))/2))进行了一些剪裁。) 但这只能放大到中心,而且 "i "并不能提供一个好的比例系数。

再次感谢您的帮助。

python
image
zooming
python-imaging-library
crop
Michael Dombrowski
Michael Dombrowski
发布于 2015-06-15
1 个回答
physicalattraction
physicalattraction
发布于 2015-06-20
已采纳
0 人赞同

这只是一个正确掌握中心和尺寸的问题。

  • Determine the center of the spot where you want to crop
  • Determine the new size using the scale factor
  • Determine the bounding box of the cropped image
  • The following script should do the trick.

    import os.path
    from PIL import Image
    def get_img_dir():
        src_dir = os.path.dirname(__file__)
        img_dir = os.path.join(src_dir, '..', 'img')
        return img_dir
    def open_img():
        img_dir = get_img_dir()
        img_name = 'amsterdam.jpg'
        full_img_path = os.path.join(img_dir, img_name)
        img = Image.open(full_img_path)
        return img
    def crop_image(img, xy, scale_factor):
        '''Crop the image around the tuple xy
        Inputs:
        -------
        img: Image opened with PIL.Image
        xy: tuple with relative (x,y) position of the center of the cropped image
            x and y shall be between 0 and 1
        scale_factor: the ratio between the original image's size and the cropped image's size
        center = (img.size[0] * xy[0], img.size[1] * xy[1])
        new_size = (img.size[0] / scale_factor, img.size[1] / scale_factor)
        left = max (0, (int) (center[0] - new_size[0] / 2))
        right = min (img.size[0], (int) (center[0] + new_size[0] / 2))
        upper = max (0, (int) (center[1] - new_size[1] / 2))
        lower = min (img.size[1], (int) (center[1] + new_size[1] / 2))
        cropped_img = img.crop((left, upper, right, lower))
        return cropped_img
    def save_img(img, img_name):
        img_dir = get_img_dir()
        full_img_path = os.path.join(img_dir, img_name)
        img.save(full_img_path)
    if __name__ == '__main__':
        ams = open_img()
        crop_ams = crop_image(ams, (0.50, 0.50), 0.95)
        save_img(crop_ams, 'crop_amsterdam_01.jpg')
        crop_ams = crop_image(ams, (0.25, 0.25), 2.5)
        save_img(crop_ams, 'crop_amsterdam_02.jpg')
        crop_ams = crop_image(ams, (0.75, 0.45), 3.5)
        save_img(crop_ams, 'crop_amsterdam_03.jpg')
    

    原始图像。

    crop_amsterdam_01.jpg。