我在做一个图像分析项目。我已经把我感兴趣的图片(一个nxmnumpy数组)转换成二进制格式。矩阵中的“1”是感兴趣的区域。存在感兴趣的区域,并且存在不可能表示图像上特征的噪声。例如,在图像的水平快照中,我不感兴趣的是孤立的1或2到5个连续1的组。我想找到一个快速的方法来翻转这些(即使它们=0)。你知道吗
我翻转1的MWE:
import numpy as np
img = np.random.choice([0,1],size=(1000,1000), p=[1./2,1./2])
#now we take the second derivative of the matrix in the horizontal axis
#since we have a binary matrix, an isolated 1, that is [...010...] is captured
#by a second derivative entry equal to -2
#because ([...010...]->dx->[...1,-1,...]->dx->[...-2...]
ddx_img = np.diff(np.diff(img,1),1)
to_flip = np.where(ddx_img==-2) #returns a tuple of [x,y] matrix entries
# the second derivative eats up an index position on horizontally, so I need to add
# +1 to the horizontal axis of the tuple
temp_copy = to_flip[1].copy() #cannot modify tuple directly, for some reason its read only
temp_copy+=1
to_flip = (to_flip[0],temp_copy)
#now we can flip the entries by adding +1 to the entries to flip and taking mod 2
img[to_flip]=mod(img[to_flip]+1,2)
在我的机器上大约需要9毫秒。我可以做一秒钟的常规动作。你知道吗
我欢迎对代码的任何批评(我不是一个好的python程序员),以及关于如何有效地扩展这个过程以消除连续1的孤立孤岛到通用大小S的孤岛的任何想法
提前谢谢
编辑:我意识到mod是不必要的。在我这样做的时候,我还想翻转太小的0孤岛。。。。按=0
问题具体案例
在编辑之后,似乎可以使用一些^{} ,从而避免制作中间副本以提高性能。这里有两行代码来实现所需的输出-
运行时测试和验证结果-
一般情况
为了使解决方案通用化,可以使用一些信号处理,特别是
2D convolution
,如下所示-样本输入,输出-
相关问题 更多 >
编程相关推荐