How to crop OpenCV Image from center

Question:

How can I crop an image using OpenCV from the center?

I think it has something to do with this line, but if there is a better way please inform me.

crop_img = img[y:y+h, x:x+w]
Asked By: Juicestus

||

Answers:

The line you provided crops the image region located at (x,y) with (w,h) width and height. Not sure if this is around the center of the image.

To crop (w,h) region around the center you have to do the following:

center = image.shape / 2
x = center[1] - w/2
y = center[0] - h/2

and only then

crop_img = img[y:y+h, x:x+w]
Answered By: lenik

Just an additional comment for the Lenik’s answer (It is the first time I want to contribute in StackOverflow and don’t have enough reputation to comment the answer), you need to be sure x and y are integers.

Probably in this case x and y would always be integers as most of resolutions are even, but is a good practice to keep the values inside an int().

center = image.shape / 2
x = center[1] - w/2
y = center[0] - h/2

crop_img = img[int(y):int(y+h), int(x):int(x+w)]

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.