tensorflow2水平和竖直翻转图片并保存

该代码段展示了如何利用TensorFlow库对图像进行左右和上下翻转。首先读取图像文件,然后进行随机翻转操作,接着将翻转后的图像转换回JPEG格式并保存。整个过程遍历指定文件夹内的所有图片,保存翻转后的两个版本。
摘要由CSDN通过智能技术生成
def flip_function(img_path,save_path):
    img = tf.io.read_file(img_path)
    img_original = tf.image.decode_jpeg(img, channels=3)

    img1 = tf.image.random_flip_left_right(img_original)
    img2 = tf.image.random_flip_up_down(img_original)

    img1 = tf.cast(img1, dtype=tf.uint8)
    img2 = tf.cast(img2, dtype=tf.uint8)

    img1 = tf.image.encode_jpeg(img1)
    img2 = tf.image.encode_jpeg(img2)

    img1_save_path = save_path + '_flip1' + '.jpg'
    with tf.io.gfile.GFile(img1_save_path, 'wb') as file:
        file.write(img1.numpy())

    img2_save_path = save_path + '_flip2' + '.jpg'
    with tf.io.gfile.GFile(img2_save_path, 'wb') as file:
        file.write(img2.numpy())


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
    # 要保存的图片
    save_path = save_path+filename[:-4]
    flip_function(img_path,save_path)

原始图片:

运行结果:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值