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

Ric*_*ose 2 opencv python-2.7

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

height, width = image.shape
Run Code Online (Sandbox Code Playgroud)

获取百分比值和裁剪:

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]
Run Code Online (Sandbox Code Playgroud)

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

小智 6

一个简单的方法是首先获取缩放后的宽度和高度,然后从图像中心裁剪到加/减缩放后的宽度和高度除以 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)
Run Code Online (Sandbox Code Playgroud)

输出:
原始
裁剪 75%