Engee documentation
Notebook

Line detection using the Haar transform

In this example, we will look at line detection in an image using the Haar transform.

First of all, let's connect all the libraries that we will need during 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 load images with a white line in the centre. In this example, we will look at two ways of uploading:

  1. via a 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, let's convert it to binary form.

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

Now let's perform thinning of the binary matrix to find the expressed lines.

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

Then, using the Haar transform, 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 let's overlay the found line on the original image and mark it with red colour.

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 picture above, our original image and the found line coincide in location and direction.

Conclusion

In this example we have learnt how to apply Haar transformations to detect objects in images. This function works correctly and you can use it in your projects.