Can't identify a Stack level too deep error on rake task with recursive function

77 views Asked by At

I have a big problem with a "Stack level too deep" error on my rake script. This script basically read an image that contains some pixels with value "-1". So I use a recursive function when found a "-1" value to analize their neightbors and save it on array if their have a "-1" value too. My object is found "-1" shapes.

I made many test and when I comment a "label_recursively" function the error is not show it. But I don't know where is the line with problem.

I tried with diferent versions of ruby but I have the same results.

To load the image I'm using Chunky PNG gem, with Rails 4.0.0 and Ruby 2.1.2p95

This is my code:

class ChunkyPNG::Image
  def neighbors(x,y)
    # up, right, down, left
    [[x, y-1], [x+1, y], [x, y+1], [x-1, y]].select do |xy|
      include_xy?(*xy)
    end
  end
end

def label_recursively(image, areas, label, x, y)
  image[x,y] = label
  (areas[label] ||= []) << [x,y]
  image.neighbors(x,y).each do |xy|
    if image[*xy] == -1
      areas[label] << xy
      label_recursively(image, areas, label, *xy)
    end
  end
end

working_image = ChunkyPNG::Image.from_file(file)

areas, label = {}, 0

working_image.height.times do |y|
  working_image.row(y).each_with_index do |pixel, x|
    label_recursively(working_image, areas, label += 1, x, y) if pixel == -1
  end
end

areas.each do
  area = areas.values.max { |result, area| result.length <=> area.length }
  areas.delete(areas.key(area))
  x, y = area.map { |xy| xy[0] }, area.map { |xy| xy[1] }
  image.rect(x.min, y.min, x.max, y.max, ChunkyPNG::Color.rgb(0,255,0))
end

Thanks in advance

0

There are 0 answers