在Python中使用对角线填充消除背景的8连接性(类似于MATLAB中的bwmorph diag)
我正在寻找一种在Python中连接8个相连像素的方法,类似于MATLAB的“diag”函数:在Python中使用对角线填充消除背景的8连接性(类似于MATLAB中的bwmorph diag),python,image,image-processing,Python,Image,Image Processing,我正在寻找一种在Python中连接8个相连像素的方法,类似于MATLAB的“diag”函数: BW = bwmorph(BW, 'diag') 比如说, 0 1 0 0 1 0 1 0 0 -> 1 1 0 0 0 0 0 0 0 提前谢谢 Misha您可以使用简单的图像过滤获得相同的结果。我是在MATLAB中完成的,但也应该直接在python中完成: %随机二进制图像 bw=兰特(50)>0.5; %使用
BW = bwmorph(BW, 'diag')
比如说,
0 1 0 0 1 0
1 0 0 -> 1 1 0
0 0 0 0 0 0
提前谢谢
Misha您可以使用简单的图像过滤获得相同的结果。我是在MATLAB中完成的,但也应该直接在python中完成:
%随机二进制图像
bw=兰特(50)>0.5;
%使用bwmorph(bw,'diag')的结果
res1=bwmorph(bw,'diag');
%过滤背景的8-连通性
f=[1-10;-110;00];
%使用原始图像初始化结果
res2=bw;
对于ii=1:4%的所有方向
%添加结果,其中总和等于屏幕上的2->两个背景像素
%对角线,在交叉迷你反对角线上有2个前景像素
res2=res2 |(imfilter(double(~bw),f)=2);
f=90(f);%将过滤器旋转到下一个方向
终止
isequal(res2,res1)%yes
很好用,谢谢!下面是python代码:
def bwmorphDiag(bw):
# filter for 8-connectivity of the background
f = np.array(([1, -1, 0],[-1, 1, 0],[0, 0, 0]),dtype = np.int)
# initialize result with original image
bw = bw.astype(np.int)
res2 = bw.copy().astype(np.bool)
for ii in range(4): # all orientations
# add results where sum equals 2 -> two background pixels on the
# diagonal with 2 foreground pixels on the crossing mini-anti-diagonal
res2 = res2 | (ndimage.filters.convolve(np.invert(bw),f) == 2)
f = np.rot90(f) # rotate filter to next orientation
return res2
我实际上是在寻找同样的python等价物,MATLAB的
bwmorph('diag')
。但由于找不到它,我最终决定编写代码。请查看MATLAB帮助中的bwmorph
和diag
选项,以获取有关其功能的更多信息
import numpy as np
import scipy.ndimage.morphology as smorph
import skimage.morphology as skm
class bwmorph:
@staticmethod
def diag(imIn):
strl = np.array([
[[0,1,0],[1,0,0],[0,0,0]],
[[0,1,0],[0,0,1],[0,0,0]],
[[0,0,0],[1,0,0],[0,1,0]],
[[0,0,0],[0,0,1],[0,1,0]],
[[0,1,0],[1,0,0],[0,1,0]],
[[0,1,0],[1,0,1],[0,0,0]],
[[0,1,0],[0,0,1],[0,1,0]],
[[0,0,0],[1,0,1],[0,1,0]]
],dtype=np.uint8)
bwIm = np.zeros(imIn.shape,dtype=int)
imIn = np.array(imIn)
imIn = imIn/np.max(np.max(imIn)) #normalizing to be added later
for i in range(7):
bwIm = bwIm + smorph.binary_hit_or_miss(imIn,strl[i,:,:])
bwIm = ((bwIm>0) + imIn)>0
return bwIm # out put is boolean
我使用了“命中或未命中”转换,在开头定义了结构元素“strl”。我想这是一个经典的方法
请注意@staticmethod
是否在旧版python上运行。
使用示例为bwmorph().diag(BinaryImage)
祝你一切顺利;) 也许您可以从库
openCV
和scikit image
中找到?不幸的是,我在这两个库中都找不到类似的函数。。。