Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 如何在opencv和python中基于百分比裁剪图像_Python 2.7_Opencv - Fatal编程技术网

Python 2.7 如何在opencv和python中基于百分比裁剪图像

Python 2.7 如何在opencv和python中基于百分比裁剪图像,python-2.7,opencv,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 c

我想拍摄一张图像,从原始图像的中心裁剪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]

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

一个简单的方法是首先获得缩放的宽度和高度,然后从图像中心进行裁剪,使其加/减缩放的宽度和高度除以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)
输出:


这里有一个简单的方法来思考这个问题。。。想象一下你的图像的一些简单但任意的尺寸,宽度和高度是不同的,以免混淆——让我们使用200x100像素。现在想象一下“75%的收成”是什么意思。现在试试你的公式,看看它们是否正确。如果你想将高度裁剪75%,你需要从顶部移除37.5%,从底部移除37.5%——这意味着你的新底部将从旧顶部向下62.5%。如果你想将高度裁剪到75%,你需要从顶部移除12.5%,从底部移除12.5%,这意味着您的新底部将比旧顶部下降87.5%。