I am solving Connected component labeling algorithm using BFS algorithm. The original image im will be labeled into out image.
When the blob is small this code works. However when I change the starting point to have a large blob, the code either reach maximum depth of recursion or has segmentation fault. How to avoid these problems?
import cv2
import numpy as np
from collections import deque
import sys
import copy
sys.setrecursionlimit(10000000)
def bfs(queue, im, out, label):
if len(queue) > 0:
pixel = queue.pop()
print pixel
out[pixel] = label
M, N = im.shape
for n in neighbors(pixel, M, N):
if out[n] == 0 and im[n] == im[pixel]:
queue.append(n)
out = bfs(queue, im, out, label)
return out
def neighbors(pixel, M, N):
if pixel[0] == M - 1 and pixel[1] == N - 1:
return [(M-2, N-1), (M-1, N-2)]
elif pixel == (0,0):
return [(0,1),(1,0)]
elif pixel == (M - 1, 0):
return [(M-1, 1), (M-2, 0)]
elif pixel == (0, N - 1):
return [(1, N-1), (0, N-2)]
elif pixel[0] == 0:
return [(1,pixel[1]), (0, pixel[1]-1), (0 ,pixel[1] + 1)]
elif pixel[1] == 0:
return [(pixel[0], 1), (pixel[0]-1, 0), (pixel[0] + 1, 0)]
elif pixel[0] == M - 1:
return [(pixel[0], pixel[1] + 1), (pixel[0] - 1, pixel[1]), (pixel[0], pixel[1] - 1)]
elif pixel[1] == N - 1:
return [(pixel[0] + 1, pixel[1]), (pixel[0], pixel[1] - 1), (pixel[0] - 1, pixel[1])]
else:
return [(pixel[0] + 1, pixel[1]), (pixel[0], pixel[1] + 1),\
(pixel[0] - 1, pixel[1]), (pixel[0], pixel[1] - 1)]
im = cv2.imread('33039.png', cv2.IMREAD_GRAYSCALE)
out = np.zeros(im.shape)
queue = deque()
queue.append((10,10))
out = bfs(queue, im, out, 1)