创建一个三维矩阵
def create_matrix(len, rows, cols):
matrix_list = []
for i in range(len):
matrix = []
for j in range(rows * cols):
matrix.append((i + 1) * 10 + (j + 1))
matrix = np.reshape(matrix, (rows, cols))
matrix_list.append(matrix)
matrix_list = np.array(matrix_list, dtype='ubyte')
return matrix_list
主函数调用
# 生成矩阵测试
matrix = create_matrix(2, 3, 4)
# 类型
print(type(matrix))
# 维度
print(matrix.shape)
# 输出
print(matrix)
测试输出
<class 'numpy.ndarray'>
(2, 3, 4)
[[[11 12 13 14]
[15 16 17 18]
[19 20 21 22]]
[[21 22 23 24]
[25 26 27 28]
[29 30 31 32]]]
将矩阵写入文件中
def write_matrix(matrix, filename):
type2code_dict = {'uint8': 0x08, 'int8': 0x09, 'int16': 0x0B, 'int32': 0x0C, 'float32': 0x0D, 'float64': 0x0E}
# 以字节方式打开文件句柄
with open(filename, 'wb') as f:
# 维度
shapes = matrix.shape
# 文件头
# 按照要求存储文件。大端优先,占位,数据类型,维度数量
file_head_fmt = '>HBB'
file_head = struct.pack(file_head_fmt, 0, 8, len(shapes))
# 查看类型
print(type(file_head))
# 参看文件头
print(file_head)
f.write(file_head)
file_head_fmt = '>I'
# 顺序将维度存储到文件
for i in shapes:
file_head = struct.pack(file_head_fmt, i)
f.write(file_head)
# 将矩阵存储到文件
f.write(matrix)
主函数调用
write_matrix(matrix, 'D:/matrix.idx')
测试输出
<class 'bytes'>
b'\x00\x00\x08\x03'
从文件中读取矩阵
def read_matrix(filename):
code2type_dict = {0x08: 'B', 0x09: 'b', 0x0B: 'h', 0x0c: 'i', 0x0D: 'f', 0x0E: 'd'}
with open(filename, 'rb') as f:
data_buff = f.read()
off_set = 0
file_head_fmt = '>HBB'
_, elem_code, dimlen = struct.unpack_from(file_head_fmt, data_buff, off_set)
off_set += struct.calcsize(file_head_fmt)
# {}是字符串的占位符
file_head_fmt = '>{}I'.format(dimlen)
shapes = struct.unpack_from(file_head_fmt, data_buff, off_set)
off_set += struct.calcsize(file_head_fmt)
# 矩阵的维度的连乘,代表一共有几个元素值
data_fmt = '>' + str(np.prod(shapes)) + code2type_dict[elem_code]
matrix = struct.unpack_from(data_fmt, data_buff, off_set)
matrix = np.reshape(matrix, shapes).astype('uint8')
return matrix
主函数调用
matrix2 = read_matrix('D:/matrix.idx')
print(type(matrix2))
print(matrix2.shape)
print(matrix2)
测试输出
<class 'numpy.ndarray'>
(2, 3, 4)
[[[11 12 13 14]
[15 16 17 18]
[19 20 21 22]]
[[21 22 23 24]
[25 26 27 28]
[29 30 31 32]]]