在OpenCV中计算沿线的白色像素数量

1 投票
1 回答
3336 浏览
提问于 2025-04-18 01:58

我正在尝试写一个函数,叫做 foo,它接收一个二进制图像的路径,获取图像中的霍夫线,然后返回这些线,按照沿着霍夫线的白色像素数量进行排序。到目前为止,我写的代码是这样的,但在“if(image[(x1+(istepx)),(y1+(istepy))].any()):”这一行出错了,提示索引无效。你们能帮我看看怎么修复这个错误吗?或者知道 OpenCV 中有没有现成的函数可以实现我想要的功能?

def lineParams(line, length):
    (dist, angl) = line
    a = math.cos(angl)
    b = math.sin(angl)
    x0 = a * dist
    y0 = b * dist
    pt1 = (int(x0 - length * b), int(y0 + length * a))
    pt2 = (int(x0 + length * b), int(y0 - length * a))
    return (pt1, pt2)

def lineWhiteness(line, image):
    (pt1, pt2) = lineParams(line, len(image))
    count = 0
    (x1, y1) = pt1
    (x2, y2) = pt2
    stepx = (x2 - x1) / 100
    stepy = (y2 - y1) / 100
    for i in xrange(1, 100):
        #print image[(x1 + i * stepx), (y1 + i * stepy)]
        if(image[(x1 + (i * stepx)), (y1 + (i * stepy))].any()):
            count = count + 1
    return count

def foo(path, display):
    edges = CannyEdge(path, False)
    lines = cv2.HoughLines(edges, rho, theta, threshold)
    image = cv2.imread(path)
    lines = lines[0]
    lines = sorted(lines, key=lambda l: lineWhiteness(l, image))
    return lines

1 个回答

3

我最后是通过使用OpenCV的线迭代器解决了这个问题,现在我正在尝试改进我的线参数函数,让它变得更好。

def lineWhiteness(line, image):
    (pt1, pt2) = lineParams(line, len(image))
    count = 0
    li = cv.InitLineIterator(cv.fromarray(image), pt1, pt2)
    for (r, g, b) in li:
        if (r or g or b):
            count += 1
    return count

撰写回答