2

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
Temak
  • 2,929
  • 36
  • 49
  • I was going to suggest `cv2.boundingRect(cv2.cv.fromarray(points))` but that doesn't seem to work either. returns `TypeError: points is not a numpy array, neither a scalar` – jmunsch Nov 09 '16 at 00:07
  • I tried your code and it gave me the this bounding box without error (1, 2, 3, 3) which seems true. However, my CV version is '3.1.0-dev'. – cagatayodabasi Nov 09 '16 at 07:56

2 Answers2

3

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)
Community
  • 1
  • 1
Dan Mašek
  • 17,852
  • 6
  • 57
  • 85
0
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.