简体   繁体   English

如何从中心裁剪 OpenCV 图像

[英]How to crop OpenCV Image from center

How can I crop an image using cv2 from the center?如何从中心使用 cv2 裁剪图像?

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]

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.只是对 Lenik 答案的附加评论(这是我第一次想在 StackOverflow 中做出贡献并且没有足够的声誉来评论答案),您需要确保 x 和 y 是整数。

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().在这种情况下,x 和 y 可能总是整数,因为大多数分辨率都是偶数,但是将值保留在 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)]

The line you provided crops the image region located at (x,y) with (w,h) width and height.您提供的线以 (w,h) 的宽度和高度裁剪位于 (x,y) 的图像区域。 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:要围绕中心裁剪 (w,h) 区域,您必须执行以下操作:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM