Skip to content

Instantly share code, notes, and snippets.

@MrPanch
Created November 3, 2021 19:21
Show Gist options
  • Select an option

  • Save MrPanch/6f5d167698f66097aa4217b5f5db1883 to your computer and use it in GitHub Desktop.

Select an option

Save MrPanch/6f5d167698f66097aa4217b5f5db1883 to your computer and use it in GitHub Desktop.

Revisions

  1. MrPanch created this gist Nov 3, 2021.
    29 changes: 29 additions & 0 deletions h.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    def hough_transform(
    img: np.ndarray, theta: float, rho: float
    ) -> (np.ndarray, list, list):
    thetas = np.deg2rad(np.linspace(0, 180, int(180 / theta + 1)))
    width, height = img.shape
    diag_len = int(np.ceil(np.sqrt(width * width + height * height))) # max_dist
    rhos = np.linspace(-diag_len, diag_len, int(diag_len / rho + 1))


    # 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((len(rhos), num_thetas), dtype=np.uint64)
    y_idxs, x_idxs = np.nonzero(img) # (row, col) indexes to edges

    # Vote in the hough accumulator
    for i in tqdm(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 = int(x * cos_t[t_idx] + y * sin_t[t_idx]) + diag_len
    accumulator[rho, t_idx] += 1

    return accumulator, thetas, list(rhos)