Numpy - change values โโnear matching value
I have an image as a numpy array. I am trying to enlarge objects with a specific color by setting any pixels next to it to the same color.
However, I cannot find a way to do this. Any suggestions how to do this?
A somewhat simplified example of my question is below. How do I find and update values โโbelow 12 in the array below?
In[1]:import numpy as np
In[2]:z = np.arange(25).reshape(5,5)
In[3]: z
Out[4]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
Result in an updated array that looks like this (update the values โโat z [2,1] and z [2,3]):
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 12, 12, 12, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
Very grateful for any advice!
source to share
Use Scipy binary dilation
in a match mask to create an extended mask that can be used boolean-indexing
to change all adjacent elements, including the matching element itself, with the appropriate number.
So the implementation would be -
from scipy.ndimage.morphology import binary_dilation
mask = binary_dilation(z==12,[[1,1,1]]) # create dilated mask
z[mask] = 12 # use dilated mask to change elements
Example run -
In [42]: z # Input array
Out[42]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
In [43]: from scipy.ndimage.morphology import binary_dilation
In [44]: mask = binary_dilation(z==12,[[1,1,1]])
In [45]: z[mask] = 12
In [46]: z # Input array modified
Out[46]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 12, 12, 12, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
source to share