Detecting lines in an image with Hough transforms
Part of a series of examples from the CV cheat sheet. Click here for other computer vision applications.
Detecting straight lines in an image is a common task in computer vision. One way to do this is with the Hough (pronounced "Huff") transform. The math behind it is beyond the scope of this example, but we should be able to get you off the ground using it with OpenCV and Python. We're going to assume you have OpenCV installed already and are able to use it in Python.
Take an input image, say, this basketball court:
Credit: Wikimedia Commons
Let's detect the straight lines in this image. The gist is this:
- Open an image
- Detect edges in it
- Use those edges to detect straight lines
- Draw those lines back on the image (you don't need to do this necessarily, but it's a nice visual)
Here's the code to extract lines in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
Here's the result:
We can see it found the majority of lines on the court - and quite a few in the skyline. This is
why you'll want to tune the threshold in
cv2.HoughLines(edges, 1, np.pi / 180, threshold) based
on your needs to prevent false positives or negatives.