tensorflow2批量缩放图片大小并保存

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)



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值