Claudiu Claudiu - 1 year ago 218
Python Question

PIL rotate image colors (BGR -> RGB)

I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?

Answer Source

Assuming no alpha band, isn't it as simple as this?

b, g, r = im.split()
im = Image.merge("RGB", (r, g, b))


Hmm... It seems PIL has a few bugs in this regard... im.split() doesn't seem to work with recent versions of PIL (1.1.7). It may (?) still work with 1.1.6, though...

Alternatively, if you have numpy available, you can use it to do this: (Again, I'm assuming an RGB image here, not an RGBA image!):

data = np.asarray(im)
im = Image.fromarray(np.roll(data, 1, axis=-1))

If im.split() would just work, it's certainly a simpler and more readable option!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download