Skip to content

Instantly share code, notes, and snippets.

@MrPanch
Created November 3, 2021 19:21
Show Gist options
  • Save MrPanch/6f5d167698f66097aa4217b5f5db1883 to your computer and use it in GitHub Desktop.
Save MrPanch/6f5d167698f66097aa4217b5f5db1883 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment