python实现批量图片格式转换

yipeiwu_com6年前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设计】。

相关文章

python使用socket 先读取长度,在读取报文内容示例

本文实例讲述了python使用socket 先读取长度,在读取报文内容。分享给大家供大家参考,具体如下: tlpmts1:~/sbin # cat test9105.py # -*-...

python如何保证输入键入数字的方法

要求:python写一个要求用户输入数字,如果不是数字就一直循环要求输入,直到输入数字为止的代码 错误打开方式: while True: ten=input('Enter a n...

Python字符串中查找子串小技巧

惭愧啊,今天写了个查找子串的Python程序被BS了… 如果让你写一个程序检查字符串s2中是不是包含有s1。也许你会很直观的写下下面的代码: 复制代码 代码如下: #determine...

解决django前后端分离csrf验证的问题

第一种方式ensure_csrf_cookie 这种方方式使用ensure_csrf_cookie 装饰器实现,且前端页面由浏览器发送视图请求,在视图中使用render渲染模板,响应给前...

Python中让MySQL查询结果返回字典类型的方法

Python的MySQLdb模块是Python连接MySQL的一个模块,默认查询结果返回是tuple类型,只能通过0,1..等索引下标访问数据 默认连接数据库: 复制代码 代码如下: M...