如何在OpenCV中的图像上画一条线?

时间:2013-09-05 09:11:51

标签: python opencv

如果我有一条直线的极坐标,我如何在OpenCV&中的图像上绘制它?蟒?

Line函数需要2个点,但只绘制段。我想从图像的一个边缘到另一个边缘绘制一条线。

4 个答案:

答案 0 :(得分:26)

只计算2分以外。 opencv的Line很好用,例如(-10,-10)为一点。

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

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

答案 1 :(得分:13)

看看以下解决方案,我首先将极坐标方程中的一条线转换为笛卡儿坐标,然后使用numpy.vectorize()生成一个向量,使我能够在空间的任何点上表示直线。 / p>

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()

结果:

enter image description here

答案 2 :(得分:3)

您可以在Hough Line Transform tutorial

中查看如何执行此操作
import cv2
import numpy as np

img = cv2.imread('dave.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)

lines = cv2.HoughLines(edges,1,np.pi/180,200)
for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('houghlines3.jpg',img)

答案 3 :(得分:0)

这是解决在OpenCV中绘制两个给定点的无限线段的方法。

handleSubmit

您可以根据需要使用p1和p2,然后调用函数 ### function to find slope def slope(p1,p2): x1,y1=p1 x2,y2=p2 if x2!=x1: return((y2-y1)/(x2-x1)) else: return 'NA' ### main function to draw lines between two points def drawLine(image,p1,p2): x1,y1=p1 x2,y2=p2 ### finding slope m=slope(p1,p2) ### getting image shape h,w=image.shape[:2] if m!='NA': ### here we are essentially extending the line to x=0 and x=width ### and calculating the y associated with it ##starting point px=0 py=-(x1-0)*m+y1 ##ending point qx=w qy=-(x2-w)*m+y2 else: ### if slope is zero, draw a line with x=x1 and y=0 and y=height px,py=x1,0 qx,qy=x1,h cv2.line(image, (int(px), int(py)), (int(qx), int(qy)), (0, 255, 0), 2) return image