簡體   English   中英

用opencv在python中繪制霍夫空間?

[英]plot hough space in python with opencv?

我正在使用 Python 在 OpenCV 中工作。

我在圖像上使用了霍夫線變換,結果成功地得到了一些線。

現在我想在霍夫空間中查看結果,以更好地了解這些行有多少票以及它們在哪里。 任何人都可以幫助我嗎?

實際上,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

OpenCV API 沒有這種能力。 OpenCV 的 Hough Lines 變換函數都不會將該圖像返回給調用者。

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

如果您想為一條線路收到的票數設置一個最小閾值,您可以在調用 Hough Lines 方法時設置threshold參數。

如果您想將霍夫線投票空間的圖像可視化以進行學習,則必須改用 MATLAB 的radon命令。 或者你可以實現自己的。

我在 Github 中找到了一個計算它的 repo,我對其進行了調整以僅顯示 hough 空間。

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')

我得到正確的結果: 在此處輸入圖片說明

對於此圖像:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM