Reputation: 59
I have the following image of a maze:
Input:
The walls are white and the path is black. How can I extract one of the walls in a separate image in opencv?
This is the output I want
Output:
Upvotes: 1
Views: 1096
Reputation: 21203
You can use the concept of flood fill algorithm for this problem.
In your input image notice how the 'walls' are distinct and are neighbored by black pixels (path). When you initialize the algorithm at any one pixel within this 'wall' they will be separated from the rest of the image.
Code:
path = r'C:\Users\Desktop'
filename = 'input.png'
img = cv2.imread(os.path.join(path, filename))
cv2.imshow('Original', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 100, 255,cv2.THRESH_BINARY_INV)
cv2.imshow('thresh1', thresh)
im_floodfill = thresh.copy()
h, w = thresh.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0,0), 255)
cv2.imshow('im_floodfill', im_floodfill)
cv2.imshow('fin', cv2.bitwise_not(cv2.bitwise_not(im_floodfill) + thresh))
There is another example detailing this function on THIS POST
Upvotes: 3