0

I've been playing around with RMagick's color_histogram method to get a histogram of colors in a quantized 8-bit image.

However, while I'm supposed to get a hash returned from this method, I get something kind of wonky. The output from IRB upon inspecting the "hash" looks like this:

=> {red=1907, green=1893, blue=2716, opacity=0=>25801, red=21141, green=14902, blue=13109, opacity=0=>3744, red=35552, green=15344, blue=8229, opacity=0=>1427, red=48734, green=19120, blue=8539, opacity=0=>1280, red=62091, green=22662, blue=8733, opacity=0=>75158, red=57917, green=33805, blue=24932, opacity=0=>275, red=47046, green=39657, blue=37365, opacity=0=>1873, red=64379, green=64336, blue=64330, opacity=0=>10442}

Any ideas what I'm doing wrong here?

Josh Smith
  • 14,674
  • 18
  • 72
  • 118
  • That's not a valid hash. I'd say the output is just garbled for some reason, the data structure (hash) is probably still working properly. Did you try `color_histogram.class`..what does that say? Also note that each key in the hash is one **pixel**, so for any moderate size image the hash will be humongous. – Casper Jul 01 '12 at 16:55
  • @Casper I did try `color_histogram.class` and it output `Hash`. I reduced the image to 8 colors so there should only be 8 keys in the hash. – Josh Smith Jul 01 '12 at 19:14
  • Hmm..ok. What about `color_histogram.keys.first`..what does that look like? And `color_histogram.keys.first.class`. I think the hash might be ok after all, the keys just represent color values (red, green, blue + opacity). – Casper Jul 01 '12 at 19:44

1 Answers1

5

Reading the documentation for color_histogram you find the explanation:

Each key in the hash is a Pixel representing a color that appears in the image. The value associated with the key is the number of times that color appears in the image.

Looking further you find that Pixel is a class. So that explains the weird looking output. Each key in the hash is of class Pixel. So when you see:

{ red=1907, green=1893, blue=2716, opacity=0 => 25801 }

What you are really looking at is:

{ Pixel => histogram_count }

Or:

{ Pixel(red=1907, green=1893, blue=2716, opacity=0) => 25801 }

The irb printout just compressed the output a bit so it was hard to read before you realize what is going on.

Casper
  • 33,403
  • 4
  • 84
  • 79
  • Awesome. Thanks so much. It would help to know a bit more Ruby to really know what to do with this, but glad the structure's apparent now. – Josh Smith Jul 01 '12 at 20:08