记录如何在tensorflow 中对batch中的每个image进行不同的操作

  tensorflow 是不支持像numpy一样对tensor/array 进行直接赋值的, 并且如果输出[batchsize, img_height, img_width, img_ch]的tensor, 如何对一个batch中的每个图片进行操作也比较麻烦。

 

解决这个问题主要是靠tensorflow的两个函数。

1、tf.map_fn(fn, elems, dtype)

这个函数有很多博客讲的很好,随便一搜就可以。  但是博客上一般都默认elems只有一个值,比如对视频进行卷积操作。 如果对每个batch中的每个图片进行操作呢?

看API:

"""map on the list of tensors unpacked from `elems` on dimension 0.

The simplest version of `map_fn` repeatedly applies the callable `fn` to a
sequence of elements from first to last. The elements are made of the
tensors unpacked from `elems`. `dtype` is the data type of the return
value of `fn`. Users must provide `dtype` if it is different from
the data type of `elems`.
这里介绍了函数是用来干嘛的。 简单地说就是函数把elements中的元素按照dimension 0展开,然后重复的给fn运行。dtype代表的是fn的返回值类型。

Suppose that `elems` is 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TensorFlow 2.0 提供了一些工具来实现图像增强(image augmentation),可以通过对原始图像进行变换,生成更多的训练数据,从而提高模型的泛化能力。下面是使用 TensorFlow 2.0 实现图像增强的基本步骤: 1. 导入相关模块和库 ```python import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator ``` 2. 创建 ImageDataGenerator 对象,并设置相关参数 ```python datagen = ImageDataGenerator( rescale=1./255, rotation_range=20, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') ``` 上述代码,`rescale` 参数用于将像素值缩放到 0 到 1 的范围内,`rotation_range` 用于旋转图像的角度范围,`width_shift_range` 和 `height_shift_range` 用于水平和垂直平移图像的范围,`shear_range` 用于剪切变换,`zoom_range` 用于随机缩放图像,`horizontal_flip` 用于水平翻转图像,`fill_mode` 用于填充新创建的像素。 3. 使用 `datagen.flow_from_directory()` 方法加载图像数据集,并设置相关参数 ```python train_generator = datagen.flow_from_directory( 'path/to/training/data', target_size=(150, 150), batch_size=32, class_mode='binary') ``` 上述代码,`train_generator` 是一个可迭代对象,可以用于获取图像增强后的训练数据。`flow_from_directory()` 方法用于从指定目录加载图像数据集,`target_size` 参数用于将图像大小调整为指定的大小,`batch_size` 参数用于指定每个批次的图像数量,`class_mode` 参数用于指定分类问题的类型。 4. 使用 `model.fit()` 方法训练模型,并使用 `train_generator` 作为输入数据 ```python model.fit( train_generator, steps_per_epoch=100, epochs=50) ``` 上述代码,`steps_per_epoch` 参数用于指定每个 epoch 的迭代次数,`epochs` 参数用于指定训练轮数。 这些步骤将会生成一些经过随机增强的图像,以及对应的标签,用于训练模型。需要注意的是,这些步骤只是一个基本示例,实际应用需要根据具体的需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值