Skip to content
Advertisement

Find center of blocks of ones in an 2d array

Lets assume I have the following array

import numpy as np

a = np.array([[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 1. 1. 0. 0. 0.]
 [0. 0. 0. 0. 1. 1. 1. 0. 0. 0.]
 [0. 0. 0. 0. 1. 1. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0. 0. 0. 0.]
 [0. 0. 1. 1. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]])

and want to get the center of each block of ones, so that I can get the following array:

a_centers = np.array([[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]])

I already thought about using means or convolutions, but I couldn’t think of a really simple solution.

One in efficient solution that I found is:

a_centers = np.zeros(a.shape)

for i in range(len(a)):
    for j in range(len(a[i])):
        if np.sum(a[i - 1:i + 2, j - 1:j + 2]) == 9:
            a_centers[i, j] = 1

Advertisement

Answer

This is a little less inefficient, since no edge cell can be at the center of a 3×3 block:

for i in range(1,len(a)-1):
    for j in range(1,len(a[i])-1):
        if np.sum(a[i - 1:i + 2, j - 1:j + 2]) == 9:
            a_centers[i, j] = 1
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement