'opencv draw rectangle function behaves different in C++ , python
I am getting bounding boxes from Yolo implementation in C++, the detected bounding boxes draws correctly using cv::Rectangle function in C++, but when drawed same bounding box coordinates in python it's localising objects incorrectly,
C++ cv::Rectangle function output,
Python cv2.rectangle method output,
I also made sure that the aspect ratio for both the input image is same for python and C++, in order to utilise(draw) detected bounded boxes in python i first dumped it to json file from the c++ detection module(yolo), and then read and rendered in separate python script just to render image and show bounding boxes using cv2.Rectangle
Solution 1:[1]
I came to conclusion that, cv::Rectangle function takes , offset values for width and height arguments , so suppose
rect = cv::Rect(x,y,w_offset,h_offset)
cv::rectangle(img, rect, cv::Scalar(0x27, 0xC1, 0x36), 2);
c++ implementation for cv::rectangle function internally manages offset values with there respective ending (x,y) bounding box coordinates, but for python based implementation offset values needs to be explicitly sum up with starting (x,y) values of the bounding boxes,
c1, c2 = (x ,y), ((x+w_offset), (y+h_offset))
cv2.rectangle(img, c1, c2, (0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
Solution 2:[2]
For record. I faced the very same problem and the solution was to use Scaler(0,255,255) I was using wrong value.
bbox_2d = cv::selectROI(frame, false);
// Display bounding box.
cv::rectangle(frame, bbox_2d, cv::Scalar( 0,255,255 ), 2, 1 );
cv::imshow("Tracking", frame);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | U.Swap |
| Solution 2 | M.Hefny |


