【发布时间】:2019-01-16 22:54:30
【问题描述】:
所以我尝试在 python 中实现霍夫变换线算法,但我发现它很难提高时间效率。
这是我的实现:
import numpy as np
def houghLines(edges, dTheta, threshold):
imageShape = edges.shape
imageDiameter = (imageShape[0]**2 + imageShape[1]**2)**0.5
rhoRange = [i for i in range(int(imageDiameter)+1)]
thetaRange = [dTheta*i for i in range(int(-np.pi/(2*dTheta)), int(np.pi/dTheta))]
cosTheta = [np.cos(theta) for theta in thetaRange]
sinTheta = [np.sin(theta) for theta in thetaRange]
countMatrix = np.zeros([len(rhoRange), len(thetaRange)])
eds = [(x,y) for (x,y), value in np.ndenumerate(edges) if value > 0]
for thetaIndex in range(len(thetaRange)):
theta = thetaRange[thetaIndex]
cos = cosTheta[thetaIndex]
sin = sinTheta[thetaIndex]
for x, y in eds:
targetRho = x*cos + y*sin
closestRhoIndex = int(round(targetRho))
countMatrix[closestRhoIndex, thetaIndex] += 1
lines = [(p,thetaRange[t]) for (p,t), value in np.ndenumerate(countMatrix) if value > threshold]
return lines
它可以工作,但速度很慢,比 opencv 实现慢 100 倍。
我该如何改进它?
【问题讨论】:
-
Python 代码总是比原生代码慢很多。一种选择是Numba。此外,您应该索引为
countMatrix[closestRhoIndex, thetaIndex]。 -
@CrisLuengo 但真的要慢得多吗?我会尝试numba,为什么是索引呢?这种方式更快还是更好?
-
我认为索引应该更快,但可能不会显着。
countMatrix[closestRhoIndex][thetaIndex]首先执行countMatrix[closestRhoIndex],创建一个新的中间矩阵,然后对其进行索引。完全可以预期 Python 会慢 100 倍,是的。这就是解释语言和编译语言的区别。 -
最近的一个相关问题:stackoverflow.com/q/54224976/7328782
-
谢谢,现在我感觉没那么笨了。我在使用 numba 时遇到问题,但我会解决的。
标签: python image-processing hough-transform houghlines