我将图像视为一个numpy数组。我试图通过将其旁边的任何像素设置为相同的特定颜色来尝试放大具有特定颜色的对象。
但是,我无法找到解决方法。有什么建议怎么做?
以下问题的略微简化示例。 如何找到并更新下面数组中12旁边的值?
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]])
导致更新的数组看起来像这样(更新z [2,1]和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]])
非常感谢任何建议!
答案 0 :(得分:2)
在匹配的掩码上使用Scipy's binary dilation
创建一个扩大的掩码,可用于boolean-indexing
将所有相邻元素(包括匹配元素本身)更改为匹配的数字。
因此,实施将是 -
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
示例运行 -
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]])