Thursday, 16 November 2023

Creating Rectangles with OpenCV: A Comprehensive Guide

Using cv2.rectangle() method, we can draw rectangle shapes on images or video frames.

 

Signature

cv2.rectangle(image, pt1, pt2, color, thickness, lineType, shift)

 

Below table summarizes the parameters of rectangle method.

 

Parameter

Description

image

Specifies the image or shape on which you want to draw the shape.

pt1

It is a tuple (x, y), specifies the top left corner of the rectangle.

pt2

It is a tuple (x, y), specifies the bottom right corner of the rectangle.

color

Specifies color of the rectangle. It can be a tuple representing the BGR (Blue, Green, Red) color values.

thickness

Specifies the thickness of the rectangle. If you pass any negative value to it, then OpenCV fill the rectangle. You can even use the constant ‘cv.FILLED’ to fill the rectangle with given color.

lineType

Specifies the line type while drawing the rectangle.

 

Ex: cv2.LINE_8

shift

Specifies the number of fractional bits in the vertex coordinates.

 

 

rectangle.py

import cv2 as cv
import numpy as np

# Create a blank image
image = np.zeros((800, 1200, 3), dtype=np.uint8)
image[:] = [220, 220, 220]

# rectangle with red color
# color is in (b, g, r) formant
cv.rectangle(image, (100, 200), (300, 500), (0, 0, 255), thickness=2)

# fill the rectangle
cv.rectangle(image, (500, 200), (700, 500), (0, 255, 0), thickness=-2)

# fill the rectangle
cv.rectangle(image, (900, 200), (1100, 500), (255, 0, 0), thickness=cv.FILLED, lineType=cv.LINE_4)

# Display the image
cv.imshow('Rectangle Image', image)
cv.waitKey(0)
cv.destroyAllWindows()

 

Output

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment