Commit 9d90fd0c authored by Radim Tylecek's avatar Radim Tylecek

evaluation code added

parent e626e219
## Allow to flag private files
classdef YAML
%YAML Serialize a matlab variable to yaml format
% [ X ] = YAML.load( S )
% [ S ] = YAML.dump( X )
% [ X ] = filepath )
% YAML.write( filepath, X )
% YAML.LOAD takes YAML string S and returns matlab variable X.
% YAML.DUMP takes matlab variable X and converts to YAML string S.
% YAML.READ and YAML.WRITE are convenient methods to load and dump
% YAML format directly from a file.
% Examples:
% To serialize matlab object
% >> X = struct('matrix', rand(3,4), 'char', 'hello');
% >> S = YAML.dump(X);
% >> disp(S);
% matrix:
% - [0.9571669482429456, 0.14188633862721534]
% - [0.4853756487228412, 0.421761282626275]
% - [0.8002804688888001, 0.9157355251890671]
% char: hello
% To decode yaml string
% >> X = YAML.load(S);
% >> disp(X)
% matrix: [3x2 double]
% char: 'hello'
% See also: xmlread xmlwrite
properties (Constant)
JARFILE = YAML.jarfile
methods (Static)
function [ S ] = jarfile()
%JARFILE path to the SnakeYAML jar file
S = fileparts(mfilename('fullpath'));
S = [S filesep 'java' filesep 'snakeyaml-1.9.jar'];
function [ X ] = load( S )
%LOAD load matlab object from yaml string
% Load yaml into java obj
yaml = org.yaml.snakeyaml.Yaml;
java_obj = yaml.load(S);
% Convert to matlab object
X = YAML.load_data(java_obj);
function [ S ] = dump( X )
%DUMP serialize matlab object into yaml string
% Convert matlab obj to java obj
yaml = org.yaml.snakeyaml.Yaml();
java_obj = YAML.dump_data(X);
% Dump into yaml string
S = char(yaml.dump(java_obj));
function [ X ] = read( filepath )
%READ read and decode yaml data from file
fid = fopen(filepath,'r');
S = fscanf(fid,'%c',inf);
X = YAML.load( S );
function [] = write( filepath, X )
%WRITE serialize and write yaml data to file
S = YAML.dump( X );
fid = fopen(filepath,'w');
methods(Static, Access=private)
function result = load_data( r )
%LOAD_DATA recursively convert java objects
if isa(r, 'char')
result = char(r);
elseif isa(r, 'double')
result = double(r);
elseif isa(r, 'java.util.Date')
result = DateTime(r);
elseif isa(r, 'java.util.List')
result = cell(r.size(),1);
itr = r.iterator();
i = 1;
while itr.hasNext()
result{i} = YAML.load_data(;
i = i + 1;
result = YAML.merge_cell(result);
elseif isa(r, 'java.util.Map')
result = struct;
itr = r.keySet().iterator();
while itr.hasNext()
key =;
result.(char(key)) = YAML.load_data(...
['Unknown data type: ' class(r)]);
function result = merge_cell( r )
%MERGE_CELL convert cell array to native matrix
% Check eligibility
merge = false;
if all(cellfun(@isnumeric,r))
merge = true;
elseif all(cellfun(@isstruct,r))
f = cellfun(@fieldnames,r,'UniformOutput',false);
if isempty(f) || (numel(unique(cellfun(@numel,f)))==1 && ...
all(cellfun(@(x) all(strcmp(f{1},x)),f)))
merge = true;
% Merge if scalar or row vector
result = r;
if merge
if all(cellfun(@isscalar,r))
result = [r{:}];
elseif all(cellfun(@isrow,r)) &&...
result = cat(1,r{:});
function result = dump_data( r )
%DUMP_DATA convert
if ischar(r)
result = java.lang.String(r);
elseif ~isscalar(r)
result = java.util.ArrayList();
if size(r,1)==1
for i = 1:numel(r)
if iscell(r)
for i = 1:size(r,1)
elseif isnumeric(r)
result = java.lang.Double(r);
elseif isstruct(r)
result = java.util.LinkedHashMap();
keys = fields(r);
for i = 1:length(keys)
elseif iscell(r)
result = java.util.ArrayList();
elseif isa(r,'DateTime')
result = java.util.Date(datestr(r));
['Unsupported data type: ' class(r)]);
<?xml version="1.0" encoding="UTF-8"?>
<ColorScale version="1">
<step r="0" g="0" b="0" pos="0"/>
<step r="0" g="0" b="255" pos="0.05"/>
<step r="0" g="255" b="0" pos="0.1"/>
<step r="255" g="255" b="0" pos="0.15"/>
<step r="255" g="0" b="255" pos="0.2"/>
<step r="255" g="0" b="0" pos="0.25"/>
<step r="255" g="0" b="0" pos="1"/>
echo "*** Computing accuracy ***"
$CC -silent -auto_save OFF -C_EXPORT_FMT PLY \
-o $1 \
-crop -9:-9:-2:10:7:4 \
-SS SPATIAL 0.01 \
-o $GT \
-c2c_dist \
-pop_clouds \
-SF_COLOR_SCALE cmap.xml \
-SS SPATIAL 0.01 \
-save_clouds file "${1%.*}-acc.ply"
echo "*** Computing completeness ***"
$CC -silent -auto_save OFF -C_EXPORT_FMT PLY \
-o $GT \
-o $1 \
-crop -9:-9:-2:10:7:4 \
-c2c_dist \
-pop_clouds \
-SF_COLOR_SCALE cmap.xml \
-save_clouds file "${1%.*}-comp.ply"
\ No newline at end of file
function stats = eval_recon(subName, scene, accRatio, compThreshold, histBins, maxRange)
%% EVAL_RECON - evaluate accuracy and completeness of a model
% acc is distance d (in m) such that [accRatio]% of the reconstruction is within d of the ground truth mesh
% comp is the percent of points on the GTM that are within [compThreshold] mm of the reconstruction
filePath = sprintf('../results/%s/%s_%s',subName,subName,scene); % distances to GT
if ~exist([filePath '-acc.ply'],'file')
%% compute distances using CloudCompare 2.10+ -
% linux: install using "sudo snap install cloudcompare --edge --classic"
if strcmp(scene,'real')
eval(sprintf('!./ %s.ply %s',filePath,scene));
eval(sprintf('!./ %s.ply %s',filePath,scene));
stats.accRatio = accRatio; %0.9;
stats.compThreshold = compThreshold; %0.1;
% histBins = 10;
%% read distances from CloudCompare pcls
compPcl = ply_read([filePath '-comp.ply']);
compDist = abs(compPcl.vertex.('scalar_C2C_absolute_distances'));
accPcl = ply_read([filePath '-acc.ply']);
accDist = abs(accPcl.vertex.('scalar_C2C_absolute_distances'));
%% compute stats
stats.acc = quantile(accDist,accRatio);
stats.comp = mean(compDist<compThreshold);
stats.histBins = linspace(maxRange/histBins/2, maxRange-maxRange/histBins/2, histBins);
stats.histBins = maxRange*logspace(-2,0,histBins);
histComp = hist(compDist,stats.histBins);
stats.histComp = histComp/sum(histComp);
histAcc = hist(accDist,stats.histBins);
stats.histAcc = histAcc/sum(histAcc);
%% plot
bar(stats.histBins,cumsum(stats.histComp)); title(sprintf('completeness: %.1f %%',stats.comp*100)); xlabel('m (GT to X)'); ylim([0 1]);
hold on; plot(compThreshold*[1 1],[0 1],'r-');
bar(stats.histBins,cumsum(stats.histAcc)); title(sprintf('accuracy: %.3f m',stats.acc)); xlabel('m (X to GT)'); ylim([0 1]);
hold on; plot([0 maxRange],accRatio*[1 1],'r-');
subplot(2,2,3); imshow(imread([filePath '-comp.png']));
subplot(2,2,4); imshow(imread([filePath '-acc.png']));
warning('eval: missing pngs');
print([filePath '-geom.pdf'],'-dpdf','-bestfit');
%% evaluate semantics
resDir = '../results';
submissions = {'snbasic-frNone'}; % each has separate folder
subnames = {'SegNet-basic'};
if 0
resName = 'real';
scenes = {'test_around_garden' };
dataPath = '../gt';
evalFrames = 140:10:1480;
evalCams = [0 2];
camType = 'uvc_camera_cam';
resName = 'test';
scenes = { 'clear_0288','cloudy_0288','overcast_0288','sunset_0288','twilight_0288'};
dataPath = '../gt';
evalFrames = 1:100;
evalCams = 0:2:9;
camType = 'vcam';
%% read label def
def = read_labels('../calibration');
labelCount = length(def.labelNames);
%% subs
for m = 1:length(submissions)
subName = submissions{m};
subTitle = subnames{m};
mstats.conf = zeros(labelCount-1,labelCount-1,length(scenes));
mstats.acc = zeros(length(scenes),length(evalCams));
%% scenes
for s = 1:length(scenes)
scene = scenes{s};
sceneName = strrep(scene,'_','-');
modelPath = sprintf('%s/%s/%s-mesh.ply',resDir,subName,subName);
if 0
%% read models
model = read_model(modelPath);
figure(101); clf; trimesh(model.tri,model.vtx(:,1),model.vtx(:,2),model.vtx(:,3)); axis equal; title('submitted');
%% project to images
stats.conf = zeros(labelCount-1,labelCount-1,length(evalCams));
stats.acc = zeros(length(evalCams),length(evalFrames));
for c = 1:length(evalCams)
%% select camera
idCam = evalCams(c);
acc = zeros(length(evalFrames),1);
conf = zeros(labelCount-1,labelCount-1,length(evalFrames));
vid = VideoWriter(sprintf('%s/%s/%s/sem-vid-cam%d.avi',resDir,subName,scene,idCam));
vid.FrameRate = 3;
vid.Quality = 100;
for i = 1:length(evalFrames)
%% select frame
idFrame = evalFrames(i);
basePath = sprintf('%s/%s/%s_%d/%s_%d_f%05d',dataPath,scene,camType,idCam,camType,idCam,idFrame);
txtPath = [basePath '_cam.txt'];
clsPath = sprintf('%s/%s/%s/%s_%d/%s_%d_f%05d_undist.png',resDir,subName,scene,camType,idCam,camType,idCam,idFrame);
if exist(txtPath,'file')
% %% read from colmap txt
% txtCam = load(txtPath);
% cam.f = txtCam(1:2); % fx fy
% cam.c = txtCam(3:4); % cx cy
% cam.q = txtCam(5:8); % qw qx qy qz
% cam.t = txtCam(9:11); % tx ty tz
% cam.resolution = [752, 480];
% cam.R = quat2rotm(cam.q);
% cam.K = eye(3);
% cam.K(1,1) = cam.f(1);
% cam.K(2,2) = cam.f(2);
% cam.K(1,3) = cam.c(1);
% cam.K(2,3) = cam.c(2);
% fprintf('Cam pose loaded from %s\n',txtPath);
% %% mesh projection
% camParsMesh{1} = struct('TcV', cam.t, ...
% 'RcM', cam.R, ...
% 'fcV', [cam.K(1,1); cam.K(2,2)], ...
% 'ccV', [cam.K(1,3); cam.K(2,3)], ...
% 'imSizeV', [cam.resolution(2); cam.resolution(1)]);
% projZrange = [1e-3; 2000];
% %% gt depths
% [projDmap, cx] = RenderDepthMesh(gtmodel.tri, gtmodel.ptXh(:,1:3), camParsMesh{1}, ...
% [cam.resolution(2); cam.resolution(1)], projZrange, 1, 0);
if exist(clsPath,'file')
%% load anot from file
imgAnot = imread(clsPath);
imgAnot = flip(imgAnot,2);
projColor = RenderColorMesh(model.tri, model.ptXh(:,1:3), single(model.vtxColor)/255, ...
camParsMesh{1}, [cam.resolution(2); cam.resolution(1)], projZrange, 1);
%% tranform color to labels
projColor = uint8(projColor);
imgAnot = uint8(rgbmapind(projColor,uint8(def.labelColors*255))) - 1;
imgAnot(imgAnot(:)==0) = 9;
stats.acc(c,i) = nan;
%% load gt anot
gtAnot = imread([basePath '_gtr.png']);
gtAnot(gtAnot(:)>10) = 9;
gtAnotTest = gtAnot;
gtValid = true(size(gtAnot));
% gtValid = (projDmap<1);
% gtValid = imdilate(gtValid,strel('diamond',3));
gtValid(gtAnot(:)==0) = 0;
gtAnotTest(gtValid==0) = 0;
gtDiff = double(gtAnotTest~=imgAnot);
gtDiff(gtAnotTest==0) = -1;
%% stats
stats.acc(c,i) = sum(gtDiff(:)==0) / sum(gtDiff(:)>=0);
conf(:,:,i) = confMatrix(gtAnotTest(gtValid(:)),imgAnot(gtValid(:)),labelCount-1);
%confMatrixShow(conf(:,:,i), def.labelNames(2:end), {'FontSize',12}, 2, 1 ); colormap hot; ylabel('GT');
%% plot
subplot(2,2,1); imshow(imgAnot,def.labelColors); axis image; title(sprintf('cam %d frame %d: submitted labels',idCam,idFrame));
subplot(2,2,2); % imagesc(projDmap); axis image; title('gt depths');
imagesc(max(conf(:))-conf(:,:,i)); axis image; colormap hot; ylabel('GT'); title('confusion matrix');
subplot(2,2,3); imshow(gtAnotTest,def.labelColors); axis image; title('gt labels (masked)');
subplot(2,2,4); imshow(gtDiff+2,[0 0 0; 0.5 0.5 0.5; 1 0 0]); axis image; title(sprintf('error mask (accuracy = %.03f)',stats.acc(c,i))); %colormap jet;
%% camera totals
camconf = sum(conf,3);
stats.conf(:,:,c) = sum(camconf,3);
stats.cacc(c) = sum(diag(camconf))/sum(camconf(:));
mstats.acc(s,c) = stats.cacc(c);
%% scene totals
resfn = sprintf('%s/%s/%s-sem',resDir,subName,scene);
stats.tconf = sum(stats.conf,3);
stats.tacc = sum(diag(stats.tconf))/sum(stats.tconf(:));
save([resfn '-stats.mat'],'-struct','stats');
plot(stats.acc','*'); ylabel 'accuracy'; grid on; xlabel('frame');
title(sprintf('%s[%s]: total pixelwise accuracy = %.3f',subName,sceneName,stats.tacc));
print([resfn '-acc.pdf'],'-dpdf','-bestfit');
confMatrixShow(stats.tconf, def.labelNames(2:end), {'FontSize',12}, 2, 1 );
colormap hot; ylabel('GT');
title(sprintf('%s[%s]: total pixelwise accuracy = %.3f',subName,sceneName,stats.tacc));
print([resfn '-conf.pdf'],'-dpdf','-bestfit');
%% main stats
mstats.conf(:,:,s) = stats.tconf;
mstats.cacc(c) = stats.tacc;
%% submission totals
resfn = sprintf('%s/%s/%s-sem-all',resDir,subName,resName); = subTitle;
mstats.tconf = sum(mstats.conf,3);
mstats.tacc = sum(diag(mstats.conf))/sum(mstats.conf(:));
save([resfn '-stats.mat'],'-struct','stats');
plot(mstats.acc','*'); ylabel 'accuracy'; grid on; xlabel('camera');
title(sprintf('%s[%s]: total pixelwise accuracy = %.3f',subTitle,resName,mstats.tacc));
print([resfn '-acc.pdf'],'-dpdf','-bestfit');
confMatrixShow(mstats.tconf, def.labelNames(2:end), {'FontSize',12}, 2, 1 );
colormap hot; ylabel('GT');
title(sprintf('%s[%s]: total pixelwise accuracy = %.3f',subTitle,resName,mstats.tacc));
print([resfn '-conf.pdf'],'-dpdf','-bestfit');
echo "*** Computing accuracy ***"
$CC -silent -auto_save OFF -C_EXPORT_FMT PLY \
-o $1 \
-crop -2:-2:-1:14:14:7 \
-SS SPATIAL 0.01 \
-o $GT \
-c2c_dist \
-pop_clouds \
-SF_COLOR_SCALE cmap.xml \
-SS SPATIAL 0.01 \
-save_clouds file "${1%.*}-acc.ply"
echo "*** Computing completeness ***"
$CC -silent -auto_save OFF -C_EXPORT_FMT PLY \
-o $GT \
-o $1 \
-crop -2:-2:-1:14:14:7 \
-c2c_dist \
-pop_clouds \
-SF_COLOR_SCALE cmap.xml \
-save_clouds file "${1%.*}-comp.ply"
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
Apache License
Version 2.0, January 2004
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,