Draw Rectangle on Image using OpenCV

Draw Rectangle on Image using OpenCV

OpenCV offers functionality for drawing various geometric shapes such as line, rectangle, circle, etc.

The rectangle function can be used to draw a rectangle by specifying x and y coordinates for top-left and bottom-right corner.

Python
C++
Java
import cv2 import numpy as np img = np.zeros((100, 300, 3), dtype=np.uint8) x1, y1 = 50, 20 x2, y2 = 250, 80 color = (0, 255, 0) thickness = 2 cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness) cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows()

Result:

Draw Rectangle on Image using OpenCV

For convenience, the rectangle function also accepts x and y coordinates of the top-left corner and width and height. It is an alternative way to draw a rectangle.

Python
C++
Java
import cv2 import numpy as np img = np.zeros((100, 300, 3), dtype=np.uint8) x, y = 50, 20 w, h = 200, 60 color = (0, 255, 0) thickness = 2 cv2.rectangle(img, (x, y, w, h), color, thickness) cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows()

Leave a Comment

Cancel reply

Your email address will not be published.