9

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]
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Juicestus
  • 442
  • 1
  • 7
  • 14
  • There is an answer here: https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python – Stefan May 21 '20 at 05:43

2 Answers2

13

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
x = center[1]/2 - w/2
y = center[0]/2 - h/2

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

  • If the values are already always going to be integers this just makes it more confusing. Using `int` on `w/2` and `h/2` might be worth while, but you could also just use floor division with `//` – RedKnite May 21 '20 at 19:45
  • 1
    floor division will still result in floats, if any operand was a float. watching the data types is important in any case. not all situations require `int()` but some do. – Christoph Rackwitz Jul 31 '22 at 17:25
  • 2
    You can't divide tuple (which is returned by image.shape) by a number. – Danil Kononyhin Sep 05 '22 at 13:02
  • Thanks @DanilKononyhin for noticing that. I had made it based on Lenik answer, but I just changed it to make the division after extracting the scalar from the tuple. – Juan Esteban Fonseca Sep 06 '22 at 14:43
3

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]
lenik
  • 23,228
  • 4
  • 34
  • 43