Fastest way to scan and analyze images

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
pitosalas

Fastest way to scan and analyze images

Post by pitosalas »

I have a variety of little algorithms that need to walk through pixels one at a time to look for stuff.

For example, given a b&w tiff image, which I know starts with around 100 rows of all white, I would like to locate the first row which has at least one non-white pixel. So I wrote this, which is very slow. I am writing in Ruby but hopefully it's pretty clear.

rows = img.rows
cols = img.columns
rows.times do
|row|
pixels = image.get_pixels(0, row, image.columns, 1)
pixels.each do |p|
if p.to_color != "white"
return row
end
end
end
return nil

So, basically I am getting the pixels of a whole row with image.get_pixels, and then stepping through those pixels, doing pixel.to_color and checking for "white".

This was the most obvious to me, but clearly way inefficient.

Tips would be greatly appreciated!

Pito
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Fastest way to scan and analyze images

Post by fmw42 »

scale the image down to one column and check for the first row in the column that is not pure white. that will tell you which row to start scanning for the first non-white pixel.
pitosalas

Re: Fastest way to scan and analyze images

Post by pitosalas »

Wow, thanks! That makes so much sense :)
User avatar
anthony
Posts: 8883
Joined: 2004-05-31T19:27:03-07:00
Authentication code: 8675308
Location: Brisbane, Australia

Re: Fastest way to scan and analyze images

Post by anthony »

Make sure you include a '!' flag in the scale, so as to ignore 'aspect ratio' during the resize.

I also do something similar in the script
http://www.imagemagick.org/Usage/scripts/divide_vert
This script tries to find rows of 'constant color' so as to divide the image into horizontal segments
of interesting, and 'blank' elements.

However for this I wanted to know not only what color it was but who many colors were on each row.
that was because I could not guarantee the background was white.

What I did was divide the image into multiple images, 1 pixel row per image (in memory) then have Im output the number of colors, and the first color of each row.

convert $tmpdir/original.mpc -crop 0x1 -format '%k %[pixel:s]' info:

You would only be interested in the %k - or number of colors on each row.

It appears to be a LOT slower (about 20 times slower) than the scale method, but will get you more information about each individual row.

Your API version of scanning the image, however may be a lot faster, and much more direct.
Anthony Thyssen -- Webmaster for ImageMagick Example Pages
https://imagemagick.org/Usage/
Post Reply