Change language

Python OpenCV cv2.line () method

|

cv2 line

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

Parameters:
image: It is the image on which line is to be drawn.
start_point: It is the starting coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
end_point: It is the ending coordinates of line. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
color: It is the color of line to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
thickness: It is the thickness of the line in px.

Return Value: It returns an image.

Drawing Line

To draw a line, you need to pass in the start and end coordinates of the line. Let’s create a black image and draw a blue line on it from the upper left corner to the lower right corner.

import numpy as np
import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Draw a diagonal blue line with thickness of 5 px
cv2.line(img,(0,0),(511,511),(255,0,0),5)

How to draw a line on an image in OpenCV?

StackOverflow question

If I have the polar coordinates of a line, how can I draw it on an image in OpenCV & python?

Line function takes 2 points, but draws only the segment. I want to draw a line from one edge of the image to other.

Answer

Just calculate for 2 points outside. opencv’s Line is fine with e.g. (-10,-10) for a point.

import cv2  # python-opencv
import numpy as np

width, height = 800, 600
x1, y1 = 0, 0
x2, y2 = 200, 400
image = np.ones((height, width)) * 255

line_thickness = 2
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), thickness=line_thickness)

http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html#cv2.line

Example 1

def __init__(self, line):
        data = line.split(’ ’)
        data[1:] = [float(x) for x in data[1:]]
        self.classname = data[0]
        self.xmin = data[1] 
        self.ymin = data[2]
        self.xmax = data[1]+data[3]
        self.ymax = data[2]+data[4]
        self.box2d = np.array([self.xmin,self.ymin,self.xmax,self.ymax])
        self.centroid = np.array([data[5],data[6],data[7]])
        self.unused_dimension = np.array([data[8],data[9],data[10]])
        self.w = data[8]
        self.l = data[9]
        self.h = data[10]
        self.orientation = np.zeros((3,))
        self.orientation[0] = data[11]
        self.orientation[1] = data[12]
        self.heading_angle = -1 * np.arctan2(self.orientation[1], self.orientation[0]) 

Example 2

def get_curve(self):
        L = 200
        canvas = np.ones((L, L, 3)) * 0.851
        curve_step = 16
        xs = np.linspace(0.0, 1.0, curve_step + 1)[:, None, None]
        xs = np.concatenate([xs] * 3, axis=2)
        ys = self.apply(xs.copy())
        ys = np.clip(ys, 0.01, 1.0)
        for i in range(curve_step):
            for j in range(3):
                x, y = xs[i, 0, j], ys[i, 0, j]
                xx, yy = xs[i + 1, 0, j], ys[i + 1, 0, j]
                color = [0, 0, 0]
                color[j] = 0.7
                color = tuple(color)
                cv2.line(canvas, (int(L * x), int(L - L * y)), (int(L * xx), int(L - L * yy)), color, 1)
        return canvas 

Example 3

def draw_projected_box3d(image, qs, color=(255,255,255), thickness=2):
    ’’’ Draw 3d bounding box in image
        qs: (8,2) array of vertices for the 3d box in following order:
            1 -------- 0
           /|         /|
          2 -------- 3 .
          | |        | |
          . 5 -------- 4
          |/         |/
          6 -------- 7
    ’’’
    qs = qs.astype(np.int32)
    for k in range(0,4):
       #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
       i,j=k,(k+1)%4
       cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.CV_AA) # use LINE_AA for opencv3

       i,j=k+4,(k+1)%4 + 4
       cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.CV_AA)

       i,j=k,k+4
       cv2.line(image, (qs[i,0],qs[i,1]), (qs[j,0],qs[j,1]), color, thickness, cv2.CV_AA)
    return image 

Example 4

def visualize_filter(self, debug_info, canvas):
    curve = debug_info[’filter_parameters’]
    height, width = canvas.shape[:2]
    for i in range(self.channels):
      values = np.array([0] + list(curve[0][0][i]))
      values /= sum(values) + 1e-30
      scale = 1
      values *= scale
      for j in range(0, self.cfg.curve_steps):
        values[j + 1] += values[j]
      for j in range(self.cfg.curve_steps):
        p1 = tuple(
            map(int, (width / self.cfg.curve_steps * j, height - 1 -
                      values[j] * height)))
        p2 = tuple(
            map(int, (width / self.cfg.curve_steps * (j + 1), height - 1 -
                      values[j + 1] * height)))
        color = []
        for t in range(self.channels):
          color.append(1 if t == i else 0)
        cv2.line(canvas, p1, p2, tuple(color), thickness=1) 

Example 5

def update(self, radarData):
        self.img = np.zeros((self.height, self.width, self.channels), np.uint8)
        cv2.line(self.img, (10, 0), (self.width/2 - 5, self.height), (100, 255, 255))
        cv2.line(self.img, (self.width - 10, 0), (self.width/2 + 5, self.height), (100, 255, 255))

        for track_number in range(1, 65):
            if str(track_number)+’_track_range’ in radarData:
                track_range = radarData[str(track_number)+’_track_range’]
                track_angle = (float(radarData[str(track_number)+’_track_angle’])+90.0)*math.pi/180

                x_pos = math.cos(track_angle)*track_range*4
                y_pos = math.sin(track_angle)*track_range*4

                cv2.circle(self.img, (self.width/2 + int(x_pos), self.height - int(y_pos) - 10), 5, (255, 255, 255))
                #cv2.putText(self.img, str(track_number), 
                #    (self.width/2 + int(x_pos)-2, self.height - int(y_pos) - 10), self.font, 1, (255,255,255), 2)

        cv2.imshow("Radar", self.img)
        cv2.waitKey(2) 

Example 6

def update(self, radarData):
        self.img = np.zeros((self.height, self.width, self.channels), np.uint8)
        cv2.line(self.img, (10, 0), (self.width/2 - 5, self.height), (100, 255, 255))
        cv2.line(self.img, (self.width - 10, 0), (self.width/2 + 5, self.height), (100, 255, 255))

        for track_number in range(1, 65):
            if str(track_number)+’_track_range’ in radarData:
                track_range = radarData[str(track_number)+’_track_range’]
                track_angle = (float(radarData[str(track_number)+’_track_angle’])+90.0)*math.pi/180

                x_pos = math.cos(track_angle)*track_range*4
                y_pos = math.sin(track_angle)*track_range*4

                cv2.circle(self.img, (self.width/2 + int(x_pos), self.height - int(y_pos) - 10), 5, (255, 255, 255))
                #cv2.putText(self.img, str(track_number), 
                #    (self.width/2 + int(x_pos)-2, self.height - int(y_pos) - 10), self.font, 1, (255,255,255), 2)

        cv2.imshow("Radar", self.img)
        cv2.waitKey(2) 

Archived version

OpenCV-Python — is a Python bindings library for solving computer vision problems.  cv2.line () is used to draw a line on any image.

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

Parameters:
image: It is the image on which line is to be drawn.
start_point: It is the starting coordinates of line. The coordinates are represented as tuples of two values ​​ie ( X coordinate value, Y coordinate value).
end_point: It is the ending coordinates of line. The coordinates are represented as tuples of two values ​​ie ( X coordinate value, Y coordinate value).
color: It is the color of line to be drawn. For BGR , we pass a tuple. eg: (255, 0, 0) for blue color.
thickness: It is the thickness of the line in px.

Return Value: It returns an image.

The image is used for all examples below:

Example # 1:

# Python program to explain the cv2.line () method

  
# cv2 import

import cv2 

 
# path

path = r ’C: UsersRajnishDesktoppythonengineeringgeeks.png’

 
# Read image in default mode

image = cv2.imread (path)

 
# Name of the window in which the image is displayed

window_name = ’Image’

  
# Start coordinate, here (0, 0)
# represents the top left image corner

start_point = ( 0 , 0 )

 
# End coord inata, here (250, 250)
# represents the lower right corner of the image

end_point = ( 250 , 250 )

 
# Green color in BGR

color = ( 0 , 255 , 0 )

 
# 9 px line width

thickness = 9

  
# Use Using the cv2.line () method
# Draw a 9px diagonal green line

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

 
# Display image
cv2.imshow (window_name , image) 

Output:

Example # 2:

# Python program to explain the cv2.line () method

 
# cv2 import

import cv2 

 
# path

path = r ’C: UsersRajnishDesktoppythonengineeringgeeks.png ’

  
# Read image in grayscale

image = cv2.imread (path, 0 )

 
# Name of the window in which the image is displayed

window_name = ’Image’

  
# The starting coordinate, here (225, 0)
# represents the upper right corner of the image enia

start_point = ( 225 , 0 )

 
# End coordinate, here (0, 225)
# represents the bottom left corner of the image

end_point = ( 0 , 225 )

 
# Black color in BGR

color = ( 0 , 0 , 0 )

 
# Line width 5 px

thickness = 5

 
# Using the cv2.line () method
# Draw a 5px diagonal black line

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

 
# Display image
cv2.imshow (window_name, image) 

Output:

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically