I am extracting RGB channels from images and saving them as grayscale png files, but I have trouble saving them. Here is my code:
listing = os.listdir(path1)
for f in listing:
im = Image.open(path1 + f)
red, green, blue = im.split()
red = red.convert('LA')
green = green.convert('LA')
blue = blue.convert('LA')
red.save(path2 + f + 'r', 'png')
green.save(path2 + f + 'g', 'png')
blue.save(path2 + f + 'b','png')
Where path1
and path2
are image folder and save destinations respectively. What I want to do is to save the b&w version of color channel of img.png
to
imgr.png
, imgg.png
, imgb.png
, but what I get with this code is img.pngr
, img.pngg
, img.pngb
. Any help would be appreciated.
You could do this as follows:
I would recommend you make use of the
os.path.split()
andos.path.join()
functions when working with paths and filenames.You first need to split the filename from the extension.
Then you can combine them correctly again doing:
Now
filename
would beimgr.png
instead ofimg.pngr
.