Change the color channel R and B in the image catalog? python

I have a large screenshot catalog. Stupid me, I didn’t check that they came out great, and found that VLC has an error with FRAPS True RGB. Fortunately, this seems to be fixable, it seems that the only problem is that the R and B channels have been replaced.

Using python PIL, I would like to get the red and blue values ​​for each pixel for each image, and then paste them again in swapped.

I know how to go through the directory, so the main part that I skip is the best way to change the values. I think I could make this pixel for pixel, but maybe there is a more pythonic way, maybe all of this in one command?

Any sample code or links would be much appreciated!

+5
source share
3 answers
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!") 
+1
source

Based on @veta's answer, the process can be significantly accelerated by processing color channels instead of individual pixels:

In a loop for each file, the channels can be replaced as follows:

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

Just use these two lines instead of nested loops in veta's answer. This should happen much faster.

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

+2
source

You can let ImageMagick do this for you. Let make a red-black gradient image as follows:

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

enter image description here

Now we can load it, separate the channels R, G and B, change Red with blue and recompile 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 distributions and is available for OSX (ideally via homebrew ), as well as for Windows from here .

If you want to make 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 will need to do something similar with Mad Windows syntax:

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

All Articles