ele*_*fun 5 python matlab numpy
好的,我有一个来自EEG扫描的数据文件(二进制文件,data.eeg),在matlab中读取文件的代码并绘制一部分数据如下:
sr=400; % Sample Rate
Nyq_freq=sr/2; % Nyquist Frequency
fneeg=input('Filename (with path and extension) :', 's');
t=input('How many seconds in total of EEG ? : ');
ch=input('How many channels of EEG ? : ');
le=t*sr; % Length of the Recording
fid=fopen(fneeg, 'r', 'l'); % Open the file to read
EEG=fread(fid,[ch,le],'int16'); % Read Data -> EEG Matrix
fclose ('all');
plot(EEG(:,3))
Run Code Online (Sandbox Code Playgroud)
这是我尝试"翻译"
from numpy import *
from matplotlib.pylab import *
sample_rate = 400
Nyquist = sample_rate/2.
fneeg = raw_input("Filename (full path & extension): ")
t = int(raw_input("How many secs in total of EEG?: "))
ch = int(raw_input("How many channels of EEG?: "))
le = t*sample_rate
fid = open(fneeg, 'r')
EEG = fromfile(fneeg, int16)
Run Code Online (Sandbox Code Playgroud)
这里的事情让我感到困惑.根据文档,matlab的fread是一种通过fread(loaded_file,size,data_type)读取二进制文件的方法.python中的替代方法是使用numpy的fromfile并使用内置的reshape函数重新整形(根据这个线程:MATLAB到Python fread).我不确定这是如何工作的,甚至与matlab方法有关?如果我的问题令人困惑,我很抱歉,matlab对我来说还是一个新手
编辑:如果你想看看这里的文件是:https://www.dropbox.com/s/zzm6uvjfm9gpamk/data.eeg
Edit2:原始输入的答案是t = 10,ch = 32.事实上,我不知道为什么我现在甚至要求用户输入我想到它..
正如您和@JoeKington 在评论中所讨论的,这应该可行(我删除了用于测试的输入内容)
import numpy as np
sample_rate = 400
Nyquist = sample_rate/2.0
fneeg = 'data.eeg'
t = 10
ch = 32
le = t*sample_rate
EEG = np.fromfile(fneeg, 'int16').reshape(ch, le, order='F')
Run Code Online (Sandbox Code Playgroud)
如果不进行重塑,您将得到:
In [45]: EEG
Out[45]: array([ -39, -25, -22, ..., -168, -586, -46], dtype=int16)
In [46]: EEG.shape
Out[46]: (128000,)
Run Code Online (Sandbox Code Playgroud)
通过重塑:
In [47]: EEG.reshape(ch, le, order='F')
Out[47]:
array([[ -39, -37, -12, ..., 5, 19, 21],
[ -25, -20, 7, ..., 20, 36, 36],
[ -22, -20, 0, ..., 18, 34, 36],
...,
[ 104, 164, 44, ..., 60, -67, -168],
[ 531, 582, 88, ..., 29, -420, -586],
[ -60, -63, -92, ..., -17, -44, -46]], dtype=int16)
In [48]: EEG.reshape(ch, le, order='F').shape
Out[48]: (32, 4000)
Run Code Online (Sandbox Code Playgroud)