13

I am trying to visualize bounding boxes on top of an image.

My Code:

color = (255, 255, 0)
thickness = 4
x_min, y_min, x_max, y_max = bbox
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, thickness=thickness)

and I get TypeError: Argument given by name ('thickness') and position (4) Even if I pass thickness positionally, I get a different traceback:

cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, thickness)

raises TypeError: expected a tuple.

Sam Shleifer
  • 1,716
  • 2
  • 18
  • 29

5 Answers5

17

You need to make sure your bounding coordinates are integers.

x_min, y_min, x_max, y_max = map(int, bbox)
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, thickness)

Either invocation of cv2.rectangle will work.

Sam Shleifer
  • 1,716
  • 2
  • 18
  • 29
5

I got this error when passing the coordinate points as lists like:

start_point = [0, 0]
end_point = [10, 10]
cv2.rectangle(image, start_point, end_point, color, thickness=1)

Passing them as tuples solved the problem:

cv2.rectangle(image, tuple(start_point), tuple(end_point), color, thickness=1)
Pablo Guerrero
  • 936
  • 1
  • 12
  • 22
1

Sometimes the reason of errors related to OpenCV is that your image (numpy array) is not contiguous in memory. Please try again with your image made explicitly contiguous :

img = np.ascontiguousarray(img)

Images tend to be not contiguous when you have performed some manipulations on images such as slicing, changing RGB order, etc..

Toru Kikuchi
  • 332
  • 4
  • 4
0

there is no need to declare thickness, you can just give the number directly, for example

cv2.rectangle(img, (0, 0), (250, 250), 3)

Here 3 represents thickness and also there is no need of colons for img name.

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41
0

I got this same error when trying to draw bounding boxes on an image using a variable to set the color of the bounding box like this:

bbox_color = (id, id, id)
cv2.rectangle(img, (x1, y1), (x2, y2), bbox_color, thickness=1)

I suppose the error is because of the type mismatch in the color argument. It should be of type <class 'int'> but in my case, it was of type <numpy.int64>.

This can be fixed by transforming every element to the correct type like this:

bbox_color = (id, id, id)
bbox_color = [int(c) for c in bbox_color]
cv2.rectangle(img, (x1, y1), (x2, y2), bbox_color, thickness=1)