import cv2 import os import numpy as np from PIL import Image import shutil import sys image_size=144 #改变之后的图片尺寸 source_path=os.getcwd()+"/image/"#等待转换的图片存放地址 types='png' #转换后的图片格式 target_path=os.getcwd()+"/changepng/"#转换过格式的图片存放地址 final_path=os.getcwd()+"/final/"转换过格式和尺寸的图片存放地址 #如果没有转换后的图片存放文件夹,就创建对应的文件夹 if not os.path.exists(target_path): os.makedirs(target_path) if not os.path.exists(final_path): os.makedirs(final_path) #转变图片格式的函数 def changepng(source_path,types): files = [] image_list=os.listdir(source_path) #print(image_list) files = [os.path.join(source_path,_) for _ in image_list] for index,jpg in enumerate(files): if index > 1000: break try: sys.stdout.write(' >>Converting image %d/100000 ' % (index)) sys.stdout.flush() im = Image.open(jpg) png = os.path.splitext(jpg)[0] + "." + types im.save(png) shutil.move(png,target_path) except IOError as e: print('could not read:',jpg) print('error:',e) print('skip it ') sys.stdout.write('Convert Over! ') sys.stdout.flush() #转化图片尺寸的函数 def changesize(source_path): image_lists=os.listdir(source_path) i=0 for file in image_lists: i=i+1 print(os.getcwd()+"/"+file) split=os.path.splitext(file) filename,type=split image_file = source_path+file image_source=cv2.imdecode(np.fromfile(image_file,dtype=np.uint8),cv2.IMREAD_UNCHANGED) image = cv2.resize(image_source, (image_size, image_size)) cv2.imencode('.png',image)[1].tofile(final_path+file) changepng(source_path,types) changesize(target_path)