Thursday, March 24, 2011

ImageMagick subimage search

As part of a larger project, I needed to find the coordinates of any instances of a small image inside a larger image. Here are the two images:


I think you can guess out what my project was. Anyway, using ImageMagick's subimage-search to get the desired coordinates (all those pyramid shaped crystal things) was pretty easy. Here is the command I used to analyze floor #11:

This outputs a new grey image, with a white spot corresponding to the location of every match. Check it out:
Note the white spot in the center of each crystal- those are the matches we're looking for! If we tell ImageMagick to output a text file, we get a list of coordinates:

Note the coordinate with the color of "white." Now we're getting somewhere- a numerical coordinate corresponding to a match. Here is a quick one-liner I used to parse the coordinates out of the file:

This grabs all the lines of the file that contain 'white.' It then uses awk to parse the raw output into something more useable in Clojure:

Done! Now we have a coordinate list of all the crystals in the image. Check out how I used it in a future blog post.

2 comments:

  1. How did you get the coordinates to output to the .txt file?

    ReplyDelete
    Replies
    1. Great question! Imagemagick will output text coordinates if your output is text files. The way you do that is just by changing the .png filename suffix to .txt. So the command becomes this:

      > compare -subimage-search floor-11.png crystal.png result-11-%d.txt

      Hope that helps!

      Delete