python - Tensorflow:如何编码和读取bmp图像?

标签 python image tensorflow bmp

我正在尝试读取 .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 file format非常简单,由一堆标题和几乎原始像素数据组成。这就是 BMP 图像如此大的原因。我想这也是 TensorFlow 开发人员懒得编写函数来将数组(表示图像)编码为这种格式的原因。现在仍然很少有人使用它。建议使用 PNG 来代替,它对图像执行无损压缩。或者,如果您可以处理有损压缩,请使用 JPG。

TensorFlow 没有对图像编码做任何特殊的事情。它只是返回表示该格式图像的字节,类似于 matplotlib 在执行 save_fig 时所做的操作(除了 MPL 还将字节写入文件)。

假设您生成一个 numpy 数组,其中顶行为 0,底行为 255。这是一个数字数组,如果您将其视为图片,那么这是一个数字数组>,代表 2 个水平带,顶部一个黑色,底部一个白色。

如果您想在另一个程序 (GIMP) 中查看此图片,您需要以标准格式编码此信息,例如 PNG。编码意味着添加一些 header 和元数据,并且可以选择压缩数据。


现在更清楚什么是编码,我建议您使用 PNG 图像。

with tf.gfile.FastGFile('image.png', 'rb') as f:
    # get the bytes representing the image
    # this is a 1D array (string) which includes header and stuff
    raw_png = f.read()

    # decode the raw representation into an array
    # so we have 2D array representing the image (3D if colour) 
    image = tf.image.decode_png(raw_png)

    # augment the image using e.g.
    augmented_img = tf.image.random_brightness(image)

    # convert the array back into a compressed representation
    # by encoding it into png
    # we now end up with a string again
    augmented_png = tf.image.encode_png(augmented_img, compression=9) 

    # Write augmented_png 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=[augmented_png])}))
    writer.write(example.SerializeToString())

    # Read img from file
    dataset = tf.data.TFRecordDataset(<img_file>)
    dataset = dataset.map(parse_img_fn)

有一些重要的建议:

  • 不要使用numpy.tostring。这会返回一个HUUGE表示,因为每个像素都表示为 float ,并且它们都是连接在一起的。没有压缩,什么都没有。尝试检查文件大小:)

  • 无需使用 tf.Session 传回 python。您可以在TF端执行所有操作。这样您就拥有了一个输入图,您可以将其重新用作输入管道的一部分。

关于python - Tensorflow:如何编码和读取bmp图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871281/

相关文章:

python - 模型有多个输出时的ModelCheckpoint监控值

python - 按索引过滤并在 numpy 中展平,如 tf.sequence_mask

python - 值错误 : invalid literal for int() with base 10: '' in python code

image - 如何在使用 refline 时阻止 MATLAB 调整图像大小或缩放图像

iOS:自定义键盘:我想将图像发送到 textDocumentProxy(输入控件)

tensorflow - 如何实现超像素池化层?

javascript - ndb.key() -> 使用 Javascript 执行此操作

python - 在 Python 中检查非负偶数

python - 在没有 App Engine 的情况下运行谷歌云端点

javascript - 为什么即使没有 src 标签,图像 'complete' 属性也总是返回 true?