使用opencv在python中绘制hough空间?

时间:2014-08-08 12:25:10

标签: python opencv hough-transform

我使用Python在OpenCV中工作。

我在图像上使用了hough line变换,并成功获得了一些行。

现在我想看一下霍夫空间的结果,以便更好地了解这些线的票数和它们的位置。任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:1)

实际上,ximgproc模块中有一个函数。您需要使用此contrib模块重新编译OpenCV,请参阅https://github.com/opencv/opencv_contrib

然后,您可以使用的功能是cv::ximgproc::FastHoughTransform https://docs.opencv.org/3.4.1/d9/d29/namespacecv_1_1ximgproc.html#a401697bbdcf6c4a4c7d385beda75e849

答案 1 :(得分:0)

OpenCV API没有该功能。没有OpenCV的Hough Lines转换函数将该图像返回给调用者。

http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlines

如果您想为某一行收到的投票数设置最低阈值,您可以在调用Hough Lines方法时设置threshold参数。

如果您想要将霍夫线投票空间的图像可视化以用于学习目的,则必须使用MATLAB的radon命令。或者你可以实现自己的。

答案 2 :(得分:0)

我在Github中找到了一个可以计算它的仓库,并对其进行了修改以仅显示霍夫空间。

Github参考:https://github.com/alyssaq/hough_transform

经过修改的代码如下:

import numpy as np
import imageio
import math
import matplotlib.pyplot as plt

def rgb2gray(rgb):
    return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.uint8)


def hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5):
    """
    Hough transform for lines
    Input:
    img - 2D binary image with nonzeros representing edges
    angle_step - Spacing between angles to use every n-th angle
                 between -90 and 90 degrees. Default step is 1.
    lines_are_white - boolean indicating whether lines to be detected are white
    value_threshold - Pixel values above or below the value_threshold are edges
    Returns:
    accumulator - 2D array of the hough transform accumulator
    theta - array of angles used in computation, in radians.
    rhos - array of rho values. Max size is 2 times the diagonal
           distance of the input image.
    """
    # Rho and Theta ranges
    thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step))
    width, height = img.shape
    diag_len = int(round(math.sqrt(width * width + height * height)))
    rhos = np.linspace(-diag_len, diag_len, diag_len * 2)

    # Cache some resuable values
    cos_t = np.cos(thetas)
    sin_t = np.sin(thetas)
    num_thetas = len(thetas)

    # Hough accumulator array of theta vs rho
    accumulator = np.zeros((2 * diag_len, num_thetas), dtype=np.uint8)
    # (row, col) indexes to edges
    are_edges = img > value_threshold if lines_are_white else img < value_threshold
    y_idxs, x_idxs = np.nonzero(are_edges)

    # Vote in the hough accumulator
    for i in range(len(x_idxs)):
        x = x_idxs[i]
        y = y_idxs[i]

        for t_idx in range(num_thetas):
            # Calculate rho. diag_len is added for a positive index
            rho = diag_len + int(round(x * cos_t[t_idx] + y * sin_t[t_idx]))
            accumulator[rho, t_idx] += 1

    return accumulator, thetas, rhos


def show_hough_line(img, accumulator, thetas, rhos, save_path=None):
    plt.imshow(accumulator, aspect='auto', cmap='jet', extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]])
    if save_path is not None:
        plt.savefig(save_path, bbox_inches='tight')
    plt.show()


if __name__ == '__main__':
    imgpath = 'path_img.tif'
    img = imageio.imread(imgpath)
    if img.ndim == 3:
        img = rgb2gray(img)
    accumulator, thetas, rhos = hough_line(img)
    show_hough_line(img,
                    accumulator,
                    thetas, rhos,
                    save_path='output.png')

我得到正确的结果: enter image description here

对于这张图片:

enter image description here