python - Python Hough Lines 实现,提高时间效率
问题描述
所以我试图在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 倍。
我该如何改进它?
解决方案
答案是使用 numba。这就是代码现在的样子:
import numpy as np
from numba import jit
@jit(nopython=True)
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 = []
sinTheta = []
for theta in thetaRange:
cosTheta.append(np.cos(theta))
sinTheta.append(np.sin(theta))
countMatrixSize = (len(rhoRange), len(thetaRange))
countMatrix = np.zeros(countMatrixSize)
eds = []
for (x,y), value in np.ndenumerate(edges):
if value > 0:
eds.append((x,y))
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 = []
for (p,t), value in np.ndenumerate(countMatrix):
if value > threshold:
lines.append((p,thetaRange[t]))
return lines
这使它至少快了 50 倍。
推荐阅读
- php - WooCommerce 购物车挂钩“woocommerce_cart_contents”在错误位置显示内容
- javascript - 寻找素数。如何提高我的代码效率
- javascript - 如何在Javascript中推送数组中的循环值
- graphql - NestJs/Graphql:“CustomObject”在解析器中定义,但不在模式中
- google-cloud-platform - Google Cloud Tasks 未随机执行任务
- html - 使用 CSS 以特定的数字顺序排列布局
- c++ - C++ 填充多维 std::arrays
- c# - C# 从 MySQL 下载空 Blob
- javascript - 用js处理文件无需下载
- r - 如何在RMD中将一个表格行分成多行