Ask Your Question
0

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

asked 2014-02-24 01:53:01 -0600

fbr gravatar image
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)
edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
0

answered 2014-02-24 02:55:36 -0600

Nghia gravatar image

The default border handling scheme is reflection (BORDER_REFLECT_101). You want to pass borderType = BORDER_CONSTANT. But for some reason filter2D doesn't let you specify the constant colour to use according to the doc. So not sure if it'll work. In the worse case you can make a slightly larger image, pad the borders with zeros, run the function and get the subimage.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-02-24 01:53:01 -0600

Seen: 1,776 times

Last updated: Feb 24 '14