filename = 'depth_map.mat'; % file containing the depth data
imagename = 'depth_map.png'; % file where the image will be saved

% load the depth map from file
load(filename);

% The depth map is now stored in the matrix depth_map.
% depth_map contains the depth of the points corresponding to the
% matrix elements.
% If an element of depth_map do not contains any point, such
% element will have a NaN value.

% Compute the extrems of the represented values.
m1 = min(min(depth_map)); % min(depth_map(:)) can also be used 
m2 = max(max(depth_map)); % max(depth_map(:)) can also be used

% The depth map will be transformed in an image where::
% - if an element is NaN, the corresponding pixel will be 0;
% - the minimum depth value will be mapped to 1;
% - the maximum depth value will be mapped to 255;
% - the intermediate depth values will be linearly mapped between 1 and 255.
%               /
%               | 0,                         Nan
%   s = T(r) = <
%               | 1+254*(r-min)/(max-min),   min <= r <= max 
%               \

% allocate the matrix that will represent the image
dm = zeros(size(depth_map));

% find the elements eqaul to NaN and map them to 0
ind = find(isnan(depth_map));
dm(ind)=0;

% the other values are linearly mapped in [1, 255]
ind = find(not(isnan(depth_map)));
dm(ind)=1+(depth_map(ind)-m1)/(m2-m1)*254;

% scale the values between 0 and 1 (dm is a matrix of double);
% alternatively, the matrix can be converted in uint8 (dm = uint8(dm))
dm = dm/255;

% display the image
imshow(dm);
colorbar;

% save the image on a file
imwrite(dm, imagename);
