Swap R and B color channel values in a directory of images? Python
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Swap R And B Color Channel Values In A Directory Of Images? Python
00:44 Accepted Answer Score 1
01:08 Answer 2 Score 2
02:01 Answer 3 Score 6
02:34 Thank you
--
Full question
https://stackoverflow.com/questions/3119...
--
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

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

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!")