How to draw a line on an image in OpenCV?

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


Take a look to the following solution, I firstly convert a line in polar equations to cartesian and then I use numpy.vectorize() to generate a vector that allows me to get represent the line in any point of the space.

import cv2
import numpy as np

img_size = (200,200)
img = np.ones(img_size) * 255

# polar equation
theta = np.linspace(0, np.pi, 1000)
r = 1 / (np.sin(theta) - np.cos(theta))

# polar to cartesian
def polar2cart(r, theta):
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    return x, y

x,y = polar2cart(r, theta)
x1, x2, y1, y2 = x[0], x[1], y[0], y[1]

# line equation y = f(X)
def line_eq(X):
    m = (y2 - y1) / (x2 - x1)
    return m * (X - x1) + y1

line = np.vectorize(line_eq)

x = np.arange(0, img_size[0])
y = line(x).astype(np.uint)

cv2.line(img, (x[0], y[0]), (x[-1], y[-1]), (0,0,0))
cv2.imshow("foo",img)
cv2.waitKey()

Result:

enter image description here