如何用Python读取Open Ephys的.continuous格式脑电数据?
读取OpenEphys .continuous文件的正确方法
错误原因分析
- pyopenephys/MNE报错
NotADirectoryError:这两个库的对应API是为读取完整的OpenEphys记录目录设计的,而非单个.continuous文件。直接传入单个文件路径自然会触发目录不存在的错误。 - h5py报错
OSError: file signature not found:.continuous是二进制格式文件,并非HDF5格式,h5py不支持解析这类文件。
解决方案
1. 使用pyopenephys读取单个.continuous文件
pyopenephys提供了ContinuousFile类专门处理单个.continuous文件,无需依赖整个记录目录:
from pyopenephys import ContinuousFile # 替换为你的.continuous文件路径 file_path = "your_file.continuous" with ContinuousFile(file_path) as f: # 获取采样率 sample_rate = f.sample_rate # 读取所有通道数据(形状:n_samples × n_channels) eeg_data = f.read() # 获取时间戳数组 timestamps = f.timestamps
2. 使用MNE-Python读取完整记录目录
如果你的.continuous文件属于某个完整的OpenEphys记录(同目录下包含settings.xml等元数据文件),直接传入记录目录路径即可:
import mne # 替换为OpenEphys记录的根目录路径 record_dir = "path/to/openephys_record_folder" # 读取数据,preload=True会将数据加载到内存 raw = mne.io.read_raw_openephys(record_dir, preload=True) # 获取通道数据(形状:n_channels × n_samples) eeg_data = raw.get_data() # 获取采样率 sample_rate = raw.info["sfreq"]
3. 手动解析二进制格式(无依赖方案)
如果第三方库存在版本兼容问题,可以直接按照OpenEphys的.continuous格式规范手动解析:
import numpy as np def parse_continuous_file(file_path): with open(file_path, "rb") as f: # 读取1024字节的头部信息 header = f.read(1024) # 解析头部中的采样率和通道数 sample_rate = np.frombuffer(header[16:20], dtype=np.float32)[0] n_channels = np.frombuffer(header[12:14], dtype=np.int16)[0] # 读取剩余的二进制数据 data_buffer = f.read() data_blocks = [] timestamps = [] offset = 0 # 每个数据块的结构:timestamp(8B) + sample_count(2B) + samples(2B×n_channels×sample_count) + recording_num(2B) while offset < len(data_buffer): # 解析时间戳 ts = np.frombuffer(data_buffer[offset:offset+8], dtype=np.uint64)[0] timestamps.append(ts) offset += 8 # 解析当前块的样本数量 sample_count = np.frombuffer(data_buffer[offset:offset+2], dtype=np.uint16)[0] offset += 2 # 解析当前块的样本数据 samples = np.frombuffer(data_buffer[offset:offset + 2*n_channels*sample_count], dtype=np.int16) samples = samples.reshape(-1, n_channels) data_blocks.append(samples) offset += 2*n_channels*sample_count # 跳过recording_number字段 offset += 2 # 合并所有数据块 full_data = np.vstack(data_blocks) # 将int16原始值转换为微伏(OpenEphys默认增益为0.195μV/单位,可根据设备调整) full_data = full_data * 0.195 return full_data, sample_rate, np.array(timestamps) # 使用示例 eeg_data, fs, timestamps = parse_continuous_file("your_file.continuous")
内容的提问来源于stack exchange,提问作者donut
相关产品推荐
相关产品推荐

