Geeks With Blogs
Ulterior Motive Lounge UML Comics and more from Martin L. Shoemaker (The UML Guy),
Offering UML Instruction and Consulting for your projects and teams.

Once upon a time, I had a really thorny development problem to solve. I needed to build a histogram of the colors in a true-color image. There was a theoretically easy way to do this. If I had had C# then, the code would’ve looked like this.

int[,,] histogram = new int[256, 256, 256];

for(int y = 0; y < bmp.Height; y++)


    for(int x = 0; x < bmp.Width; x++)


        Color clr = bmp.GetPixel(x, y);

        histogram[clr.R, clr.G, clr.B]++;




This was the brain-dead simple way to build the histogram. Only one problem: it required 16million 32-bit counts, or 64 megabytes.

64 M*E*G*A*B*Y*T*E*S OF RAM, MAN! ARE YOU MAD? THAT WOULD COST US $50,000!!!!! The whole SYSTEM is supposed to cost under $30,000!!!

Well, OK, for some of you, that just pinpointed the year, more or less. There was no way on Earth we could ship a system with 64 MB. Instead, I built a complex and ultimately failed algorithm to build a sparse histogram. I solved the general problem of sparse histograms – with a solution vaguely like what you’ll see below, but less elegant – but I couldn’t easily ascertain color proximity within the histogram. That was just too difficult. It took me months, and it never worked perfectly. Like Alan Cooper says, the bear danced, but never well.

Today, I am almost never without two memory sticks, a memory card, and a phone that collectively add up to about 3 GB. I sometimes forget I even have the card.

And so today, I could actually build the algorithm above (if I still needed it); and it would run in an insignificant amount of memory.

But why bother? I realized that Microsoft had given me simple tools for building a sparse histogram:

Dictionary<System.Drawing.Color, int> histogram = new Dictionary<System.Drawing.Color, int>();
for (int y = 0; y < bmp.Height; y++)
    for (int x = 0; x < bmp.Width; x++)
        System.Drawing.Color clr = bmp.GetPixel(x, y);
        if (histogram.Keys.Contains<System.Drawing.Color>(clr))
            histogram[clr] = 1;

There it is. It works. It’s maybe not efficient, but it’s simple. It still doesn’t solve my color proximity problem (hey, I’ve gotta keep some of my secrets to myself for a while); but it works, and it took me less time to write than I’ve spent on this blog post.

And when it was done, and I found that it didn’t address the problem I was really trying to solve (trying to figure out why my bitmaps aren’t transparent), I threw it away.

Code that once took me weeks, written more elegantly in minutes, and casually thrown away as trivial.

I am so jaded…

Posted on Thursday, March 19, 2009 5:54 PM Personal | Back to top

Comments on this post: Jaded

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Martin L. Shoemaker | Powered by: