裁切图像中心部分的最佳方法是什么?

时间:2019-08-22 11:20:45

标签: python opencv image-processing python-imaging-library

我目前有一个正方形图像,我想将其用作576x576尺寸的ResNet50的输入,并且正在尝试仅使该图像的中心正方形。换句话说,在图像中心周围切出边框。是否可以通过仅定义切出的宽度(以像素为单位)来做到这一点?

3 个答案:

答案 0 :(得分:0)

例如,您可以执行以下操作:

import numpy as np
start_width = 576
center_width = 100

start_image = np.random.rand(start_width,start_width,3)
# With open CV:
# start_image = cv2.imread("your_file",mode='RGB')
# start_width = start_image.shape[0]
center_image_start_idx = int((start_width-center_width)/2)

center_image = start_image[
        center_image_start_idx:(center_image_start_idx+center_width),
        center_image_start_idx:(center_image_start_idx+center_width),:]

print(start_image.shape)
print(center_image.shape)

# Which outputs:
> (576, 576, 3)
> (100, 100, 3)

答案 1 :(得分:0)

from PIL import Image
img = Image.open("ImageName.jpg") # or any format you want
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.save("ImageName2.jpg", "JPEG") # or any format you want, even diifferent than the original format.
cropped_img.show()

这是一种裁剪方法。定义自己的算法来解决您的问题。

答案 2 :(得分:0)

假设new_hnew_w是您的目标高度和宽度。

org_h, org_w, _ = img.shape
crop_img = img[org_h//2 - new_h//2:org_h//2 + new_h, org_w//2 - new_w//2:org_w//2 + new_w,:]