如何从txt文件中读取特定的单词和数字并将它们保存在矩阵中

时间:2014-10-18 12:47:04

标签: matlab

我正在进行对象检测,并希望从7481个文本文件生成基本事件.mat文件。这些文件的内容都采用以下格式:

car 0.00 0 -1.82 804.97 167.34 995.43 327.94 1.63 1.48 2.37 3.23 1.59 8.55 -1.47   
misc 0.00 5 2.35 254.24 -2 305.25 7.6 4.58 5.35 2.35 1.35 2.35 3.36 1.56  
bicycle 0.00 1 2 3 1 2.3 4.25 3.1 2 1 2.4 1.25 46.5 1.54  
don't know 0.00 2.21 5.32 1.23 5.25 9.46 4.35 1.25 5 1 3 2 4 1.54

即,在每个文本文件中,有几行(不同文件中的行数不同),并且在每一行中,第一项是类型(car / misc / people / van / don&t; t知道....),下面的类型是由空格分隔符分隔的14个双数字。我想做以下事情:

  1. 检查类型是否为car / van / misc / tram
  2. 如果类型是其中之一,则在以下14个数字中,选取第4,第5,第6,第7和第14个数字,然后将它们保存在矩阵中
  3. 对文件夹中的所有文本文件重复1和2,然后生成包含地面实况信息的mat文件
  4. 现在我的代码就像:

    clc;
    clear all;
    DetDir = '/scratch/yangj/project/car_dataset/training/label/';
    F = dir([DetDir,'/*.txt']);
    for frameNum = 1:7481
    
    detFile = [DetDir,F(frameNum).name]; 
    
    fid = fopen(detFile);
    
    while 1
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    str = tline;
    
    end
    fclose (fid);
    
    end
    

    我认为我应该在while循环中进行类型检查和数字拾取,但我不知道如何编写代码来实现我的目标。

    你可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

如果您的分隔符是空格,don't know语句非常烦人。我建议首先使用这个好的(Perl)函数replaceinfile来修复它,它可以更改{{ 1}}例如don't know

如果修复了,以下情况应该有效:

don't_know

如果您不更改文件中的N = numel(F); C = cell(N,1); for idx = 1:N % get the data fid = fopen([DetDir F(idx).name]); data = textscan(fid,'%s %f %f %f %f %f %f %f %f %f %f %f %f %f %f'); fclose(fid); % combine all numeric data M = horzcat(data{2:end}); % check for a string match b = cellfun(@(type) strcmp(data{1}, type), {'car','van','misc','tram'}, 'uni', 0); % keep only the interesting part of the numeric data C{idx} = M(any(horzcat(b{:}),2),[4 5 6 7 14]); end % combine and save gt = vertcat(C{:}); save('gt.mat', 'gt'); 语句,代码实际上仍会运行,但(通常)不会产生所需的don't know矩阵。


回答有关添加其他内容的问题:

构建gt后,只需添加:

M

通过将M(:,end+1) = M(:,6)-M(:,4); % this becomes the 15-th value 更改为

来完成包含文件编号
C{idx} = M(any(horzcat(b{:}),2),[4 5 6 7 14]);