We can draw shapes like Circle and Rectangle using OpenCV easily by just providing basic details. Opencv is easy to use and can easily draw different shapes on images with just one line of code. In this tutorial we will draw circle and rectangle using opencv on images.
To draw circle on image, we will use cv2.circle() method. There are some arguments we need to provide while calling this method.
- Circle Center coordinates represented as (x,y)
- Radius of circle in pixels
- Color of circle border in RGB Format
- Line Thickness(If want to fill circle with color, set to -1)
- Line Type
Now we read an image file and draw circle using cv2 method.
import cv2 image = cv2.imread("images/bike-gta.png") # circle center coordinates coordinates = (652, 245) # radius of circle radius = 100 # color, thickness and line type color = (0, 255, 0) thickness = 2 linetype = cv2.LINE_AA # draw circle on image image = cv2.circle(image, coordinates, radius, color, thickness, linetype) # show image cv2.imshow("Circle Image", image) cv2.waitKey(0) cv2.destroyAllWindows()
Now it draws circle with specified radius on these coordinates with 2 pixel thickness.
It we want to fill circle with the color we provided we can chang thickness variable to
thickness = -1. Remaining code will be the same.
thickness = -1 image = cv2.circle(image, coordinates, radius, color, thickness)
To draw rectangle on image, we can use cv2.rectangle() method for drawing any rectangle. It access two points as top left and bottom right point to draw rectangle on image. All arguments that we pass to method are as follows.
- Top Left coordinates as (xmin, ymin)
- Bottom RIght coordinates as (xmax, ymax)
- Color of Line as RGB
- Thickness of line
- Line Type
We can draw line as follows.
import cv2 image = cv2.imread("images/bike-gta.png") # rectangle coordinates xmin, ymin = (546, 175) xmax, ymax = (765, 330) # color, thickness and line type color = (0, 255, 0) thickness = 2 # set thickness to -1 to fill rectangle linetype = cv2.LINE_AA # draw circle on image image = cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, thickness, linetype) # show image cv2.imshow("Circle Image", image) cv2.waitKey(0) cv2.destroyAllWindows()
Same as circle, if we set thickness to -1, we can fill area inside rectangle with color provided. For complete details and new features, view cv2 drawing methods documentations.