Reputation: 77
I want to take an image and crop it by 75% from the center of the original image. To be honest I'm at a bit of a loss on it. I had thought about getting the original image size
height, width = image.shape
getting a percentage value and cropping:
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]
There are multiple problems with this but the main one being its not based off the center of the image. Any advice on this would be much appreciated.
Upvotes: 3
Views: 6953
Reputation: 104
A simple way is to first get your scaled width and height, and then crop from the image center to plus/minus the scaled width and height divided by 2.
Here is an example:
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)
Output:
Original
Cropped by 75%
Upvotes: 9