如果我有一条线的极坐标,如何在OpenCV & python中的图像上绘制它呢?
Line函数取2点,但只绘制段。我想从图像的边缘画一条线到另一条。
发布于 2013-09-05 10:32:49
只需计算外面的2分。opencv的线条很好,例如(-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)发布于 2013-09-05 09:58:15
看看下面的解,我首先把极坐标方程中的一条线转换成笛卡儿,然后用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()结果:

发布于 2017-09-14 00:37:33
您可以在Hough线变换教程中看到如何做到这一点。
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)https://stackoverflow.com/questions/18632276
复制相似问题