Python 为什么图像(numpy数组)在编码到tfrecord文件之前要转换为字符串?
最近,我正在将图像(比如说位图格式)解码为tfrecord文件 但是,我想知道原因 为什么需要将numpy数组数据转换为字符串类型 在将数据写入tfrecord文件之前 像 下面是我在博客文章中找到的完整代码示例Python 为什么图像(numpy数组)在编码到tfrecord文件之前要转换为字符串?,python,numpy,tensorflow,Python,Numpy,Tensorflow,最近,我正在将图像(比如说位图格式)解码为tfrecord文件 但是,我想知道原因 为什么需要将numpy数组数据转换为字符串类型 在将数据写入tfrecord文件之前 像 下面是我在博客文章中找到的完整代码示例 任何暗示都将不胜感激。提前感谢。为了高效地读取数据,可以将数据序列化并存储在一组100-200MB的文件中,每个文件都可以线性读取。如果数据通过网络传输,则尤其如此。这对于缓存任何数据预处理也很有用 编辑: 当您将映像传输到服务器tensorflow服务器时,这非常方便。在那里,您必须
任何暗示都将不胜感激。提前感谢。为了高效地读取数据,可以将数据序列化并存储在一组100-200MB的文件中,每个文件都可以线性读取。如果数据通过网络传输,则尤其如此。这对于缓存任何数据预处理也很有用 编辑: 当您将映像传输到服务器tensorflow服务器时,这非常方便。在那里,您必须以序列化字符串的形式发送数据 因为有些媒体是为流式文本制作的。你永远不知道-有些协议可能会将你的二进制数据解释为调制解调器之类的控制字符,或者你的二进制数据可能会出错,因为底层协议可能认为你输入了一个特殊的字符组合,比如FTP如何翻译行尾 为了解决这个问题,人们把二进制数据编码成字符。Base64是这些类型的编码之一 为什么是64岁?
因为您通常可以依赖许多字符集中存在的相同64个字符,并且您可以有理由相信您的数据最终将不会被损坏。Hi@Vedanshu,感谢您的回复。但是,为什么字符串类型而不是只存储其他类型,如无符号整数?或者序列化数据最好使用字符串?我想知道这背后的原因:为了序列化图像,必须将其转换为base64字符串。嗨@Vedanshu,我知道,但为什么我必须转换为字符串?这就是我的观点:P
from PIL import Image
...
npimg = np.array(Image.open(img_path))
# My question:
# why do we need to convert numpy array img to stirng?
img_raw = npimg.tostring()
...
# later on, write img_raw to tf.train.Example
from PIL import Image
import numpy as np
import skimage.io as io
import tensorflow as tf
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
tfrecords_filename = 'pascal_voc_segmentation.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename)
original_images = []
filename_pairs = [
('/path/to/example1.jpg',
'/path/to/example2.jpg'),
...,
('/path/to/exampleN.jpg',
'/path/to/exampleM.jpg'),
]
for img_path, annotation_path in filename_pairs:
# read data into numpy array
img = np.array(Image.open(img_path))
annotation = np.array(Image.open(annotation_path))
height = img.shape[0]
width = img.shape[1]
original_images.append((img, annotation))
# My question:
# why do we need to convert numpy array img to stirng?
img_raw = img.tostring()
annotation_raw = annotation.tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(height),
'width': _int64_feature(width),
'image_raw': _bytes_feature(img_raw),
'mask_raw': _bytes_feature(annotation_raw)}))
writer.write(example.SerializeToString())
writer.close()