LineSegmentDetector in Opencv 3 with Python

I was able to draw the lines in OpenCV 3.2.0 with the following:

lsd = cv2.createLineSegmentDetector(0)
dlines = lsd.detect(gray_image)
  for dline in dlines[0]:
    x0 = int(round(dline[0][0]))
    y0 = int(round(dline[0][1]))
    x1 = int(round(dline[0][2]))
    y1 = int(round(dline[0][3]))
    cv2.line(mask, (x0, y0), (x1,y1), 255, 1, cv2.LINE_AA)

I am not sure why all of the extra [0] indirection, but that seems to be what it takes to extract the coordinates.

When unpacking OpenCV returns, I have found it helpful to just print the thing on the console. In this case, I did

print(dlines)

From all of the nested square brackets, I can often work out a solution without having to worry too much about the why and wherefore of it all.

I had previously used a Windows DLL version of LSD that I compiled from the authors' source and called with ctypes.


You can use cv2.drawSegments function like this:

#Read gray image
img = cv2.imread("test.png",0)

#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)

#Detect lines in the image
lines = lsd.detect(img)[0] #Position 0 of the returned tuple are the detected lines

#Draw detected lines in the image
drawn_img = lsd.drawSegments(img,lines)

#Show image
cv2.imshow("LSD",drawn_img )
cv2.waitKey(0)

You can check OpenCV documentation.