Python-Hough行实现,提高了时间效率

2024-04-20 08:38:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试在python中实现hough变换线算法,我发现很难提高时间效率。你知道吗

这是我的实现:

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倍。你知道吗

我怎样才能改进它?你知道吗


Tags: inforvaluenprangesincosint
1条回答
网友
1楼 · 发布于 2024-04-20 08:38:08

答案是使用麻木。代码现在是这样的:

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倍。你知道吗

相关问题 更多 >