Skip to content

Instantly share code, notes, and snippets.

@farrajota
Last active September 29, 2016 21:19
Show Gist options
  • Save farrajota/1e926f6d74923b38b171e2045cbad9ee to your computer and use it in GitHub Desktop.
Save farrajota/1e926f6d74923b38b171e2045cbad9ee to your computer and use it in GitHub Desktop.
Convert SVHN metadata .mat file format to .json
function svhn_convert_json(path)
% convert .mat to json files
%% Create .json file
if isempty(path)
error('Must specify a path to the dataset')
end
%% Train
fprintf('Processing train data (1/3):\n');
convert_to_json(path, 'train');
%% Test
fprintf('Processing test data (2/3):\n');
convert_to_json(path, 'test');
%% Extra
fprintf('Processing extra data (3/3):\n');
convert_to_json(path, 'extra');
%% Script complete
fprintf('Convert SVHN to json script complete. \n')
end
function convert_to_json(path, setName)
%% load annotation file
fprintf('==> Load annotation files... ')
data = load(strcat(path,'/',setName,'/digitStruct.mat'));
fprintf('Done.\n')
%% open file
save_path = strcat(path,'/',setName,'.json');
fprintf('==> Open file: %s \n', save_path)
fileID = fopen(save_path,'w');
%% cycle all data and save to file (.json)
fprintf('==> Parsing annotations to the .json file... ')
fprintf(fileID, '"[');
% add field name + bbox
nfiles = size(data.digitStruct,2);
for i=1:1:nfiles
fprintf(fileID, '{\\"name\\": \\"%s\\", \\"bbox\\": [', data.digitStruct(i).name);
for ibb =1:1:size(data.digitStruct(i).bbox,2)
fprintf(fileID, '{\\"height\\": %d,', data.digitStruct(i).bbox(ibb).height);
fprintf(fileID, '\\"width\\": %d,', data.digitStruct(i).bbox(ibb).width);
fprintf(fileID, '\\"left\\": %d,', data.digitStruct(i).bbox(ibb).left);
fprintf(fileID, '\\"top\\": %d,', data.digitStruct(i).bbox(ibb).top);
fprintf(fileID, '\\"label\\": %d}', data.digitStruct(i).bbox(ibb).label);
if ibb < size(data.digitStruct(i).bbox,2)
fprintf(fileID, ',');
end
end
fprintf(fileID, ']}');
if i < nfiles
fprintf(fileID, ',');
end
end
fprintf(fileID, ']"');
fclose(fileID);
fprintf('Done.\n\n')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment