How to Draw Line in OpenCV for Computer Vision
To draw a line in OpenCV, use the
cv2.line() function by specifying the image, start and end points, color, and thickness. This function modifies the image by adding a straight line between the given points.Syntax
The cv2.line() function draws a line on an image. It requires the image to draw on, the start and end points of the line, the color, and the thickness.
- img: The image where the line will be drawn.
- pt1: Starting point of the line (x, y).
- pt2: Ending point of the line (x, y).
- color: Line color in BGR format (e.g., (255, 0, 0) for blue).
- thickness: Thickness of the line in pixels.
python
cv2.line(img, pt1, pt2, color, thickness)
Example
This example creates a black image and draws a blue line from the top-left corner to the bottom-right corner with thickness 3 pixels.
python
import cv2 import numpy as np # Create a black image 400x400 pixels img = np.zeros((400, 400, 3), dtype=np.uint8) # Draw a blue line from (0,0) to (399,399) with thickness 3 cv2.line(img, (0, 0), (399, 399), (255, 0, 0), 3) # Save the image to file cv2.imwrite('line_example.png', img)
Output
A 400x400 black image with a blue diagonal line saved as 'line_example.png'.
Common Pitfalls
Common mistakes when drawing lines in OpenCV include:
- Using the wrong color format (OpenCV uses BGR, not RGB).
- Specifying points outside the image boundaries, which will not draw anything.
- Forgetting that thickness must be a positive integer; zero or negative values are invalid.
- Not modifying the original image or not saving/showing the result after drawing.
python
import cv2 import numpy as np img = np.zeros((100, 100, 3), dtype=np.uint8) # Wrong color format (RGB instead of BGR) - line will be red instead of blue cv2.line(img, (10, 10), (90, 90), (255, 0, 0), 2) # Actually draws blue line # Correct color format (BGR) for blue cv2.line(img, (10, 10), (90, 90), (255, 0, 0), 2)
Quick Reference
- cv2.line(img, pt1, pt2, color, thickness): Draws a line on
img. - Color format: Use BGR tuples, e.g., (0, 255, 0) for green.
- Points: Must be inside image dimensions.
- Thickness: Positive integer, default is 1.
Key Takeaways
Use cv2.line() with image, start/end points, color in BGR, and thickness to draw lines.
Always check that points are inside the image to see the line.
Remember OpenCV uses BGR color format, not RGB.
Thickness must be a positive integer to draw visible lines.
Save or display the image after drawing to see the result.