Reputation: 3009
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
Upvotes: 2
Views: 4620
Reputation: 1
points = np.array([[1, 2], [3, 4]], dtype=np.float32)[:,np.newaxis,:]
import cv2
cv2.boundingRect(points)
You just need to add another axis, so the function will know it is a point list and not a 2d array.
Upvotes: 0
Reputation: 19041
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)
Upvotes: 3