Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crop center portion of a numpy image

Let's say I have a numpy image of some width x and height y. I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?

like image 363
Gert Gottschalk Avatar asked Sep 08 '16 04:09

Gert Gottschalk


People also ask

How do I crop an image in OpenCV?

There is no specific function for cropping using OpenCV, NumPy array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped. And it's done!


1 Answers

Something along these lines -

def crop_center(img,cropx,cropy):     y,x = img.shape     startx = x//2-(cropx//2)     starty = y//2-(cropy//2)         return img[starty:starty+cropy,startx:startx+cropx] 

Sample run -

In [45]: img Out[45]:  array([[88, 93, 42, 25, 36, 14, 59, 46, 77, 13, 52, 58],        [43, 47, 40, 48, 23, 74, 12, 33, 58, 93, 87, 87],        [54, 75, 79, 21, 15, 44, 51, 68, 28, 94, 78, 48],        [57, 46, 14, 98, 43, 76, 86, 56, 86, 88, 96, 49],        [52, 83, 13, 18, 40, 33, 11, 87, 38, 74, 23, 88],        [81, 28, 86, 89, 16, 28, 66, 67, 80, 23, 95, 98],        [46, 30, 18, 31, 73, 15, 90, 77, 71, 57, 61, 78],        [33, 58, 20, 11, 80, 25, 96, 80, 27, 40, 66, 92],        [13, 59, 77, 53, 91, 16, 47, 79, 33, 78, 25, 66],        [22, 80, 40, 24, 17, 85, 20, 70, 81, 68, 50, 80]])  In [46]: crop_center(img,4,6) Out[46]:  array([[15, 44, 51, 68],        [43, 76, 86, 56],        [40, 33, 11, 87],        [16, 28, 66, 67],        [73, 15, 90, 77],        [80, 25, 96, 80]]) 
like image 149
Divakar Avatar answered Sep 23 '22 10:09

Divakar