The Python Oracle

Swap R and B color channel values in a directory of images? Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC G Dvoks String Quartet No 12 Ame 2

--

Chapters
00:00 Question
01:00 Accepted answer (Score 1)
01:38 Answer 2 (Score 6)
02:21 Answer 3 (Score 2)
03:23 Thank you

--

Full question
https://stackoverflow.com/questions/3119...

Answer 2 links:
[here]: http://imagemagick.org

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #colors #pythonimaginglibrary #imagemanipulation

#avk47



ANSWER 1

Score 6


Building on @veta's answer, the process may be greatly accelerated by working on color channels instead of individual pixels:

In the loop for each file, channels may be swapped like this:

r, g, b = im_rgb.split()
im_rgb = Image.merge('RGB', (b, g, r))

Just use these two lines instead of the nested loops in veta's answer. This should run considerably faster.

This solution first uses Image.split() to create three separate images, one for each R, G, B, channel. Then Image.merge() is used to create a new RGB image with swapped R and B channels.




ANSWER 2

Score 2


You can let ImageMagick do that for you. Let's make a red-black gradient image like this:

convert -size 256x100 gradient:red-black in.png

enter image description here

Now we can load it up, separate the R, G and B channels, swap the Red with the Blue and recombine them into the output image:

convert in.png -separate -swap 0,2 -combine out.png

enter image description here

ImageMagick is installed on most Linux distros and available for OSX (ideally via homebrew) and also for Windows from here.

If you want to do a whole directory of PNG files, for example, you would do

find . -iname "*.png" -exec convert "{}" -separate -swap 0,2 -combine {} \;

if you are on Linux or OS X.

If you are on Windows, you would need to do something like this with the mad Windows syntax:

FOR %%F in (*.PNG) DO convert "%%F" -separate -swap 0,2 -combine "%%F



ACCEPTED ANSWER

Score 1


import os
from PIL import Image


dirPath = r"D:\Fraps\Movies\Screens"
dirList = os.listdir(dirPath)
outPath = r"D:\Fraps\Movies\Screens\Output"

for (dirname, dirs, files) in os.walk(dirPath):
   for filename in files:
       if filename.endswith('.png'):
            print("Opening:"+filename)
            thefile = os.path.join(dirname,filename)
            im = Image.open(thefile)
            #im.load()

            width, height = im.size

            im_rgb = im.convert('RGB')

            for x in range(0, width):
                for y in range(0,height):
                    r, g, b = im_rgb.getpixel((x, y))
                    im_rgb.putpixel((x, y), (b, g, r))

            print("Saving:"+filename)
            #outfile, ext = os.path.splitext(infile)
            outfile = os.path.join(outPath,filename)
            im_rgb.save(outfile, "PNG")


print("Ding!")