function [data, map_info] = load_feature_map(parent_dirs, name_root, ...
                                 layer_params, load_params)

% Create path to the file.
if strcmp(layer_params.subdir, '*RAW_DATA*')
    path = fullfile(parent_dirs{:});
else
    path = layer_params.full_dir;
end
if strcmp(layer_params.type, 'feature_map')
    layer_params.format = '%s.mat';
end
path = fullfile(path, sprintf(layer_params.format, name_root));

% Load the data.
switch layer_params.type
  case 'feature_map'
    load(path, 'feature_map', 'map_info');
    data = full(feature_map)';
    data = reshape(data, map_info.height, map_info.width, size(data,2));
  case 'depth_raw'
    data = load_raw_depth(path, load_params);
  case 'rgb_raw'
    load_params.color_space = 'rgb';
    data = load_raw_image(path, load_params);
    if size(data, 3) == 1
        data = repmat(data, [1 1 3]);
    end
  case 'gray_raw'
    load_params.color_space = 'rgb';
    data = load_raw_image(path, load_params);
    if size(data, 3) == 3
        data = rgb2gray(data);
    end
  case 'lab_raw'
    data = load_lab_raw(path, load_params);
  case 'lab_l_raw'
    data = load_lab_raw(path, load_params);
    data = data(:,:,1);
  case 'lab_ab_raw'
    data = load_lab_raw(path, load_params);
    data = data(:,:,2:3);
  case 'depth'
    load(path, 'depth');
    data = depth;
  case 'normals'
    load(path, 'normals');
    data = normals;
  case 'curvature'
    load(path, 'curvature');
    data = curvature;
  case 'shape_index'
    load(path, 'curvature');
    data = cat(3, 2 / pi * ...
               atan(sum(curvature, 3)./...
                    (-sign(curvature(:,:,1)).*diff(curvature, 1, 3))), ...
               sqrt(mean(curvature.^2, 3)));
  otherwise
    error('unknown data type');
end

if ~strcmp(layer_params.type, 'feature_map')
    if isfield(load_params, 'use_gt_box') && load_params.use_gt_box
        % Crop around the ground truth foreground.
        gt_label = load_ground_truth(parent_dirs, name_root, load_params);
        gt_crop = get_gt_box(gt_label, load_params);
        data = data(gt_crop(1):gt_crop(2), gt_crop(3):gt_crop(4), :);
        map_info.crop = gt_crop;
    end

    map_info.height = size(data, 1);
    map_info.width = size(data, 2);
    map_info.cover = 1;
    map_info.center = 1;
    map_info.scale = 1;
end
data(isnan(data)) = 0;

% Pad if necessary.
patch_sz = layer_params.patch_sz;
if size(data, 1) < patch_sz
    data = padarray(data, [(patch_sz - size(data, 1)) 0 0], 0, 'post');
    map_info.height = patch_sz;
end

if size(data, 2) < patch_sz
    data = padarray(data, [0 (patch_sz - size(data, 2)) 0], 0, 'post');
    map_info.width = patch_sz;
end

end

function data = load_lab_raw(path, load_params)
load_params.color_space = 'lab';
data = load_raw_image(path, load_params);
data = bsxfun(@plus, lab, permute([0 128 128], [1 3 2]));
data = bsxfun(@rdivide, data, permute([100 256 256], [1 3 2]));
end
