Engee documentation
Notebook

Line detection using Hough transform

In this example, we will look at the possibilities of detecting lines in an image using the Haar transform.

First, we will connect all the libraries that we will need in the process of this work.

In [ ]:
Pkg.add(["ImageCore", "ColorVectorSpace", "ImageDraw", "Clustering", "ImageMorphology", "ImageFeatures"])
In [ ]:
using ImageFeatures, FileIO, ImageDraw, ColorVectorSpace
using ImageCore, Clustering, ImageMorphology
gr()

Now let's upload images with a white line in the center.
In this example, we'll look at two loading methods.:

  1. through the URL link,
  2. From the Engee file manager.
In [ ]:
# Скачать изображения из интернета
file = download("https://grizly.club/uploads/posts/2023-08/1691448777_grizly-club-p-kartinki-belaya-poloska-bez-fona-31.jpg")
img = FileIO.load(file)
# Подгрузить изображения из файлов Engee
#img = load( "$(@__DIR__)/line.jpg" )
Out[0]:
No description has been provided for this image

After the image has been loaded into variables, we will convert it to a binary format.

In [ ]:
img_g = Gray.(img)
thresh = otsu_threshold(img_g)
tf = img_g .> thresh;

Now let's thin out the binary matrix to find the pronounced lines.

In [ ]:
t = thinning(tf)
heatmap(t)
Out[0]:

Next, using the Haar transformation, we calculate the cordinates in which the desired line is located.

In [ ]:
 = hough_transform_standard(t, stepsize = 3, vote_threshold = 500, max_linecount = 100, angles = range(0, pi, length = 10000))
R = kmeans(Matrix(hcat(vcat.(...)...)'),3) 
m = Tuple.(eachcol(R.centers))
Out[0]:
3-element Vector{Tuple{Float64, Float64}}:
 (-451.5, 3.141278462905366)
 (454.5, 0.0)
 (-448.5, 3.1375081746922366)

Now we will overlay the found line on the original image and mark it in red.

In [ ]:
img = RGB.(tf);
for (r, θ) in m
    draw!(img, LineNormal(r, θ), RGB{N0f8}(1, 0, 0))
end
img
Out[0]:
No description has been provided for this image

As we can see in the figure above, our original image and the found line match in location and direction.

Conclusion

In this example, we have figured out how to apply Haar transformations to detect objects in images. This function works correctly, and it can be used in your projects.