1

So I'm trying to write a function, lets call it foo, that takes the path of a binary image, gets the Hough lines along it and then returns the lines sorted by how many white pixels are along the Hough lines. This is the code I have so far, but its crashing at the "if(image[(x1+(istepx)),(y1+(istepy))].any()):" line with an invalid index. Do you guys see what I can do to fix the bug or know of a function built in OpenCV to do what I want?

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
Joshua Snider
  • 705
  • 1
  • 8
  • 34
  • Are you using Python 2 or 3? Because in Python 3, I believe the `/` is _not_ integer division (or if you said `from __future__ import division` in your Python 2 program), so you would end up trying to index non-integer positions. Also, another issues to consider is that a line of length less than 100 will have `stepx=0` and `stepy=0`. Also, make sure that both `pt1` and `pt2` are within the bounds of the image. – Nicu Stiurca Apr 09 '14 at 04:34
  • Python 2.7 and casting (i*stepx) and (i*stepy) to ints results in the same error. – Joshua Snider Apr 09 '14 at 04:54

1 Answers1

3

I ended up solving it by using OpenCV's line iterator as follows and I'm currently trying to rewrite my line params function to be better.

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
Joshua Snider
  • 705
  • 1
  • 8
  • 34