Matlab how to read txt data in a specific format into the workspace

2 views (last 30 days)
My txt file is organized in the following format:
image filename
n (number of objects of interest in the image)
bounding box for object 1
bounding box for object 2
...
bounding box for object n
For example, the contents in the txt file are listed as follows:
images/1.jpg
1
39.284331 23.721327 88.000000 135.915360
images/2.jpg
4
107.912089 129.898400 62.372022 89.263200
186.266100 61.768245 64.831800 106.847910
298.909724 34.289100 73.830894 105.977200
135.454600 -63.205613 109.739600 176.375026
images/3.jpg
2
136.462492 18.762699 121.522126 187.348778
333.601798 18.139177 104.944018 155.239682
Now I want to read the data file into a structure data (N*1, where N is equal to the number of images) with three fields, file name, number of objects and bounding box. Is there some efficient way to achieve that?

Accepted Answer

KSSV
KSSV on 14 Oct 2016
Edited: KSSV on 14 Oct 2016
fileID = fopen('yourfile.txt','rt');
data = textscan(fileID,'%s','delimiter','\n');
C = data{1} ;
fclose(fileID);
IdxC = strfind(C, 'images');
Idx = find(not(cellfun('isempty', IdxC)));
nimages = length(Idx) ; % total number of images
iwant = struct ; % initialize structure
for i = 1:nimages-1
iwant(i).name = C{Idx(i)} ;
iwant(i).no_objects = str2num(C{Idx(i)+1}) ;
iwant(i).bounding_box = C((Idx(i)+2):(Idx(i+1)-1)) ;
end
iwant(nimages).name = C(Idx(nimages)) ;
iwant(nimages).no_objects = C(Idx(nimages)+1) ;
iwant(nimages).bounding_box = C(Idx(nimages)+2:end) ;
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!