如何在二值化后从图像中删除粗线伪影



>我陷入了一个问题,我想区分对象和背景(具有带背光的半透明白片),即在背景中引入固定的粗线并与对象合并。我现在的算法是我从相机中获取图像,用高斯模糊进行平滑处理,然后从HSV中提取值分量,使用wolf方法应用局部二值化以获得二值化图像,然后使用OpenCV连接分量算法我删除了一些未连接到对象的小伪影,如图所示。现在只有这个线工件与对象合并,但我只想要这个图像中看到的对象。请注意,二进制图像中有 2 行,因此使用 8 个连接的逻辑来检测不循环的行是不可能的,这是我的想法和尝试。这是代码

size = np.size(thresh_img)
skel = np.zeros(thresh_img.shape,np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
done = False
while( not done):
eroded = cv2.erode(thresh_img,element)
temp = cv2.dilate(eroded,element)
temp = cv2.subtract(thresh_img,temp)
skel = cv2.bitwise_or(skel,temp)
thresh_img = eroded.copy()
zeros = size - cv2.countNonZero(thresh_img)
if zeros==size:
done = True
# set max pixel value to 1
s = np.uint8(skel > 0)
count = 0
i = 0
while count != np.sum(s):
# non-zero pixel count
count = np.sum(s)
# examine 3x3 neighborhood of each pixel
filt = cv2.boxFilter(s, -1, (3, 3), normalize=False)
# if the center pixel of 3x3 neighborhood is zero, we are not interested in it
s = s*filt
# now we have pixels where the center pixel of 3x3 neighborhood is non-zero
# if a pixels' 8-connectivity is less than 2 we can remove it
# threshold is 3 here because the boxfilter also counted the center pixel
s[s < 1] = 0
# set max pixel value to 1
s[s > 0] = 1
i = i + 1

非常感谢代码形式的任何帮助。

由于您已经在使用connectedComponents,因此最好的方法是不仅排除那些很小的组件,还要排除那些接触图像边界的组件。 您可以使用connectedComponentsWithStats()来了解要丢弃哪些组件,该还为您提供有关每个组件的边界框的信息。

或者,非常类似地,您可以从connectedComponents()切换到findContours(),这直接为您提供组件,以便您可以丢弃外部组件和小组件以检索您感兴趣的零件。

最新更新