python实现批量图片格式转换

yipeiwu_com7年前Python基础

本文实例为大家分享了python实现批量格式转换的具体代码,供大家参考,具体内容如下

深度学习过程中总是绕不开数据集的制作,有时候实际图片格式或大小可能与需要关心的图片信息不一致,那么我们只能手动做好数据预处理,再进行training dataset.现在将介绍最简单的格式转换问题。可以支持批量图片任意格式转换。

直接上代码:

# 将jpg格式转位png 
import os 
from PIL import Image 
import shutil 
import sys 
 
# Define the input and output image 
output_dirHR = '../data/Mosaic_HR/' 
output_dirLR = '../data/Mosaic_LR/' 
if not os.path.exists(output_dirHR): 
  os.mkdir(output_dirHR) 
if not os.path.exists(output_dirLR): 
  os.mkdir(output_dirLR) 
 
 
 
def image2png(dataset_dir,type): 
  files = [] 
  image_list = os.listdir(dataset_dir) 
  files = [os.path.join(dataset_dir, _) for _ in image_list] 
  for index,jpg in enumerate(files): 
    if index > 100000: 
      break 
    try: 
      sys.stdout.write('\r>>Converting image %d/100000 ' % (index)) 
      sys.stdout.flush() 
      im = Image.open(jpg) 
      png = os.path.splitext(jpg)[0] + "." + type 
      im.save(png) 
      # 将已经转换的图片移动到指定位置 
      ''''' 
      if jpg.split('.')[-1] == 'jpg': 
        shutil.move(png,output_dirLR) 
      else: 
        shutil.move(png,output_dirHR) 
      ''' 
      shutil.move(png, output_dirHR) 
    except IOError as e: 
      print('could not read:',jpg) 
      print('error:',e) 
      print('skip it\n') 
 
  sys.stdout.write('Convert Over!\n') 
  sys.stdout.flush() 
 
 
 
if __name__ == "__main__": 
  current_dir = os.getcwd() 
  print(current_dir) # /Users/gavin/PycharmProjects/pygame 
  data_dir = '/home/gavin/MyProject/python/nesunai_faces/' 
 
  image2png(data_dir,'png') 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

 前言 pyinstaller能够在Windows、Linux等操作系统下将Python脚本打包成可直接运行程序。使Python脚本可以在没有安装Python的环境中直接运行,...

Python模块WSGI使用详解

WSGI(Web Server Gateway Interface):Web服务网关接口,是Python中定义的服务器程序和应用程序之间的接口。 Web程序开发中,一般分为服务器程序和...

Python中super()函数简介及用法分享

首先看一下super()函数的定义: super([type [,object-or-type]]) Return a **proxy object** that delegates m...

对python插入数据库和生成插入sql的示例讲解

如下所示: #-*- encoding:utf-8 -*- import csv import sys,os import pymysql def read_csv(filen...

python操作MongoDB基础知识

首先运行easy_install pymongo命令安装pymongo驱动。然后执行操作:创建连接复制代码 代码如下:In [1]: import pymongoIn [2]: conn...