Jon-Eric
Jon-Eric

Reputation: 17275

Using Python to convert color formats?

I'm working on a Python tool to convert image data into these color formats:

What's the simplest way to achieve this?

I've used the Python Imaging Library (PIL) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point.

Is there an easier way? Perhaps some type of 'formatter' plugin for PIL?

Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code.

Or is there a better library than PIL to accomplish this in Python?

Any tips would be appreciated. Thanks!

Upvotes: 3

Views: 5471

Answers (5)

Jon-Eric
Jon-Eric

Reputation: 17275

I ended up doing the conversions manually as Lennart Regebro suggested.

However, pure Python (iterating over each pixel) turned out to be too slow.

My final solution used PIL to load the image and numpy to operate on (convert) an array of pixels.

Upvotes: 0

Lennart Regebro
Lennart Regebro

Reputation: 172209

Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 0 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc.

Edit: Reading through your question again, I think there is a confusion (either with me or you). RGB555 and RGBA4444 etc are not really formats, like GIF or JPG, they are color spaces. That conversion is trivial (see above). What file format you want to save it in later is another question. Most file formats have limited support for color spaces. I think for example that JPEG always saves it in YCbCr (but I could be mistaken), GIF uses a palette (which in turn always is RGB888, I think) etc.

Upvotes: 2

Hexbee
Hexbee

Reputation: 11

There is also a module named Grapefruit that let you do conversions between quite a lot of color formats.

Upvotes: 1

Paul
Paul

Reputation: 3112

Numpy is powerful indeed, but to get there and back to PIL requires two memory copies. Have you tried something along the following lines?

im = Image.open('yourimage.png')
im.putdata([yourfunction(r,g,b) for (r,g,b) in im.getdata()])

This is quite fast (especially when you can use a lookup table). I am not familiar with the colour spaces you mention, but as I understand you know the conversion so implementation of yourfunction(r,g,b) should be straight forward.

Also im.convert('RGBA', matrix) might be very powerful as it is super fast in applying a colour transformation through the supplied matrix. However I have never gotten that to do what I wanted it to do... :-/

Upvotes: 1

mikl
mikl

Reputation: 24267

There's a module called Python Colormath which provides a lot of different conversions. Highly recommended.

Upvotes: 1

Related Questions