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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18632276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:16:37  来源:igfitidea点击:

How to draw a line on an image in OpenCV?

pythonopencv

提问by Rahul

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

如果我有一条线的极坐标,我如何在 OpenCV 和 python 的图像上绘制它?

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

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

采纳答案by Robert Caspary

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

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

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

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

回答by jabaldonedo

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.

看看下面的解决方案,我首先将极坐标方程中的一条线转换为笛卡尔,然后我使用它numpy.vectorize()来生成一个向量,该向量允许我在空间的任何点上表示这条线。

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

在此处输入图片说明

回答by James L.

You can see how to do this in the 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)