MNE Python 快速上手教程:从采集到可视化

从环境配置到LSL数据接入,再到预处理和频谱分析,手把手教你用MNE Python处理神经信号数据。

1. 环境配置

首先安装Anaconda或Miniconda,然后创建虚拟环境并安装必要的包:

# 创建虚拟环境
conda create -n mne_env python=3.10
conda activate mne_env

# 安装MNE Python
pip install mne

# 安装数据处理相关包
pip install numpy scipy matplotlib jupyter

# 安装LSL支持
pip install pylsl

# 安装深度学习相关(可选)
pip install torch tensorflow

验证安装是否成功:

python -c "import mne; print(mne.__version__)"
# 输出示例:1.6.0

2. 从LSL数据流接入实时数据

宸络采集终端通过LSL协议实时输出数据。以下代码演示如何接入LSL流:

import numpy as np
import pylsl
from pylsl import StreamInlet, resolve_stream

# 查找LSL流
print("正在查找LSL数据流...")
streams = resolve_stream('type', 'EEG')
if not streams:
    print("未找到LSL流,请确保采集终端已启动")
    exit()

# 连接数据流
inlet = StreamInlet(streams[0])
print(f"已连接: {streams[0].name()}")

# 采集10秒数据
sampling_rate = 500  # Hz
duration = 10  # 秒
total_samples = sampling_rate * duration

chunk = []
for i in range(total_samples):
    sample, timestamp = inlet.pull_sample()
    chunk.append(sample)

data = np.array(chunk)
print(f"数据形状: {data.shape}")  # (samples, channels)

3. 数据预处理

将原始数据转换为MNE的Raw对象,并进行预处理:

import mne

# 创建info结构
ch_names = ['Fz', 'Cz', 'Pz', 'Oz', 'C3', 'C4', 'T7', 'T8']
ch_types = ['eeg'] * 8
sfreq = 500  # 采样率

info = mne.create_info(ch_names, sfreq, ch_types)

# 创建Raw对象
raw = mne.io.RawArray(data.T, info)

# 添加标准电极位置
montage = mne.channels.make_standard_montage('standard_1020')
raw.set_montage(montage)

# 滤波处理
raw.filter(1, 40, fir_design='firwin')

# 去除工频干扰
raw.notch_filter(50)

# 查看数据概览
print(raw)
raw.plot(n_channels=8, duration=5, scalings='auto')

4. 频谱分析

计算各频段的功率谱密度:

import matplotlib.pyplot as plt

# 计算功率谱密度
spectrum = raw.compute_psd(fmin=1, fmax=40)

# 绘制频谱图
fig = spectrum.plot(picks='eeg', average=True)
plt.suptitle('功率谱密度', fontsize=14)
plt.show()

# 提取频段功率
delta = spectrum.get_data(fmin=1, fmax=4)
theta = spectrum.get_data(fmin=4, fmax=8)
alpha = spectrum.get_data(fmin=8, fmax=13)
beta = spectrum.get_data(fmin=13, fmax=30)

print(f"Delta功率: {delta.mean():.3f}")
print(f"Theta功率: {theta.mean():.3f}")
print(f"Alpha功率: {alpha.mean():.3f}")
print(f"Beta功率: {beta.mean():.3f}")

5. 事件相关电位(ERP)分析

当实验中有事件标记时,可以进行ERP分析:

# 假设我们有事件标记
events = mne.find_events(raw, stim_channel='STI')

# 创建epochs
epochs = mne.Epochs(raw, events, event_id={'target': 1, 'non-target': 2},
                    tmin=-0.2, tmax=0.8, baseline=(-0.2, 0),
                    preload=True)

# 绘制ERP波形
fig = epochs.plot_image(picks='Cz')

# 计算并绘制ERP差异波
target_evoked = epochs['target'].average()
non_target_evoked = epochs['non-target'].average()

mne.viz.plot_compare_evokeds(
    dict(target=target_evoked, non_target=non_target_evoked),
    picks='Cz', combine='mean'
)

完整的示例代码和实验模板可在我们的技术文档中找到。如需更多帮助,请联系 tech@chenluoai.com

获取完整SDK和技术文档

欢迎联系我们获取完整的Python SDK、20+实验场景示例代码和技术文档。

联系我们获取文档