2017-05-15 55 views
1

我想从原始图像的中心拍摄图像并将其裁剪75%。说实话,我有点不知所措。我曾想过获得原始图像大小如何根据百分比在opencv和python中裁剪图像

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

下面就来仔细想想......想象一些简单的一种简单的方法,但对于图像的任意尺寸在宽度和高度都不同,所以不混淆 - 让我们去200x100像素。现在想象一下你的意思是“裁剪75%”*。现在尝试你的公式,看看他们是否出来正确。 –

+2

如果你想把**的高度**减少75%,你需要从顶部删除37.5%,从底部删除37.5% - 这意味着你的新底部将比老顶部减少62.5%。 –

+2

如果您想将高度**裁剪为** 75%,则需要从顶部删除12.5%,从底部删除12.5%,这意味着您的新底部将比旧顶部减少87.5%。 –

回答

1

一个简单的方法是,首先获得您的缩放的宽度和高度,然后从图像中心到加裁剪/减去经缩放的宽度和高度由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%