python - python 中的 matlab bwmorph(图像, 'spur' )

标签 python matlab scikit-image

我正在将 matlab 图像处理脚本移植到 python/skimage,但无法找到 Matlab 的 bwmorph函数,特别是 skimage 中的'spur' 操作。 matlab 文档对 spur 操作是这样说的:

Removes spur pixels. For example:
0  0  0  0           0  0  0  0
0  0  0  0           0  0  0  0
0  0  1  0  becomes  0  0  0  0
0  1  0  0           0  1  0  0
1  1  0  0           1  1  0  0

我已经在 python 中实现了一个版本,可以很好地处理上述情况:

def _neighbors_conv(image):
    image = image.astype(np.int)
    k = np.array([[1,1,1],[1,0,1],[1,1,1]])
    neighborhood_count = ndimage.convolve(image,k, mode='constant', cval=1)
    neighborhood_count[~image.astype(np.bool)] = 0
    return neighborhood_count

def spur(image):
    return _neighbors_conv(image) > 1

def bwmorph(image, fn, n=1):
    for _ in range(n):
        image = fn(image)
    return image

t= [[0, 0, 0, 0],
    [0, 0, 1, 0],
    [0, 1, 0, 0],
    [1, 1, 0, 0]]
t = np.array(t)
print('neighbor count:')
print(_neighbors_conv(t))
print('after spur:')
print(bwmorph(t,spur).astype(np.int))

neighbor count:
[[0 0 0 0]
 [0 0 1 0]
 [0 3 0 0]
 [7 5 0 0]]
after spur:
[[0 0 0 0]
 [0 0 0 0]
 [0 1 0 0]
 [1 1 0 0]]

上述方法的工作原理是删除仅具有单个相邻像素的任何像素。

我注意到上述实现的行为与 matlab 的 spur 操作不同。以 matlab 为例:

0     0     0     0     0
0     0     1     0     0
0     1     1     1     1
0     0     1     0     0
0     0     0     0     0

becomes, via bwmorph(t,'spur',1):

0      0     0     0     0
0      0     0     0     0
0      0     1     1     1
0      0     0     0     0
0      0     0     0     0

支线操作比查看 8 邻居计数要复杂一些。我不清楚如何扩展我的实现来满足这种情况而不使其过于激进(即删除有效像素)。

matlab 的 spur 的底层逻辑是什么,或者是否有我可以使用的 python 实现?

更新: 我发现 Octave 的支线实现使用了 LUT:

case('spur')
      ## lut=makelut(inline("xor(x(2,2),(sum((x&[0,1,0;1,0,1;0,1,0])(:))==0)&&(sum((x&[1,0,1;0,0,0;1,0,1])(:))==1)&&x(2,2))","x"),3);
      ## which is the same as
      lut=repmat([zeros(16,1);ones(16,1)],16,1); ## identity
      lut([18,21,81,273])=0; ## 4 qualifying patterns
      lut=logical(lut);
      cmd="BW2=applylut(BW, lut);";

(来自https://searchcode.com/codesearch/view/9585333/) 假设这是正确的,我只需要能够在 python 中创建这个 LUT 并应用它...

最佳答案

我最终自己实现了我自己的 spur 版本和 bwmorph 的其他操作。对于有相同需求的 future 互联网旅行者,这里是我最终使用的一个方便的要点:

https://gist.github.com/bmabey/4dd36d9938b83742a88b6f68ac1901a6

关于python - python 中的 matlab bwmorph(图像, 'spur' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341793/

相关文章:

Python flask @app.errorhandler(Exception) 得到完整的错误,而不仅仅是描述

visual-studio - 有没有办法将 Visual Studio 或 MATLAB 中的程序执行顺序设为 "map"?

matlab - 无法在 Matlab 中保存非常大的矩阵

python - Python 中 Kruskal-Wallis 检验的输入格式

python - 有没有办法将多种日期格式转换为日期时间python

python - 文件 "E:\python\lib\re.py",第 229 行,在 finditer 中返回 _compile(pattern, flags).finditer(string) TypeError : expected string or bytes-like object

numpy - 将有符号 float 转换为 uint8 图像 opencv

python - 使用 scikit-image 和 Python 实现 GLCM 纹理特征

python - 从 pandas dataframe groupby 中提取带有计数的新列

Matlab:如何发布需要用户输入的脚本