【问题标题】:how to convert a directory of image on png to jpg in python如何在python中将png上的图像目录转换为jpg
【发布时间】:2020-01-28 14:48:15
【问题描述】:
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
..

【问题讨论】:

    标签: python-3.x python-2.7 png python-imaging-library jpeg


    【解决方案1】:

    使用 pathlib 进行文件系统访问。那是更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)
    

    【讨论】:

      【解决方案2】:

      这样工作:

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

      【讨论】:

      • 请问将JPEG质量设置为200的目的是什么?
      猜你喜欢
      • 2012-06-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2011-10-21
      • 2013-05-10
      • 2018-12-05
      相关资源
      最近更新 更多