How to Draw Rectangle in OpenCV for Computer Vision
Use the
cv2.rectangle() function in OpenCV to draw a rectangle on an image by specifying the image, top-left and bottom-right corner points, color, and thickness. This function modifies the image in place and is commonly used for highlighting regions in computer vision tasks.Syntax
The cv2.rectangle() function draws a rectangle on an image. It requires the image, two corner points, color, and thickness as inputs.
- img: The image where the rectangle will be drawn.
- pt1: Top-left corner of the rectangle (x, y).
- pt2: Bottom-right corner of the rectangle (x, y).
- color: Rectangle color in BGR format (e.g., (255, 0, 0) for blue).
- thickness: Thickness of the rectangle border in pixels. Use
-1to fill the rectangle.
python
cv2.rectangle(img, pt1, pt2, color, thickness)
Example
This example loads a blank image, draws a blue rectangle with a thickness of 3 pixels, and displays the result.
python
import cv2 import numpy as np # Create a black image 400x400 pixels img = np.zeros((400, 400, 3), dtype=np.uint8) # Define top-left and bottom-right points pt1 = (50, 50) pt2 = (300, 300) # Define color (Blue in BGR) color = (255, 0, 0) # Draw rectangle with thickness 3 cv2.rectangle(img, pt1, pt2, color, 3) # Show the image in a window cv2.imshow('Rectangle', img) cv2.waitKey(0) cv2.destroyAllWindows()
Output
A window opens displaying a black image with a blue rectangle drawn from (50, 50) to (300, 300) with a border thickness of 3 pixels.
Common Pitfalls
- Using incorrect point coordinates can draw the rectangle outside the image or inverted.
- For color, OpenCV uses BGR, not RGB, so colors may appear swapped if misunderstood.
- Setting thickness to 0 will not draw anything; use positive integers or -1 to fill.
- Modifying a read-only image or wrong image type can cause errors.
python
import cv2 import numpy as np img = np.zeros((200, 200, 3), dtype=np.uint8) # Wrong: Points inverted (bottom-right first) # cv2.rectangle(img, (150, 150), (50, 50), (0, 255, 0), 2) # This still works but is confusing # Correct: Top-left then bottom-right cv2.rectangle(img, (50, 50), (150, 150), (0, 255, 0), 2)
Quick Reference
Remember these tips when drawing rectangles with OpenCV:
- Points: Always specify top-left then bottom-right corners.
- Color: Use BGR format, not RGB.
- Thickness: Positive integer for border,
-1to fill. - Image: Must be a valid OpenCV image (numpy array).
Key Takeaways
Use cv2.rectangle() with image, two corner points, color in BGR, and thickness to draw rectangles.
Specify points as top-left and bottom-right corners to avoid confusion.
Use thickness=-1 to fill the rectangle instead of just drawing the border.
OpenCV colors use BGR order, so blue is (255, 0, 0), not (0, 0, 255).
Always ensure the image is a valid numpy array before drawing.