Code and Life

Programming, electronics and other cool tech stuff

Supported by

Supported by Picotech

Correcting image white balance with Python PIL and Numpy

I started writing another blog post about my new keyboard today, and when uploading the unboxing video to my YouTube channel, I realized they have no “auto white balance” option, not in their new or old video editor either. Shoot. After googling for free video editors, I settled on OpenShot.

And guess what? OpenShot doesn’t have a white balance setting either! The author himself said this on Reddit, asking for help to implement it. I was pretty shocked, as it seems like the first filter I would implement myself, and thought “surely it doesn’t take more than five minutes to implement one, right?”. So I did. Well, it took maybe 15 minutes, plus 45 fiddling with Jupyter notebooks to get PIL and numpy commands right.

The Python 3 code above basically loads an image (either local if you run it with Jupyter notebook locally, or over network), get a small subportion of it to act as a grey reference, and adjusts color channel balance with two alternate methods: RGB or YCbCr. More advanced versions should be easy to add as well.

You can view the above gist in Github or just copy-paste the code to your own / cloud based notebook to try it out:

https://gist.github.com/jokkebk/7a0feab274356768b515db6b05f124bf

If you don’t have access to anything that can run a ipynb file, you can just take a look at the PDF version of a sample run. Enjoy!

2 comments

Sulio:

If you cant understand color science why you try to give advises to others? How you get grey reference? Whats happened if region you get is colored? How you find the region? Your approach is not the right one. It may be work in some cases but not in all cases. Please stop deal with image processing and try to make programs for sheep counting.

Joonas Pihlajamaa:

Your angry writing style made me suspect this is some automatically generated troll text, but you do raise a good point I did not cover in detail. So I’ll bite!

Yes, you definitely need to choose a neutral grey area manually from the image for the approach described to work. Photo touching software like Adobe Lightroom have this feature, so I kind of skipped the explanation of area selection. If you are really pro, you have a neutral grey reference board you shoot in the location&lighting, but usually a part of the image you know should be fairly neutral grey will get you 98 % there.

And finally to match your tone (this is tongue in cheek, no offense meant): I do know color science well enough to correct it (not pretending to be an expert in color spaces or color perception though). Making programs for sheep counting would be much harder! You might need to practice constructive commenting and your writing tone, or perhaps stick to talking to sheep!