使用PIL在中间裁剪图像

2024-04-25 07:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

提出的解决方案的一个潜在问题是,在期望大小和旧大小之间存在奇数差异的情况下。两边不能有半个像素。一个人必须选择一个侧面放置一个额外的像素。

如果水平方向上有一个奇差,下面的代码将把额外的像素放在右边,如果垂直方向上有一个奇差,额外的像素将到达底部。

import numpy as np

def center_crop(img, new_width=None, new_height=None):        

    width = img.shape[1]
    height = img.shape[0]

    if new_width is None:
        new_width = min(width, height)

    if new_height is None:
        new_height = min(width, height)

    left = int(np.ceil((width - new_width) / 2))
    right = width - int(np.floor((width - new_width) / 2))

    top = int(np.ceil((height - new_height) / 2))
    bottom = height - int(np.floor((height - new_height) / 2))

    if len(img.shape) == 2:
        center_cropped_img = img[top:bottom, left:right]
    else:
        center_cropped_img = img[top:bottom, left:right, ...]

    return center_cropped_img

这就是我想要的功能:

from PIL import Image
im = Image.open("test.jpg")

crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)

cropped_im.show()

取自another answer

假设您知道要裁剪到的大小(新宽X新高):

import Image
im = Image.open(<your image>)
width, height = im.size   # Get dimensions

left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2

# Crop the center of the image
im = im.crop((left, top, right, bottom))

如果你试图将一个小图像裁剪得更大,这将被打破,但我假设你不会尝试那样做(或者你可以抓住这个情况而不裁剪图像)。

相关问题 更多 >