Skip to content

Instantly share code, notes, and snippets.

@smeschke
Created March 20, 2019 22:12
Show Gist options
  • Save smeschke/4b422bb849a0396b4f728636ba74773a to your computer and use it in GitHub Desktop.
Save smeschke/4b422bb849a0396b4f728636ba74773a to your computer and use it in GitHub Desktop.
Draws a line and hows Hough Space
import cv2, numpy as np, math
# Parameters
num_dots, hw, num_bins = 10, 400, 400
# Read image that has two lines in it
lines = np.zeros((hw,hw), np.uint8)
# Create a row of diagonal dots
space = int(hw / (num_dots+1))
for i in range(num_dots): cv2.circle(lines, (space*(i+1), space*(i+1)), 0, 255, 1)
# Create accumulator array
accumulator = np.zeros((num_bins,num_bins), np.uint8)
# Calculate the diagonal distance of the image (used to scale rho)
diag = math.sqrt(lines.shape[0]**2 + lines.shape[1]**2)
# Iterate through each row in the image
for x in range(lines.shape[0]):
# Iterate through each column in the image
for y in range(lines.shape[1]):
# Get the pixel value for this row, column
px = lines[x, y]
# If the pixel value is not black
if px != 0:
# Iterate through theta values
for theta_idx in range(num_bins):
# Calculate theta
theta = theta_idx * math.pi / num_bins
# Calculate rho
rho = x * math.cos(theta) + y * math.sin(theta)
# Scale rho so that it is a value between 0 and num_bins
rho = int(num_bins * .5 * (rho+diag) / diag)
# Increment the appropriate bin
accumulator[rho, theta_idx] += 1
# Make a circle around the brightest spot
_, _, _, maxLoc = cv2.minMaxLoc(accumulator)
cv2.circle(accumulator, maxLoc, 25, 255, 2)
# Threshold the accumulator (this makes the lines visible)
_, accumulator = cv2.threshold(accumulator, 0, 255, 0)
# Show image
cv2.imshow('img', cv2.dilate(lines,np.ones((5,5),np.uint8),iterations = 2))
cv2.imshow('accumulator', cv2.resize(accumulator, (hw,hw)))
cv2.imwrite('/home/stephen/Desktop/lines.png', cv2.dilate(lines,np.ones((5,5),np.uint8),iterations = 2))
cv2.imwrite('/home/stephen/Desktop/accumulator.png', cv2.resize(accumulator, (hw,hw)))
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment