babinks93
babinks93

Reputation: 11

cv2.rectangle throws error: (-215:Assertion failed) cn <= 4 in function 'scalarToRawData'

I can't solve this error when I use the cv2.rectangle function to add bboxes to my image. I really don't understand where this error came from.

Here is my code:

for cord in cords:
    
    pt1, pt2 = (cord[0], cord[1]) , (cord[2], cord[3])
    
    pt1 = int(float(pt1[0])), int(float(pt1[1]))
    pt2 = int(float(pt2[0])), int(float(pt2[1]))
    print('pt1 et pt2')
    print(pt1,pt2)
    print(im.shape)
    bgr = (0,0,255)
    im = cv2.rectangle(im, tuple(pt1), tuple(pt2), color=(255,255,0))

This is the result of the output:

pt1 et pt2
(1, 206) (17, 223)
(3, 500, 500)

Thanks for your answers!

Upvotes: 1

Views: 2624

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15576

It's complaining that your passed image has too many channels. It expects four or less. It also expects the color channels to be the third/last dimension, or the image to be grayscale (have no color dimension).

if im.shape == (3, 500, 500), then you've got the dimensions ordered wrong.

OpenCV expects HWC but you have CHW.

Use im = im.transpose((1, 2, 0)) and then you can use OpenCV's drawing functions...

If OpenCV complains after that, you might need to call im = np.ascontiguousarray(im). That's because numpy could transpose using stride tricks (to avoid copying data) but OpenCV cannot model such arrays.

To convert HWC back to CHW, use im = im.transpose((2, 0, 1))

Upvotes: 2

Related Questions