Проблемы с заливкой (аналогично алгоритму заливки) [python] - PullRequest
2 голосов
/ 16 декабря 2011

Пару дней назад я попросил помочь с функцией floodfill, и сообщество stackoverflow очень помогло, указав мне на ошибки в моей функции (я новичок в python и программировании).Функция будет искать соседние элементы в массиве и искать элементы со значениями в пределах 0,05 друг от друга, как это делает алгоритм заливки.Теперь, когда я запускаю его, кажется, что он работает для маленьких массивов, но не для больших массивов

    import numpy
    import time
    def floodcount (x,y,arraycopy,value,count=0):
        #print 'x= ', x
        nrows = len(arraycopy) -1        #rows of the image
        ncols = len(arraycopy[0])-1       #columns of the image
        if x < 0 or y < 0 or x > nrows or y > ncols:
            return count

        diff = arraycopy[x][y] - value
        print '[',x,y,']','-',value, ' = ', diff
        # the base case, finding a diff more than 0.5 or less than 0 is like finding a boundary
        if (diff < 0.00) or (diff > 0.5): 
            return count

        count = count +1

        arraycopy[x][y] = -5 # so we do no calculate this pixel again
       #print "[",x,",",y,"]"

        count = floodcount (x-1,y,arraycopy,value,count)
        count = floodcount (x,y+1,arraycopy,value,count)
        count = floodcount (x+1,y,arraycopy,value,count)
        count = floodcount (x,y-1,arraycopy,value,count)
        count = floodcount (x-1,y-1,arraycopy,value,count)
        count = floodcount (x+1,y+1,arraycopy,value,count)
        count = floodcount (x+1,y-1,arraycopy,value,count)
        count = floodcount (x-1,y+1,arraycopy,value,count)


        return count



    array =numpy.zeros([31,31]) # fails for anything bigger than 31x31

    arraycopy = [x[:] for x in array]

    thresholdMin, thresholdMax, thresholdStep = 0,0,0.5
    thresholdRange = numpy.arange( thresholdMin, thresholdMax+thresholdStep,  thresholdStep )

    for x in range(len(arraycopy)):
        for y in range(len(arraycopy[0])):
            tempstorage= []
            value = float(arraycopy [x][y])
            if value != -5 and value in thresholdRange:
                print value,x,y
                matches = floodcount(x,y,arraycopy,value)

                    tempstorage.append(matches)
                    maxarea = max(tempstorage)
                    found.append([value,maxarea])

Код работает для массивов меньше, чем 31x31, но не больше.Если я назначаю больший массив, он выдает что-то вроде этого

Вывод

  Traceback (most recent call last):
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 73, in <module>
    matches = floodcount(x,y,arraycopy,value)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)
  File "C:\Users\Geek\Desktop\Light stuff\floodcount.py", line 22, in floodcount
    count = floodcount (x,y+1,arraycopy,value,count)

Это происходит до тех пор, пока "RuntimeError: максимальная глубина рекурсии превышена в cmp"

Любые предложения какк чему я делаю не так?

1 Ответ

2 голосов
/ 16 декабря 2011

Вы, кажется, вызываете переполнение стека. Вместо этого рекурсивного решения может быть лучше использовать массив точек, чтобы проверить и вытолкнуть / вытолкнуть их из этого массива, когда вы столкнетесь / обработаете их.

например:

create an array called toProcess
create an array or similar to mark which points have been encountered
add your start point to toProcess
while (there are points in toProcess) {
  pop the top/bottom point of toProcess into a temp variable
  process the point
  mark the point as encountered
  if any of the points neighbours are not encountered add them to toProcess

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...