PIL保存时修改路径名

Modify path name when saving with PIL

我正在从图像中提取 RGB 通道并将它们保存为灰度 png 文件,但我无法保存它们。这是我的代码:

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')

其中path1path2分别是图像文件夹和保存目的地。我想要做的是将 img.png 的黑白版本的颜色通道保存到 imgr.pngimgg.pngimgb.png,但我用这段代码得到的是 img.pngrimg.pnggimg.pngb。任何帮助将不胜感激。

您首先需要将文件名与扩展名分开。

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

然后你可以再次正确组合它们:

filename = root + "r" + ext

现在 filename 将是 imgr.png 而不是 img.pngr

您可以按如下方式进行:

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

我建议您在处理路径和文件名时使用 os.path.split() and os.path.join() 函数。