RobotsIO
Loading...
Searching...
No Matches
FileToDepth.cpp
1/*
2 * Copyright (C) 2020 Istituto Italiano di Tecnologia (IIT)
3 *
4 * This software may be modified and distributed under the terms of the
5 * BSD 3-Clause license. See the accompanying LICENSE file for details.
6 */
7
8#include <RobotsIO/Utils/FileToDepth.h>
9
10#include <Eigen/Dense>
11
12#include <opencv2/opencv.hpp>
13#include <opencv2/core/eigen.hpp>
14
15using namespace Eigen;
16
17
18std::pair<bool, Eigen::MatrixXf> RobotsIO::Utils::file_to_depth(const std::string& file_name)
19{
20 const std::string log_name = "RobotsIO::Utils::file_to_depth";
21
22 /* Identify format */
23 auto dot_position = file_name.find_last_of('.');
24 if (dot_position == std::string::npos)
25 {
26 std::cout << log_name << "Error: invalid file extension in provided file name " + file_name << std::endl;
27 return std::make_pair(false, MatrixXf());
28 }
29 std::string format = file_name.substr(dot_position);
30
31 if (format == ".float")
32 {
33 std::FILE* in;
34
35 if ((in = std::fopen(file_name.c_str(), "rb")) == nullptr)
36 {
37 std::cout << log_name << "Error: cannot open file " + file_name << std::endl;
38 return std::make_pair(false, MatrixXf());
39 }
40
41 /* Load image size .*/
42 std::size_t dims[2];
43 if (std::fread(dims, sizeof(dims), 1, in) != 1)
44 {
45 std::cout << log_name << "Error: cannot load depth size for frame " + file_name << std::endl;
46
47 fclose(in);
48
49 return std::make_pair(false, MatrixXf());
50 }
51
52 /* Load image. */
53 float float_image_raw[dims[0] * dims[1]];
54 if (std::fread(float_image_raw, sizeof(float), dims[0] * dims[1], in) != dims[0] * dims[1])
55 {
56 std::cout << log_name << "Error: cannot load depth data for frame " + file_name << std::endl;
57
58 fclose(in);
59
60 return std::make_pair(false, MatrixXf());
61 }
62
63 /* Store image. */
64 MatrixXf float_image(dims[1], dims[0]);
65 float_image = Map<Matrix<float, -1, -1, RowMajor>>(float_image_raw, dims[1], dims[0]);
66
67 fclose(in);
68
69 return std::make_pair(true, float_image);
70 }
71 else if (format == ".png")
72 {
73 cv::Mat image = cv::imread(file_name, cv::IMREAD_UNCHANGED);
74
75 if (image.empty())
76 {
77 std::cout << log_name << "Error: cannot load depth data for frame " + file_name << std::endl;
78
79 return std::make_pair(false, MatrixXf());
80 }
81
82 MatrixXf float_image(image.rows, image.cols);
83 cv::cv2eigen(image, float_image);
84
85 /* FIXME: the depth_scale should be an input parameter. */
86 float depth_scale = 0.1 / 1000.0;
87 float_image *= depth_scale;
88
89 return std::make_pair(true, float_image);
90 }
91
92 std::cout << log_name << "Error: not supported file extension in provided file name " + file_name << std::endl;
93 return std::make_pair(false, MatrixXf());
94}