Shahrukh Azhar
Shahrukh Azhar

Reputation: 59

Extracting Walls from Image in OpenCv

I have the following image of a maze:

Input:

image

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:

Output

Upvotes: 1

Views: 1096

Answers (1)

Jeru Luke
Jeru Luke

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)

enter image description here

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)

enter image description here

cv2.imshow('fin', cv2.bitwise_not(cv2.bitwise_not(im_floodfill) + thresh))

enter image description here

There is another example detailing this function on THIS POST

Upvotes: 3

Related Questions