You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中读取16位无符号大端序二进制文件并转NumPy数组

读取分块GZIP压缩的16位无符号大端序二进制文件为NumPy数组

文件核心参数

  • 总维度:64 × 384 × 384
  • 分块大小:32 × 128 × 128
  • 数据类型:16位无符号大端序整数(对应NumPy的'>u2')
  • 压缩方式:GZIP(level=2)

实现逻辑

由于文件采用分块压缩存储,无法直接用numpy.fromfile一次性读取,需逐个解压分块后拼接成完整数组:

  1. 计算总块数:总维度各轴除以块大小,得到2×3×3=18个独立压缩块
  2. 依次读取每个GZIP块,解压后转换为对应数据类型的数组
  3. 按分块顺序将所有子块填充到目标数组的对应位置,恢复原始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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:40:50