如何根据百分比在opencv和python中裁剪图像

时间:2017-05-15 19:34:50

标签: python-2.7 opencv

我想拍摄一张图片并将其从原始图像的中心裁剪75%。说实话,我有点不知所措。我曾想过要获得原始图像尺寸

height, width = image.shape

获取百分比值并进行裁剪:

cropped_y_start = int((height * 0.75))
cropped_y_end = int((height * 0.25))
cropped_x_start = int((width * 0.75))
cropped_x_end = int((width * 0.25))

print cropped_x_start
print cropped_x_end

crop_img = image[cropped_y_start:cropped_y_end, cropped_x_start:cropped_x_end]

这有多个问题,但主要的问题是它不是基于图像的中心。对此有任何建议将非常感激。

1 个答案:

答案 0 :(得分:3)

一种简单的方法是首先获得缩放的宽度和高度,然后从图像中心裁剪到正/负缩放的宽度和高度除以2.
这是一个例子:

import cv2


def crop_img(img, scale=1.0):
    center_x, center_y = img.shape[1] / 2, img.shape[0] / 2
    width_scaled, height_scaled = img.shape[1] * scale, img.shape[0] * scale
    left_x, right_x = center_x - width_scaled / 2, center_x + width_scaled / 2
    top_y, bottom_y = center_y - height_scaled / 2, center_y + height_scaled / 2
    img_cropped = img[int(top_y):int(bottom_y), int(left_x):int(right_x)]
    return img_cropped


img = cv2.imread('lena.jpg')
img_cropped = crop_img(img, 0.75)

输出:
Original
Cropped by 75%