Draw line on Image using OpenCV
In this article, we have presented the technique to Draw line on Image using OpenCV in Python. We have presented the complete Python code example as well.
Table of contents:
- Draw line on Image using OpenCV
- Complete Python Code
Draw line on Image using OpenCV
Load OpenCV and Numpy libraries:
import numpy as np
import cv2
Load an image or create a sample Numpy image for testing:
height = 500
width = 600
channel = 3 # for RGB images
image = np.zeros((height, width, channel), np.uint8)
This will create a black colored image.
To draw a line across an image, we need to set the following information:
- dimension of the left most point of the line (width1, height1)
- dimension of the right most point of the line (width2, height2)
- A straight line will be drawn between the two specified end points
- In OpenCV, we need to specify the font color of the line as BGR and the line thickness (starting from 1). The font color is specified as a triplet. For white, the font color is (255, 255, 255). For black font color, we need to use (0, 0, 0).
- In OpenCV, the line() function is used to draw lines over an image.
Following is the Python code snippet to draw a line over an image using OpenCV:
width1 = 0
height1 = 20
width2 = 600
height2 = 20
fontColor = (255, 255, 255) # white
line_thickness = 1
cv2.line(image, (width1, height1), (width2, height2), fontColor,
thickness=line_thickness)
Complete Python Code
Following is the complete Python code to draw line on Image using OpenCV:
import numpy as np
import cv2
height = 500
width = 600
channel = 3 # for RGB images
image = np.zeros((height, width, channel), np.uint8)
width1 = 0
height1 = 20
width2 = 600
height2 = 20
fontColor = (255, 255, 255) # white
line_thickness = 1
cv2.line(image, (width1, height1), (width2, height2), fontColor,
thickness=line_thickness)
image_filename = "image.jpeg"
image.save(image_filename)
With this article at OpenGenus, you must have the complete idea of how to draw line on Image using OpenCV.