Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用自定义文件格式创建TensorFlow数据集_Python_Python 3.x_Image_Numpy_Tensorflow - Fatal编程技术网

Python 使用自定义文件格式创建TensorFlow数据集

Python 使用自定义文件格式创建TensorFlow数据集,python,python-3.x,image,numpy,tensorflow,Python,Python 3.x,Image,Numpy,Tensorflow,我正在尝试创建一个tf.data.Dataset,其中文件名映射到深度图像。我的图像保存为原始二进制文件,每个文件320*240*4字节。图像为320x240像素,4个字节表示一个像素 我不知道如何创建一个解析函数,该函数将采用tf.Tensor文件名,并返回包含我的图像的(240320)tf.Tensor 这是我试过的 import tensorflow as tf import numpy as np import struct import math from os import list

我正在尝试创建一个tf.data.Dataset,其中文件名映射到深度图像。我的图像保存为原始二进制文件,每个文件320*240*4字节。图像为320x240像素,4个字节表示一个像素

我不知道如何创建一个解析函数,该函数将采用tf.Tensor文件名,并返回包含我的图像的(240320)tf.Tensor

这是我试过的

import tensorflow as tf
import numpy as np
import struct
import math
from os import listdir


class Dataset:
    def __init__(self):
        filenames = ["./depthframes/" + f for f in listdir("./depthframes/")]

        self._dataset = tf.data.Dataset.from_tensor_slices(filenames).map(Dataset._parse)

    @staticmethod
    def _parse(filename):
        img = DepthImage(filename)
        return img.frame


class DepthImage:
    def __init__(self, path):
        self.rows, self.cols = 240, 320
        self.f = open(path, 'rb')
        self.frame = []
        self.get_frame()

    def _get_frame(self):
        for row in range(self.rows):
            tmp_row = []
            for col in range(self.cols):
                tmp_row.append([struct.unpack('i', self.f.read(4))[0], ])
            tmp_row = [[0, ] if math.isnan(i[0]) else list(map(int, i)) for i in tmp_row]
            self.frame.append(tmp_row)

    def get_frame(self):
        self._get_frame()
        self.frame = tf.convert_to_tensor(np.array(self.frame).reshape(240, 320))


if __name__ == "__main__":
    Dataset()
我的错误如下:

File "C:/Users/gcper/Code/STEM/msrdailyact3d.py", line 23, in __init__ 
    self.f = open(path, 'rb')
TypeError: expected str, bytes or os.PathLike object, not Tensor

根据@kvsih的建议,以下解决方案有效

self._dataset = tf.data.Dataset.from_tensor_slices(filenames)\
    .map(lambda name: tf.py_func(self._parse, [name], tf.int32))
另外,
get\u frame
不能返回张量
self.\u parse
必须返回上文lambda中定义的
tf.int32
。以下代码将替换
get\u frame

def get_frame(self):
    self._get_frame()
    self.frame = np.array(self.frame).reshape(240, 320)

您正在tf张量上使用python操作。您有一种方法可以将python函数集成到tensorflow操作中。