Search code examples
pythonopencvcomputer-visionobject-detectiondraw

OpenCV: draw a rectangle around a region


How can I use OpenCV in Python to draw rectangles around some regions within an image for object detection purposes?


Solution

  • Use cv2:

    import cv2
    
    cv2.rectangle(img, (x1, y1), (x2, y2), color=(255,0,0), thickness=2)
    
    
    x1,y1 ------
    |          |
    |          |
    |          |
    --------x2,y2
    

    [edit] to append the follow-up questions below:

    cv2.imwrite("my.png",img)
    
    cv2.imshow("lalala", img)
    k = cv2.waitKey(0) # 0==wait forever