Py学习  »  Python

如何使用python和opencv获得距离变换图像中的“直线”

cris318 • 4 年前 • 211 次点击  

我现在正在做的一个项目有一个半问题。我已经成功地使用了距离变换( cv2.distanceTransform )在图像上。现在我需要得到轮廓内的明亮“线”(距离轮廓最远的地方)。我已经有了一个算法,但结果有一些错误,我想纠正。但我不知道怎么做。我正在使用python、opencv和pycharm。

距离图像:

enter image description here

我尝试了几种形式的阈值,canny和hough(我想这在曲线上是行不通的)。没人能满足我的需要。 我现在的代码是这样工作的。我构造一个间隔,在这里我寻找具有最大值的像素。这些像素的值设置为255。我看了两遍图像。一次从行开始,一次从列开始。不幸的是,这样做的像素将不属于该行。原因当然是使用的间隔是按行或按列计算的。

结果是:

enter image description here

从轮廓上看,这不是最后一条线。这张图片我稍后将用作一个遮罩来绘制直方图。

def maxValueinIntervall(pathname, bounds, rowMax, colMax):
    img = cv2.imread(pathname, 0)
    res = np.zeros(img.shape, img.dtype)
    maxValue = 0
    kernel = np.ones((5, 5), np.uint8)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if(img[i, j] == bounds and img[i, j + 1] > bounds and img[i, j - 1] <= bounds):
                n = 1
                k = j
                myList = []
                while(img[i, k + n ] > bounds):
                    myList.append(img[i, k + n])
                    k = n + k
                maxValue = max(myList)

            if (maxValue > rowMax and img[i, j] == maxValue):
                res[i, j] = 255

    for j in range(img.shape[1]):
        for i in range(img.shape[0]):
            if(img[i, j] == bounds and img[i + 1, j] > bounds and img[i - 1, j] <= bounds):
                n = 1
                k = i
                myList = []
                while(img[k + n, j] > bounds):
                    myList.append(img[k + n, j])
                    k = n + k
                maxValue = max(myList)

            if (maxValue > colMax and img[i, j] == maxValue):
                res[i, j] = 255

    return res

也许已经有一个opencv函数来实现这个功能了,我还没有找到它。我希望改进我的解决方案,以便我能为下一步准备一个更好的面具。 谢谢你抽出时间。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46575
 
211 次点击