使用Python OpenCV寻找模糊物体周围的紧密轮廓

3

我在模糊的物体周围寻找轮廓时遇到了麻烦。以下是我想要实现的一些示例:

enter image description here

enter image description here

正如您所看到的,这些物体非常模糊。我尝试计算平均背景值并使用简单的阈值。问题是,较小的颗粒比较大的颗粒亮得多。因此,当我使用简单的阈值时,它要么切掉太多的小颗粒,要么不能紧密地围绕较大的颗粒。我还尝试根据对象的最暗像素值设置阈值。虽然这对某些颗粒有效,但只要一个颗粒既有暗区域又有亮区域,它就会崩溃。
我还尝试了skimage熵过滤器,但没有成功。由于图像的模糊性,Canny边缘检测也不可能。
但是,既然我的眼睛能够勾勒出物体的轮廓,我认为必须有一种简单的方法来使用Python和OpenCV找到轮廓。
提前感谢! Luca
2个回答

3
一种简单的方法是使用大津阈值自适应阈值来自动确定阈值。思路是先进行高斯模糊,然后进行阈值处理以获得二值图像,接着查找轮廓并使用cv2.drawContours突出显示轮廓。您可能需要调整参数以获得所需的输出结果。结果如下:
输入(截图)-> 输出

enter image description here enter image description here

enter image description here enter image description here

import cv2
import numpy as np

# Load image, grayscale, Gaussian blur, Adaptive threshold
image = cv2.imread('2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (9,9), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,23,3)

# Find contours and filter using contour area
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10:
        cv2.drawContours(image, [c], -1, (36,255,12), 1)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()     

-1
我觉得我终于找到了我的问题的答案。如果有人遇到类似的问题,请查找OpenCV的自适应阈值可能性!

3
请考虑添加您自己的解决方案(包括代码和结果)。这可能对他人有所帮助。 - Andreas K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接