python - matlab 在 python 中的 bwmorph(image, 'spur')
问题描述
我正在将一个 matlab 图像处理脚本移植到 python/skimage 并且无法找到 Matlab 的bwmorph函数,特别是'spur'
skimage 中的操作。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
。对于有相同需求的未来互联网旅行者,这里有一个我最终使用的方便要点:
https://gist.github.com/bmabey/4dd36d9938b83742a88b6f68ac1901a6
推荐阅读
- python - 如何遍历网络爬虫的结果页面并解析单个页面结果以获取更多详细信息?
- automapper - 在自动映射器映射期间调用异步方法
- javascript - ReactJS Flex 布局问题
- reactjs - 如何在 React Native 中显示一次屏幕?
- if-statement - 带有 IF 和 While 的 BigQuery 脚本
- ios - 如何在 PDF 中获取选定的单词以便发音?[斯威夫特,PDFKit]
- sql-server - 错误:此平台不支持 System.Data.SqlClient
- r - 使用R从以表达式结尾的句子中提取所有单词
- c++ - 如何使用标志变量为旨在搜索数组以查找通过用户输入提供的字符串的程序生成输出?
- python - 使用高阶函数发现了一种模式。这种模式叫什么?