How to detect lines accurately using HoughLines transform in openCV python?

Viewed 24956

I am a newbie in both python and opencv and I am facing a problem in detecting lines in the following image, which has strips of black lines laid on the ground:

enter image description here

I used the following code:

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
print img.shape[1]
print img.shape
minLineLength = img.shape[1]-1
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
    cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

but it is unable to detect the lines accurately and only draws a green line on the first black strip from the bottom which does not even cover the entire line,
also,
please suggest a way of obtaining the y cordinates of each line.

2 Answers

I tried to extract horizontal and vertical lines in an image.So we can use morphological operations for this.It'll be the best thing for this problem.Try it.

Mat img = imread(argv[1]);

if(!src.data)
    cerr << "Problem loading image!!!" << endl;

imshow("img .jpg", img);

cvtColor(img, gray, CV_BGR2GRAY);
imshow("gray", gray);


Mat binary_image;
adaptiveThreshold(gray, binary_image, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
imshow("binary.jpg", binary_image);

// Create the images that will use to extract the horizontal and vertical lines
Mat horizontal = binary_image.clone();
Mat vertical = binary_image.clone();

int horizontalsize = horizontal.cols / 30;

Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontalsize,1));


erode(horizontal, horizontal, horizontalStructure, Point(-1, -1));
dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1));
imshow("horizontal", horizontal);

int verticalsize = vertical.rows / 30;

Mat verticalStructure = getStructuringElement(MORPH_RECT, Size( 1,verticalsize));

erode(vertical, vertical, verticalStructure, Point(-1, -1));
dilate(vertical, vertical, verticalStructure, Point(-1, -1));

imshow("vertical", vertical);

bitwise_not(vertical, vertical);
imshow("vertical_bit", vertical);


Mat edges;
adaptiveThreshold(vertical, edges, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, -2);
imshow("edges", edges);

Mat kernel = Mat::ones(2, 2, CV_8UC1);
dilate(edges, edges, kernel);
imshow("dilate", edges);

Mat smooth;
vertical.copyTo(smooth);

blur(smooth, smooth, Size(2, 2));

smooth.copyTo(vertical, edges);

imshow("smooth", vertical);
waitKey(0);
return 0;
Related