import tensorflow as tf
import os
def resize_function(img_path,img_save_path):
img = tf.io.read_file(img_path)
# 解码图片
# img = tf.image.decode_png(img,channels=3) # RGBA,PNG
img = tf.image.decode_jpeg(img,channels=3) # RGBA,jpg
hight = img.shape[0]
width = img.shape[1]
print('original shape:',img.shape)
img = tf.image.resize(img,[int(hight*0.5),int(width*0.5)])
print('resized shape:',img.shape)
# 转换张量数据类型
img = tf.cast(img, dtype=tf.uint8)
# 编码为图片
# img = tf.image.encode_png(img) # PNG
img = tf.image.encode_jpeg(img) # jpeg
# 保存图片
with tf.io.gfile.GFile(img_save_path,'wb') as file:
file.write(img.numpy())
"""单张图片"""
# img_path = 'C:/Users/a/Downloads/dog.png' # PNG格式
# img_path = 'C:/Users/a/Downloads/001.jpg' # JPEG格式
# save_path = img_path[:-4]+'_resize.jpg' # 要保存为的图片
# resize_function(imgs_path,save_path)
"""很多图片"""
imgs_path = 'C:/Users/a/Downloads/test_images/' # 文件所在文件夹
save_path = 'C:/Users/a/Downloads/test_save/' # 保存文件文件夹
filenames = os.listdir(imgs_path)
for filename in filenames:
# 要处理的图片路径
img_path = imgs_path+filename
# 要保存的图片
img_save_path = save_path+filename[:-4]+'_resize.jpg'
resize_function(img_path, img_save_path)