最近需要把一些图片格式转成一样的,查找了一下大神们写的资料,用TensorFlow中的图片处理函数可以做reshape,于是就写了一段代码:读取一个文件夹中的所有图片,批量处理成同样格式的;
import tensorflow as tf
import os
import numpy as np
import matplotlib.pyplot as plt
path = 'Z:/jupyter_notebooks/icon_test'
files = os.listdir(path) #列出文件夹下所有的目录与文件
for file in files:#遍历文件夹;
if not os.path.isdir(file): #判断是否是文件夹,不是文件夹才打开
#你想对文件的操作
image_raw_data = tf.gfile.FastGFile(path+"/"+file, 'rb').read()
with tf.Session() as sess:
img_data = tf.image.decode_png(image_raw_data)
img_data.set_shape([1797, 2673, 3])
#print(img_data.eval())
print("文件名是 "+path+"/"+file)
print('原图')
plt.imshow(img_data.eval())
plt.show() # 显示原图
resized = tf.image.resize_images(img_data, [300,300],method=0)
#第一个参数为原始图像,第二个参数为图像大小,第三个参数给出了指定的算法
resized = np.asarray(resized.eval(),dtype='uint8')
plt.imshow(resized)
print("变换后的图形")
plt.show()
encoded_image = tf.image.encode_png(resized)
print("cnm") # 中间老报错,贼气
with tf.gfile.GFile("Z:/jupyter_notebooks/icon_new_test"+"/"+file, 'wb') as f:
f.write(encoded_image.eval())
其中,path是图片所在的文件夹;最后倒数第二行的路径是我们要存放新的图片的路径;
新手上路,有错误请大家指正!
参考:https://blog.csdn.net/zsean/article/details/76383100
https://blog.csdn.net/ZiTeng_Du/article/details/78305356?locationNum=5&fps=1