簡體   English   中英

我是否能夠將目錄路徑轉換為可以輸入 python hdf5 數據表的內容?

[英]Am I able to convert a directory path into something that can be fed into a python hdf5 data table?

我想知道,如何將字符串或路徑轉換為可以輸入 hdf5 表的內容。 例如,我從 Pytorch 數據加載器返回 numpy img 數組、label 和圖像路徑,其中圖像的路徑如下所示:

('mults/train/0/5678.ndpi/40x/40x-236247-16634-80384-8704.png',)

我基本上想將它輸入到這樣的 hdf5 表中:

hdf5_file = h5py.File(path, mode='w')
hdf5_file.create_dataset(str(phase) + '_img_paths', (len(dataloaders_dict[phase]),))

我不確定我想做的事情是否可行。 也許我將這些數據輸入表格是錯誤的。

我努力了:

hdf5_file.create_dataset(str(phase) + '_img_paths', (len(dataloaders_dict[phase]),),dtype="S10")

但是得到這個錯誤:

 hdf5_file[str(phase) + '_img_paths'][i] = str(paths40x)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/anaconda3/lib/python3.6/site-packages/h5py/_hl/dataset.py", line 708, in __setitem__
    self.id.write(mspace, fspace, val, mtype, dxpl=self._dxpl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5d.pyx", line 211, in h5py.h5d.DatasetID.write
  File "h5py/h5t.pyx", line 1652, in h5py.h5t.py_create
  File "h5py/h5t.pyx", line 1713, in h5py.h5t.py_create
TypeError: No conversion path for dtype: dtype('<U64')

在保存字符串數據時,您有兩種選擇:

  1. 您可以在 h5py 或 PyTables 中創建標准數據集,並使用任意大的字符串大小進行定義。 這是最簡單的方法,但存在任意大的字符串不夠大的風險。 :)
  2. 或者,可以創建可變長度數據集。 PyTables 將此數據集類型稱為 VLArray,它使用的 object 是 Class VLStringAtom()。 h5py 使用標准數據集,但 dtype 引用 special_dtype(vlen=str) (請注意,如果您使用的是 h5py 2.10,則可以使用 string_dtype() 代替)。

我創建了一個示例,展示了如何為 PyTables 和 h5py 執行此操作。 它是圍繞您評論中引用的程序構建的。 我沒有復制所有代碼——只是檢索文件名和隨機播放它們所必需的。 另外,我發現的 kaggle 數據集有不同的目錄結構,所以我修改cat_dog_train_path變量以匹配。

from random import shuffle
import glob
shuffle_data = True  # shuffle the addresses before saving
cat_dog_train_path = '.\PetImages\*\*.jpg'

# read addresses and labels from the 'train' folder
addrs = glob.glob(cat_dog_train_path, recursive=True)
print (len(addrs))
labels = [0 if 'cat' in addr else 1 for addr in addrs]  # 0 = Cat, 1 = Dog

# to shuffle data
if shuffle_data:
    c = list(zip(addrs, labels))
    shuffle(c)
    addrs, labels = zip(*c)

# Divide the data into 10% train only, no validation or test
train_addrs = addrs[0:int(0.1*len(addrs))]
train_labels = labels[0:int(0.1*len(labels))]

print ('Check glob list data:')
print (train_addrs[0])
print (train_addrs[-1])

import tables as tb

# Create a hdf5 file with PyTaables and create VLArrays
# filename to save the hdf5 file
hdf5_path = 'PetImages_data_1.h5'  
with tb.File(hdf5_path, mode='w') as h5f:
    train_files_ds = h5f.create_vlarray('/', 'train_files', 
                                        atom=tb.VLStringAtom() )
    # loop over train addresses
    for i in range(len(train_addrs)):
        # print how many images are saved every 1000 images
        if i % 500 == 0 and i > 1:
            print ('Train data: {}/{}'.format(i, len(train_addrs)) )
        addr = train_addrs[i]
        train_files_ds.append(train_addrs[i].encode('utf-8'))

with tb.File(hdf5_path, mode='r') as h5f:
    train_files_ds = h5f.root.train_files
    print ('Check PyTables data:')
    print (train_files_ds[0].decode('utf-8'))
    print (train_files_ds[-1].decode('utf-8'))

import h5py

# Create a hdf5 file with h5py and create VLArrays
# filename to save the hdf5 file
hdf5_path = 'PetImages_data_2.h5'  
with h5py.File(hdf5_path, mode='w') as h5f:
    dt = h5py.special_dtype(vlen=str) # can use string_dtype() wiuth h5py 2.10
    train_files_ds = h5f.create_dataset('/train_files', (len(train_addrs),), 
                                        dtype=dt )

    # loop over train addresses
    for i in range(len(train_addrs)):
        # print how many images are saved every 1000 images
        if i % 500 == 0 and i > 1:
            print ('Train data: {}/{}'.format(i, len(train_addrs)) )
        addr = train_addrs[i]
        train_files_ds[i]= train_addrs[i]

with h5py.File(hdf5_path, mode='r') as h5f:
    train_files_ds = h5f['train_files']
    print ('Check h5py data:')
    print (train_files_ds[0])
    print (train_files_ds[-1])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM