Rectangle Not Showing up in Opencv

Why is rectangle not showing up in my code?

import cv2

im = cv2.imread('players.bmp')

#im.shape >>returns (765,1365,3)

cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.imshow('image', im)
cv2.waitKey(0)
cv2.destroyAllWindows()

3 Answers

It does not show the rectangle, because you are drawing it outside the image.

Why? you may be asking. It is simple. You have this:

#im.shape >>returns (765,1365,3)

This means

rows/height = 765
cols/width = 1365
channels = 3

Then you do

cv2.rectangle(im, (64,1248), (191,1311), (0,255,0), 2)

Here you use 2 points which are tuples (x,y), but you are writing them as if they where tuples (y,x). I know that OpenCV uses in a lot of functions the order (y,x), but this is due that they see the image as a matrix, which commonly is accessed with (row, column) which translates to (y,x). In the case of this rectangle they require which are expressed in the typical Cartesian way (x,y).

In conclusion, just change it to:

cv2.rectangle(im, (1248, 64), (1311, 191), (0,255,0), 2)

And it should work.

2

I had a completely different cause for the issue

for me it wasn't showing up because I was using a numpy view from the image, so instead of using cv2.cvtColor(frame, cv2.COLOR_RGB2BGR), I instead used frame[..., ::-1] to convert RGB and BGR.

Somehow this makes the result immutable and when cv2.rectangle tries to write to it, it just doesn't get changed.

1

I stumbled upon this question while facing the same problem. In my case, I was correctly passing x and y along with x+w and y+h. I had made 2 mistakes though:

  • I had this part in a try and except block (so I couldn't see the exception being raised)
  • My code was changing h to an array prior to me drawing the rectangle. (I had extracted the values of x,y,w,h from x,y,w,h = cv2.boundingRect(cnt) before mistakenly changing h to [1,-1,-1,-1])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest