如何将 png 上的图像目录转换为 python 中的 jpg

how to convert a directory of image on png to jpg in python

from PIL import Image
from os import listdir
from os.path import splitext
import cv2
target_directory = r"E:\pre\png"
target = '.jpg'
jpg_folder_path = r"E:\pre\jpeg"
for file in listdir(target_directory):
    filename, extension = splitext(file)
    try:
        if extension not in ['.py', target]:
            im = Image.open(filename + extension)
            #im.save((os.path.join(jpg_folder_path, im))filename + target)
            cv2.imwrite(os.path.join(jpg_folder_path , filename + target), im)
    except OSError:
        print('Cannot convert %s' % file)

输出

Cannot convert 000c1434d8d7.png
Cannot convert 00a8624548a9.png
..

使用路径库访问文件系统。这是更pythonic的方式。

from pathlib import Path
from PIL import Image

inputPath = Path("E:/pre/png")
inputFiles = inputPath.glob("**/*.png")
outputPath = Path("E:/pre/jpeg")
for f in inputFiles:
    outputFile = outputPath / Path(f.stem + ".jpg")
    im = Image.open(f)
    im.save(outputFile)

这是这样工作的:

import cv2, os


def tif_to_jpeg_converter(filePath):
    base_path = filePath
    new_path = filePath
    for infile in os.listdir(base_path):
        # print("file : " + infile)
        read = cv2.imread(base_path + infile)
        outfile = infile.split('.')[0] + '.jpg'
        cv2.imwrite(new_path + outfile, read, [int(cv2.IMWRITE_JPEG_QUALITY), 200])
        # Deleting the .tiff file after converting
        if infile[-3:] == "tif":
            print(infile)
            os.remove(filePath + '/' + infile)
            # check if file exists or not


if __name__ == "__main__":
    print("cleaning the files")
    tif_to_jpeg_converter("images/")