gpt4 book ai didi

python - Tensorflow/Keras 意思是图像减法

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:32 26 4
gpt4 key购买 nike

在训练数据生成期间,计算平均图像(不是每个 channel 的平均像素值)

为了改进学习过程,我想对我的网络输入数据(主要由 RGB 图像组成)应用零中心化和归一化的简化方法:

image = (image - meanImage + 1.0) / 2.0

作为 DL 框架,我正在使用 Keras - 加载训练数据 tfrecords 文件,如所述 here被使用。

在我的加载管道的某个点,我有输入 (X) 和输出 (Y) 张量:

def datasetLoader(dataSetPath, batchSize):
dataset = tf.data.TFRecordDataset(dataSetPath)

dataset = dataset.map(_ds_parser, num_parallel_calls=8)

# This dataset will go on forever
dataset = dataset.repeat()

# Set the batchsize
dataset = dataset.batch(batchSize)

# Create an iterator
iterator = dataset.make_one_shot_iterator()

# Create your tf representation of the iterator
X, Y = iterator.get_next()

# Bring the date back in shape
X = tf.reshape(I, [-1, 66, 198, 3])
Y = tf.reshape(Y,[-1,1])

return X, Y

变量 X 和 Y 只是张量,稍后在 tensorflow session 期间填充。

问题是:如何使用本地 png 均值图像执行零中心和归一化任务? .

最佳答案

张量减法

要从一批图像数据中减去平均图像,您可以简单地使用减号运算符(这只是 tf.subtract 的语法糖):

In [28]: x = tf.zeros((2, 3, 3))

In [29]: x
Out[29]:
<tf.Tensor: id=38, shape=(2, 3, 3), dtype=float32, numpy=
array([[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],

[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]], dtype=float32)>

In [30]: mean = tf.eye(3)

In [31]: mean
Out[31]:
<tf.Tensor: id=42, shape=(3, 3), dtype=float32, numpy=
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]], dtype=float32)>

In [32]: x - mean
Out[32]:
<tf.Tensor: id=44, shape=(2, 3, 3), dtype=float32, numpy=
array([[[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., -1.]],

[[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., -1.]]], dtype=float32)>

将图像读入张量

要将 PNG 图像作为 TensorFlow 张量,只需使用 tf.constant 包装一个 numpy 数组:

import cv2

mean_img = cv2.imread('/path/to/the/image')
mean_img_tensor = tf.constant(mean_img)

注意OpenCV默认会将图像读入BGR颜色空间。你可能想把它转换成 RGB 然后:

mean_img = cv2.cvtColor(mean_img, cv2.COLOR_BGR2RGB))

或者使用Python图片库:

from PIL import Image
import numpy as np
mean_img = Image.open('/path/to/image')
mean_img_tensor = tf.constant(np.array(mean_img))

将它们放在一起

既然你使用了 TF Dataset API,我相信 map_and_batch 一定是一个更好的性能解决方案:

def datasetLoader(dataSetPath, batchSize, mean_image_path):
dataset = tf.data.TFRecordDataset(dataSetPath)
mean_img = cv2.cvtColor(cv2.imread(mean_image_path), cv2.COLOR_BGR2RGB)
mean = tf.constant(mean_img)

dataset = dataset.map(_ds_parser, num_parallel_calls=8)

# This dataset will go on forever
dataset = dataset.repeat()

def preprocess(X, Y):
# Bring the date back in shape
X = tf.reshape(X, [-1, 66, 198, 3])
Y = tf.reshape(Y,[-1,1])
X = X - mean
return X, Y

# Set the batchsize
dataset = dataset.apply(tf.contrib.data.map_and_batch(map_func=preprocess, batch_size=batchSize, num_parallel_calls=8))

return dataset.make_one_shot_iterator().get_next()

关于python - Tensorflow/Keras 意思是图像减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com