Modify path name when saving with PIL

2019-07-26 20:16发布

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.

2条回答
爷的心禁止访问
2楼-- · 2019-07-26 21:10

You could do this as follows:

import os

listing = os.listdir(path1)    

for f in listing:
    im = Image.open(os.path.join(path1, f))

    red, green, blue = im.split()
    red = red.convert('LA')
    green = green.convert('LA')
    blue = blue.convert('LA')

    file_name, file_ext = os.path.splitext(f)

    red.save(os.path.join(path2, "{}r.png".format(file_name))
    green.save(os.path.join(path2, "{}g.png".format(file_name))
    blue.save(os.path.join(path2, "{}b.png".format(file_name))

I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.

查看更多
欢心
3楼-- · 2019-07-26 21:17

You first need to split the filename from the extension.

import os
filename = path2 + f # Consider using os.path.join(path2, f) instead
root, ext = os.path.splitext(filename)

Then you can combine them correctly again doing:

filename = root + "r" + ext

Now filename would be imgr.png instead of img.pngr.

查看更多
登录 后发表回答