Ask Your Question

Revision history [back]

How to count the number of neighbor pixels in a mask?

Let's say I have a 0 or 1 mask image.

How can I count, for each pixel, its number of 9-connected
neighbors which are set to 1?

I tried this:

count_neighbors_K = np.array([ [1,1,1],
                               [1,0,1],
                               [1,1,1] ], dtype = np.uint8)


test_array = np.array([ [0,0,0,0],
                        [0,0,0,0],
                        [0,1,0,0],
                        [0,0,0,0] ], dtype = np.uint8)

# neighbors_count = cv2.filter2D(mask, -1, count_neighbors_K)
neighbors_count = cv2.filter2D(test_array, -1, count_neighbors_K)
neighbors_count

But the count on the borders are wrong:

>>> neighbors_count
array([[0, 0, 0, 0],
       [2, 1, 1, 0],
       [2, 0, 1, 0],
       [4, 2, 2, 0]], dtype=uint8)