[英]How to efficiently write a binary file containing mixed label and image data
cifar10教程將二進制文件作為輸入處理。 這些CIFAR10數據文件上的每個記錄/示例均包含混合標簽(第一個元素)和圖像數據信息。 本頁的第一個答案顯示了如何使用ndarray.tofile()從numpy數組(在每一行中累積標簽和圖像數據信息)寫入二進制文件,如下所示:
import numpy as np
images_and_labels_array = np.array([[...], ...], dtype=np.uint8)
images_and_labels_array.tofile("/tmp/images.bin")
當最大類數為256時,這對我來說是完美的,因為uint8數據類型已足夠。 但是,當最大類數大於256時,則必須更改images_and_labels_array中的dtype = np.uint16。 結果只是大小增加了一倍。 我想知道是否有一種有效的方法來克服它。 如果是,請提供示例。
當我寫二進制文件時,我通常只使用python模塊struct ,它的工作方式如下:
import struct
import numpy as np
image = np.zeros([2, 300, 300], dtype=np.uint8)
label = np.zeros([2, 1], dtype=np.uint16)
with open('data.bin', 'w') as fo:
s = image.shape
for k in range(s[0]):
# write label as uint16
fo.write(struct.pack('H', label[k, 0]))
# write image as uint8
for i in range(s[1]):
for j in range(s[2]):
fo.write(struct.pack('B', image[k, i, j]))
這將導致300 * 300 * 2 + 2 * 1 * 2 = 180004字節的大二進制文件。 它可能不是完成工作的最快方法,但對我而言,到目前為止,它的運行速度足夠快。 有關其他數據類型,請參見文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.