How to search image for subimages using linux console?
I need to look for the appearance of a smaller image in a larger one using the console. As a result, I want to get its image coordinates. What solutions are possible?
I've heard about ImageMagick but don't really understand how it works. If that's enough, then I would appreciate the example team.
Thank.
source to share
Here's a small example so you can see how it works ...
First, our needle image
Now make a haystack, green and blue - very classy :-)
convert -size 256x256 gradient:lime-blue haystack.png
Now hide two needles in a haystack, one at a time, nothing fancy:
convert haystack.png needle.png -geometry +30+5 -composite haystack.png
convert haystack.png needle.png -geometry +100+150 -composite haystack.png
Now find the needles in the haystack, two output files will be generated, locations-0.png
andlocations-1.png
compare -metric RMSE -subimage-search haystack.png needle.png locations.png > /dev/null 2>&1
This is the second, more useful output file locations-1.png
. It is black, where IM is sure there is no match and is gradually approaching white, the more definite ImageMagick is that there is a match.
Now find places where IM is 95 +%, there is definitely a match and conversion of all pixels to text so that we can search for a word white
.
convert locations-1.png -threshold 95% txt: | grep white
The way out is that ImageMagick found needles at 30.5 and 100 150 - that's where we hid them! Said it was Magic !
30,5: (255,255,255) #FFFFFF white
100,150: (255,255,255) #FFFFFF white
Here's the entire script so you can run it and play with it:
#!/bin/bash
convert -size 256x256 gradient:lime-blue haystack.png # make our haystack
convert haystack.png needle.png -geometry +30+5 -composite haystack.png # hide our needle near top-left
convert haystack.png needle.png -geometry +100+150 -composite haystack.png # hide a second needle lower down
# Now search for the needles in the haystack...
# ... two output files will be produced, "locations-0.png" and "locations-1.png"
compare -metric RMSE -subimage-search haystack.png needle.png locations.png > /dev/null 2>&1
# Now look for locations where IM is 95% certain there is a match
convert locations-1.png -threshold 95% txt: | grep white
source to share