Drawing rectangles in OpenCV is primarily achieved using the cv2.rectangle function. This function requires specifying several parameters, including the image, the top-left and bottom-right coordinates of the rectangle, the rectangle's color, and the line thickness.
Here is a basic example of drawing a rectangle using Python and OpenCV:
pythonimport cv2 import numpy as np # Create a black image image = np.zeros((512, 512, 3), np.uint8) # Define the rectangle's top-left and bottom-right coordinates top_left = (100, 100) bottom_right = (400, 400) # Rectangle color using blue in BGR format (Blue, Green, Red) color = (255, 0, 0) # Line thickness; set to -1 to fill the rectangle thickness = 2 # Draw the rectangle using cv2.rectangle() cv2.rectangle(image, top_left, bottom_right, color, thickness) # Display the image cv2.imshow('Image with Rectangle', image) cv2.waitKey(0) cv2.destroyAllWindows()
In this example, we first create a 512x512 pixel black image. Next, we define the rectangle's position based on the top-left and bottom-right coordinates, select blue as the rectangle's color, and set the line thickness to 2. Finally, we use the cv2.rectangle() function to draw the rectangle on the image and display it via cv2.imshow().
This is a fundamental approach for drawing rectangles. You can adjust the color, coordinates, and line thickness as needed, or use thickness=-1 to fill the rectangle. This functionality is highly valuable in image processing tasks, such as annotating objects in images or creating graphical user interface elements.