require 'imagestring' def better_difference?(current, new) if current.abs < new.abs return false elsif current.abs > new.abs return true else return (current < new) end end filename = ARGV[0] i = ImageString.new(filename) path = [] # find lowest position in first column (current_row, current_col) = 0, 0 min = i.pixel_at(current_row, current_col) for row in 1..(i.rows - 1) if i.pixel_at(row, 0) < min current_row = row min = i.pixel_at(row, 0) end end path.push([current_row, current_col]) while path.size <= i.columns current_pixel = i.pixel_at(current_row, current_col) (next_row, next_col) = current_row, current_col + 1 # How much difference is safe? min_diff = current_pixel - i.pixel_at(next_row, next_col) if current_row != 0 up_right = current_pixel - i.pixel_at(current_row - 1, next_col) if better_difference?(min_diff, up_right) next_row = current_row - 1 end end if current_row != i.rows - 1 down_right = current_pixel - i.pixel_at(current_row + 1, next_col) if better_difference?(min_diff, down_right) next_row = current_row + 1 end end path.push([next_row, next_col]) (current_row, current_col) = next_row, next_col end # display path on image path.each do |point| i.set_pixel(point[0], point[1], 255) end pathed_filename = filename.sub(/\./, '.pathed.') i.dump_to_file(pathed_filename)