Skip to content

Instantly share code, notes, and snippets.

@pachacamac
Created May 22, 2012 16:28
Show Gist options
  • Save pachacamac/2770100 to your computer and use it in GitHub Desktop.
Save pachacamac/2770100 to your computer and use it in GitHub Desktop.
Bidirectional Hough Transformation with ChunkyPNG
require 'mathn'
require 'chunky_png'
def hough_transformation(img, cutoff=185, steps=1)
mx, my = img.width*0.5, img.height*0.5
to_rad = Math::PI / 180.0
hough = Hash.new(0)
img.width.times do |x|
#puts "#{x} of #{img.width}"
img.height.times do |y|
next if ChunkyPNG::Color.to_grayscale_bytes(img[x,y]).first < cutoff
(0...180).step(steps).each do |a|
rad = a * to_rad
d = (x-mx) * Math.cos(rad) + (y-my) * Math.sin(rad)
hough[[a.to_i, d.to_i]] += 1
end
end
end
hough
end
def display_hough_transformation(hough, heatmap='heatmap.png', outname='hough.png')
heat = (ChunkyPNG::Image.from_file(heatmap) rescue nil)
max = hough.values.max
max_d = hough.max_by{|k,v| k[1].abs}[0][1].abs
out = ChunkyPNG::Image.new(180, max_d*2+1, ChunkyPNG::Color::BLACK) #TRANSPARENT
hough.each_pair do |k,v|
a, d = k
c = ((v / max) * 255).to_i
out[a, max_d + d] = heat ? heat[c, 0] : ChunkyPNG::Color.rgb(c,c,c)
end
out.save(outname)
end
#http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2
def draw_hough_lines(hough, img)
mx, my = img.width*0.5, img.height*0.5
max = hough.values.max
to_rad = Math::PI / 180.0
cutoff = max - (max / 2)
objects = hough.select{|k,v| v > cutoff}
p objects
img[mx,my] = ChunkyPNG::Color.rgb(0,255,0)
objects.each do |k,v|
a, d = k
a = a * to_rad
(-mx..mx).step(0.01).each do |x|
begin
y = ((1 / Math.sin(a)) * (d - x * Math.cos(a)))
img[(mx+x).to_i,(my+y).to_i] = ChunkyPNG::Color.rgb(255,0,0)
rescue
end
end
#img.circle(mx, my, d.abs, ChunkyPNG::Color.rgb(255,0,0))
end
img.save('reverse_hough.png')
end
img = ChunkyPNG::Image.from_file('test.png')
puts "calculating hough transformation"
hough = hough_transformation(img)
puts "creating hough space image"
display_hough_transformation(hough, nil)
puts "creating reverse hough transformation image"
draw_hough_lines(hough, img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment