[Image-SIG] PIL and swapping colors

Anders Sandvig anders.sandvig at gmail.com
Fri Nov 5 11:05:10 CET 2010


On Fri, Nov 5, 2010 at 7:16 AM, loz.accs <loz.accs at gmail.com> wrote:
> [...]
>
> Image object (Image.fromstring) was created successfully, but red and
> blue colors was swapped.
> So my question: is there any way to swap colors in image using PIL?

My naive (and slow) implementation would be something like this (code not
tested):

def swap(image):
    width, height = image.size()
    res = Image.new("RGBA", (width, height))
    data1 = image.load()
    data2 = res.load()
    for y in range(height):
        for x in range(width):
            r, g, b, a = data1[x, y]
            data2[x, y] = (b, g, r, a)
    del image
    return res

However, be aware that even if the format is BGRx on your machine doesn't
mean it's the same on a different machine (or even on your machine with a
different resolution), as the screen format will depend on the graphics card and
driver.

Usually the drivers will have a way to tell which format the screen is in (i.e.
RGBx or BGRx), so I advice you to check the format and pass this information on
to the Python code, or convert it to RGBx before handing the image buffer over
to Python.


Anders


More information about the Image-SIG mailing list