如何在Python中读取16位无符号大端序二进制文件并转NumPy数组
读取分块GZIP压缩的16位无符号大端序二进制文件为NumPy数组
文件核心参数
- 总维度:64 × 384 × 384
- 分块大小:32 × 128 × 128
- 数据类型:16位无符号大端序整数(对应NumPy的
'>u2') - 压缩方式:GZIP(level=2)
实现逻辑
由于文件采用分块压缩存储,无法直接用numpy.fromfile一次性读取,需逐个解压分块后拼接成完整数组:
- 计算总块数:总维度各轴除以块大小,得到
2×3×3=18个独立压缩块 - 依次读取每个GZIP块,解压后转换为对应数据类型的数组
- 按分块顺序将所有子块填充到目标数组的对应位置,恢复原始3D结构
代码实现
import numpy as np import gzip # 配置文件参数 total_shape = (64, 384, 384) # 原始数据维度 (Z, Y, X) chunk_shape = (32, 128, 128) # 分块存储维度 dtype = np.dtype('>u2') # 16位无符号大端序整数 # 初始化空数组用于存储完整数据 full_array = np.empty(total_shape, dtype=dtype) # 读取并处理分块数据 with open('target_file.bin', 'rb') as f: # 按Z-Y-X顺序遍历所有分块 for z_chunk in range(total_shape[0] // chunk_shape[0]): for y_chunk in range(total_shape[1] // chunk_shape[1]): for x_chunk in range(total_shape[2] // chunk_shape[2]): # 读取并解压当前块 compressed_chunk = f.read() decompressed_chunk = gzip.decompress(compressed_chunk) # 转换为NumPy数组并调整形状 chunk_array = np.frombuffer(decompressed_chunk, dtype=dtype).reshape(chunk_shape) # 将块写入目标数组的对应位置 z_start = z_chunk * chunk_shape[0] y_start = y_chunk * chunk_shape[1] x_start = x_chunk * chunk_shape[2] full_array[z_start:z_start+chunk_shape[0], y_start:y_start+chunk_shape[1], x_start:x_start+chunk_shape[2]] = chunk_array # 验证结果 print(f"生成数组形状:{full_array.shape}") print(f"数组数据类型:{full_array.dtype}")
注意事项
- 替换代码中的
'target_file.bin'为实际文件路径 - 若分块存储的轴顺序与代码假设的Z-Y-X不同,需调整循环顺序和数组切片位置
- 若出现解压错误,检查文件是否完整、分块边界是否正确
内容的提问来源于stack exchange,提问作者Captain Ahab
相关产品推荐
相关产品推荐

