我想使用 tfrecord 來處理大量的 MRI 影像,但我不知道該怎么做。下面是我的代碼、錯誤和資料鏈接。(抱歉,如果您發現代碼有點長)。
關于資料:
- 484張訓練影像,每張的形狀為(240, 240, 155, 4),這4個數字分別是高度、寬度、層數和通道數。
- 484 個標簽,每個標簽的形狀為 (240, 240, 155)
首先我重新排列我的資料,
image_data_path = './drive/MyDrive/Brain Tumour/Task01_BrainTumour/imagesTr/'
label_data_path = './drive/MyDrive/Brain Tumour/Task01_BrainTumour/labelsTr/'
image_paths = [image_data_path name
for name in os.listdir(image_data_path)
if not name.startswith(".")]
label_paths = [label_data_path name
for name in os.listdir(label_data_path)
if not name.startswith(".")]
image_paths = sorted(image_paths)
label_paths = sorted(label_paths)
并定義一個函式來加載 1 個 nii 檔案。我用尼巴貝爾。
def load_one_sample(image_path, label_path):
image = nib.load(image_path).get_fdata()
label = nib.load(label_path).get_fdata().astype(int) # the original dtype is float64
return image, label
這里我寫了一些輔助函式,'float' 用于影像,'int' 用于標簽:
def float_feature(value):
return tf.train.Feature(float_list = tf.train.FloatList(value = value))
def int64_feature(value):
return tf.train.Feature(int64_list = tf.train.Int64List(value = value))
def create_example(image_path, label_path):
image, label = load_one_sample(image_path, label_path)
image, label = image.ravel(), label.ravel()
feature = {'image': float_feature(image),
'label': int64_feature(label)}
example = tf.train.Example(features = tf.train.Features(feature = feature))
return example
def parse_tfrecord(example):
feature = {'image': tf.io.FixedLenFeature([240, 240, 155, 4], tf.float32),
'label': tf.io.FixedLenFeature([240, 240, 155], tf.int64)}
parsed_example = tf.io.parse_single_example(example, feature)
return parsed_example
然后開始轉換和讀取tfrecord,僅舉一個例子:
test_writer = tf.io.TFRecordWriter('test.tfrecords')
example = create_example(image_paths[0], label_paths[0])
test_writer.write(example.SerializeToString())
serialised_example = tf.data.TFRecordDataset('test.tfrecords')
parsed_example = serialised_example.map(parse_tfrecord)
最后,我嘗試繪制一張影像,但收到此錯誤訊息:
for features in parsed_example.take(1):
plt.imshow(features['image'][:, :, 100, 0])
錯誤: 0' 處的截斷記錄失敗,讀取的位元組數少于請求的位元組數 [Op:IteratorGetNext]
資料鏈接:![如何撰寫tfrecord檔案并讀取它?錯誤是:在 0' 處截斷的記錄失敗,讀取的位元組數比請求的少 [Op:IteratorGetNext]](https://img.uj5u.com/2021/11/30/8ceed02620df4e85a1605ad115a3523a.png)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369685.html
上一篇:TF,訪問資料集物件中元素的檔案名:dataset.group_by_windowgroupbyfilename?
