Connect new point to the previous point on a image with a straight line in OpenCV-Python

In OpenCV-Python, we can draw lines between points on an image to create paths, track movements, or create interactive drawing applications. This is particularly useful for computer vision applications where user interaction is required.

OpenCV (Open Source Computer Vision Library) provides powerful functions for image manipulation and computer vision tasks. In this article, we will learn how to connect mouse-clicked points on an image with straight lines using OpenCV-Python.

Understanding the cv2.line() Function

To draw a straight line between two points, OpenCV provides the cv2.line() function with the following syntax:

cv2.line(image, start_point, end_point, color, thickness)

Parameters:

  • image: The image on which to draw the line
  • start_point: Starting coordinates (x, y)
  • end_point: Ending coordinates (x, y)
  • color: Line color in BGR format
  • thickness: Line thickness in pixels

Complete Implementation

Here's a complete example that demonstrates connecting clicked points with straight lines:

import cv2
import numpy as np

# Create a sample image (you can also use cv2.imread('your_image.jpg'))
img = np.ones((400, 600, 3), dtype=np.uint8) * 255  # White canvas

# List to store all clicked points
points = []

def mouse_callback(event, x, y, flags, param):
    """Callback function to handle mouse events"""
    if event == cv2.EVENT_LBUTTONDOWN:
        # Add the clicked point to our list
        points.append((x, y))
        
        # Draw a small circle at the clicked point
        cv2.circle(img, (x, y), 3, (0, 255, 0), -1)  # Green circle
        
        # If we have at least 2 points, draw a line between the last two
        if len(points) >= 2:
            cv2.line(img, points[-2], points[-1], (255, 0, 0), 2)  # Blue line
        
        # Display the updated image
        cv2.imshow('Connect Points', img)

# Display the initial image
cv2.imshow('Connect Points', img)

# Set the mouse callback function
cv2.setMouseCallback('Connect Points', mouse_callback)

print("Click on the image to draw connected lines. Press any key to exit.")

# Wait for user input
cv2.waitKey(0)
cv2.destroyAllWindows()

How It Works

The implementation follows these key steps:

  1. Initialize: Create an image canvas and empty points list
  2. Mouse Callback: Define a function that responds to left mouse clicks
  3. Point Storage: Store each clicked coordinate in the points list
  4. Visual Feedback: Draw circles at clicked points for visual confirmation
  5. Line Drawing: Connect the current point to the previous point using cv2.line()
  6. Display Update: Refresh the image display after each click

Enhanced Version with Clear Functionality

Here's an enhanced version that includes a clear function and better visual feedback:

import cv2
import numpy as np

# Create a white canvas
img = np.ones((400, 600, 3), dtype=np.uint8) * 255
original_img = img.copy()
points = []

def mouse_callback(event, x, y, flags, param):
    global img, points
    
    if event == cv2.EVENT_LBUTTONDOWN:
        points.append((x, y))
        
        # Draw point marker
        cv2.circle(img, (x, y), 4, (0, 255, 0), -1)
        cv2.circle(img, (x, y), 6, (0, 0, 0), 1)
        
        # Draw line to previous point
        if len(points) >= 2:
            cv2.line(img, points[-2], points[-1], (255, 0, 0), 2)
        
        cv2.imshow('Line Drawing', img)
    
    elif event == cv2.EVENT_RBUTTONDOWN:
        # Right click to clear
        img = original_img.copy()
        points = []
        cv2.imshow('Line Drawing', img)

# Setup window and callback
cv2.imshow('Line Drawing', img)
cv2.setMouseCallback('Line Drawing', mouse_callback)

print("Left click: Add point and draw line")
print("Right click: Clear all")
print("Press any key to exit")

cv2.waitKey(0)
cv2.destroyAllWindows()

Key Features

  • Interactive Drawing: Click anywhere to add points and connect them
  • Visual Feedback: Green circles mark clicked points
  • Progressive Lines: Each new point connects to the previous one
  • Clear Function: Right-click to reset the canvas

Common Applications

Application Description Use Case
Path Tracking Track movement trajectories Object tracking, route planning
Interactive Drawing Create drawing applications Digital sketching, annotations
Region Marking Mark areas of interest Image analysis, measurements

Conclusion

Using OpenCV's cv2.line() function with mouse callbacks enables interactive line drawing between points. This technique is fundamental for creating drawing applications, tracking systems, and interactive image analysis tools in computer vision projects.

Updated on: 2026-03-27T01:28:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements