【发布时间】:2018-06-15 07:51:44
【问题描述】:
我正在尝试读取 .bmp 图像,对这些图像进行一些扩充,将它们保存到 .tfrecords 文件中,然后打开 .tfrecords 文件并将图像用于图像分类。我知道有一个 tf.image.encode_jpeg() 和一个 tf.image.encode_png() 函数,但是没有 tf.image.encode_bmp() 函数。我知道 .bmp 图像是未压缩的,所以我尝试简单地对图像进行 base64 编码、np.tostring() 和 np.tobytes(),但在尝试解码这些格式时出现以下错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: channels attribute 3 does not match bits per pixel from file <some long number>
我的看法是,tensorflow 在编码为 jpeg 或 png 时,对图像的字节编码做了一些额外的事情;保存有关数组维度等的信息。但是,我对此一无所知,所以任何帮助都会很棒!
一些代码来显示我想要实现的目标:
with tf.gfile.FastGFile(filename, 'rb') as f:
image_data = f.read()
bmp_data = tf.placeholder(dtype=tf.string)
decode_bmp = tf.image.decode_bmp(self._decode_bmp_data, channels=3)
augmented_bmp = <do some augmentation on decode_bmp>
sess = tf.Session()
np_img = sess.run(augmented_bmp, feed_dict={bmp_data: image_data})
byte_img = np_img.tostring()
# Write byte_img to file using tf.train.Example
writer = tf.python_io.TFRecordWriter(<output_tfrecords_filename>)
example = tf.train.Example(features=tf.train.Features(feature={
'encoded_img': tf.train.Feature(bytes_list=tf.train.BytesList(value=[byte_img])}))
writer.write(example.SerializeToString())
# Read img from file
dataset = tf.data.TFRecordDataset(<img_file>)
dataset = dataset.map(parse_img_fn)
parse_img_fn 可以浓缩为以下内容:
def parse_img_fn(serialized_example):
features = tf.parse_single_example(serialized_example, feature_map)
image = features['encoded_img']
image = tf.image.decode_bmp(image, channels=3) # This is where the decoding fails
features['encoded_img']
return features
【问题讨论】:
-
似乎问题只是关于编码 bmp 图像,因为您知道如何阅读它们。您将其编码为 bmp 的用例是什么?为什么不改用 png 呢?
-
好点!我不知道 png 是一种非破坏性压缩算法,因此我尝试修复 bmp 加密。那么,我将使用 png 代替,所以谢谢!无论如何,我还是想知道 tensorflow 是如何加密图像的,以及是否可以加密 bmp 图像。这将是一个了解它如何在幕后工作的绝佳机会!
标签: python image tensorflow bmp