ruby-hough-hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Authors: Robert Jackson, Jonathan Jackson | |
# the formatting of this file has been altered in | |
# order to fit on this website. Check out | |
# https://gist.github.com/1233581 if you care | |
require 'chunky_png' #or 'oily_png' | |
class Hough | |
def initialize(image_path, options={}) | |
@image = ChunkyPNG::Image.from_file(image_path) | |
@image_path = image_path | |
@angles ||= {} | |
end | |
def is_dark?(color) | |
ChunkyPNG::Color.r(color) + | |
ChunkyPNG::Color.g(color) + | |
ChunkyPNG::Color.b(color) < 40 | |
end | |
def is_light?(color) | |
ChunkyPNG::Color.r(color) + | |
ChunkyPNG::Color.g(color) + | |
ChunkyPNG::Color.b(color) > 600 | |
end | |
def angles(theta) | |
@angles[theta] ||= { | |
:cos => Math.cos(theta), | |
:sin => Math.sin(theta) | |
} | |
end | |
def get_hough_matrix | |
hough = Hash.new(0) | |
# iterate over every point of the image 'Hooray Chunky Png' | |
@image.height.times do |y| | |
@image.width.times do |x| | |
# run the point through hough transform only if the | |
# sum of the points' rgb values are less than 40 (are black) | |
# and the point directly below's( y+1 ) rgb values | |
# are greater than 600 (are white) | |
if is_dark?(@image[x,y]) && is_light?(@image[x,y + 1]) | |
# run r = xcos(theta) + ysin(theta) from 0 to 20 | |
# stepping 0.2 at a time | |
(0..20).step(0.2).each do |theta| | |
# http://en.wikipedia.org/wiki/Hough_transform" | |
distance = ( | |
x * angles(theta)[:cos] + | |
y * angles(theta)[:sin] | |
).to_i | |
# populate [theta, distance] as key to hough and increment | |
# the point's score | |
hough[[theta, distance]] += 1 if distance >= 0 | |
end | |
end | |
end | |
end | |
return hough | |
end | |
def average_theta | |
# sort by score, grab top twenty, sum (inject) and divide by length to | |
# get the average. (after #sort_by hough looks like | |
# [[theta, distance] score]) so v[0][0] is just score | |
get_hough_matrix.sort_by {|k,v| v }.take(20).inject(0.0) { |sum,v| | |
sum + v[0][0] | |
} / 20 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment