cv2.rectangle: TypeError: Argument given by name ('thickness') and position (4)
Asked Answered
C

5

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.

Confidential answered 6/5, 2019 at 18:55 Comment(2)
can you print(type(thickness) and print(thickness) so we can trace what's going on?Simile
Added them as constants, but you can see in my solution that the traceback is super misleading!Confidential
C
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.

Confidential answered 6/5, 2019 at 18:55 Comment(0)
B
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)
Brockman answered 6/9, 2020 at 23:12 Comment(0)
R
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..

Recollected answered 25/10, 2022 at 1:59 Comment(0)
W
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.

Warehouseman answered 28/4, 2021 at 3:14 Comment(0)
C
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)
Checklist answered 14/5, 2021 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.