mardi 24 août 2021

Change values in array based on distance to other elements in the same array

I have a one-dimensional Boolean Array. Later this array is used for indexing over coordinates indicating a certain area in a 3-dimensional Point array. I want to make the edges of this area a little bit more rough/noisy. (True= area_of_interest) Therefore I want to change the False values in the array based on their distance to the next true value i.e. Values next to a True value are likely to be true while far away ones (further than the cutoff) are unlikely to change.

Input:

bool_array = [False, False, False, False, True, True, False, False]

sample Output:

func(bool_array) = [False, False, False, True, True, True, True, False]

I came up with a solution however this is incredibly slow for huge data (which for me is the case).

decay_prob = lambda x: random() < e ** (-x / 10)

boolean_array = np.asarray([False, False, False, False, True, True, False, False, False, False])
cutoff = 3
true_indeces = np.asarray(np.where(boolean_array == True))

for i in range(boolean_array.size):
    distances = np.abs(true_indeces - i)
    # only modify the ones in within a certain area
    if np.any(distances < cutoff):
        # calculate the distances from the current index to the closest True value
        # change the value dependent on the distance (smaller values are more likely to change to true)
        boolean_array[i] = decay_prob(np.min(distances))

I'm probably missing something obvious but I also couldn't find anything more pythonic or numpy based.




Aucun commentaire:

Enregistrer un commentaire