Apply cv2.boundingRect on np.array

风格不统一 提交于 2021-01-29 02:39:15

问题


How to apply cv2.boundingRect to a np.array of points ?
The following code produces an error.

points = np.array([[1, 2], [3, 4]], dtype=np.float32)
import cv2
cv2.boundingRect(points)

Error:

OpenCV Error: Unsupported format or combination of formats (The image/matrix format is not supported by the function) in cvBoundingRect, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/shapedescr.cpp, line 97

File "<ipython-input-23-42e84e11f1a7>", line 1, in <module>
  cv2.boundingRect(points)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/shapedescr.cpp:970: error: (-210) The image/matrix format is not supported by the function in function cvBoundingRect

回答1:


The Python bindings of the 2.x versions of OpenCV use slightly different representation of some data than the ones in 3.x.

From existing code samples (e.g. this answer on SO), we can see that we can call cv2.boundingRect with a en element of the list of contours returned by cv2.findContours. Let's have a look what that looks like:

>>> a = cv2.copyMakeBorder(np.ones((3,3), np.uint8),1,1,1,1,0)
>>> b,c = cv2.findContours(a, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
>>> b[0]
array([[[1, 1]],

       [[1, 3]],

       [[3, 3]],

       [[3, 1]]])

We can see that each point in the contour is represented as [[x, y]] and we have a list of those.

Hence

import numpy as np
import cv2

point1 = [[1,2]]
point2 = [[3,4]]

points = np.array([point1, point2], np.float32)

print cv2.boundingRect(points)

And we get the output

(1, 2, 3, 3)


来源:https://stackoverflow.com/questions/40498336/apply-cv2-boundingrect-on-np-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!