0

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

jgiunta
  • 3
  • 2
  • Just a guess: your algorithm finds the neighbor `(x + 1, y)` for the pixel `(x, y)`, and the neighbor `(x, y)` for the pixel `(x + 1, y)`, and keeps doing that over and over. – Adrian Dec 21 '14 at 18:20
  • Yes, sory I forgot the method "neighbors". I edited the post including this. Thanks – jgiunta Dec 21 '14 at 18:38
  • Try this method on a very low pixel-count image and inspect the x and y coordinates at each step to see how they change. If the method itself is valid, perhaps the image is too large and the shear number of method calls is rightfully overflowing the stack. You might be able to mitigate this by breaking up the recursion into chunks. i.e., Break up the image into several chunks, then apply the method to each of those chunks. – SnakeWasTheNameTheyGaveMe Dec 21 '14 at 21:15

0 Answers0