-
Notifications
You must be signed in to change notification settings - Fork 0
/
KinectHandler.cpp
400 lines (326 loc) · 11.3 KB
/
KinectHandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#include "KinectHandler.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <map>
#include <stdio.h>
#include <QDir>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
using namespace std;
#define cvWindowTitleRgb "RGB"
#define cvWindowTitleDepth "Depth"
/**
* @brief Start capturing image and depth frames from the Kinect device.
*/
void KinectHandler::startCapturing() {
_isRunning = true;
const string separator = "/";
string resDir{""};
string rgbDir{""};
string depthDir{""};
int64_t rgbTimestamp{0};
int64_t depthTimestamp{0};
cv::Mat depthMat(cv::Size(640,480), CV_16UC1);
cv::Mat rgbMat(cv::Size(640,480), CV_8UC3, cv::Scalar(0));
Freenect::Freenect freenect;
short depthMode = 4;
if(_device) {
_device->stopVideo();
_device->stopDepth();
}
_device = &freenect.createDevice<KinectDevice>(0);
setDepthMode(depthMode);
_device->startVideo();
_device->startDepth();
bool save = false;
bool resultDirectoriesCreated = false;
cv::namedWindow(cvWindowTitleRgb, CV_WINDOW_AUTOSIZE);
cv::namedWindow(cvWindowTitleDepth, CV_WINDOW_AUTOSIZE);
while(_isRunning) {
_device->getVideo(rgbMat, rgbTimestamp);
_device->getDepth(depthMat, depthTimestamp);
displayResults(rgbMat, depthMat);
char k = cvWaitKey(5);
// see http://www.asciitable.com key codes
if( k == 27 ){
// ESC
cout << "quit application" << endl;
break;
}
if(k == 97) {
// a
_enableAutoExposure = !_enableAutoExposure;
_device->setFlag(FREENECT_AUTO_EXPOSURE, _enableAutoExposure);
cout << "FREENECT_AUTO_EXPOSURE: " << (_enableAutoExposure ? "on" : "off") << endl;
}
if(k == 119) {
// w
_enableWhiteBalance = !_enableWhiteBalance;
_device->setFlag(FREENECT_AUTO_WHITE_BALANCE, _enableWhiteBalance);
cout << "FREENECT_AUTO_WHITE_BALANCE: " << (_enableWhiteBalance ? "on" : "off") << endl;
}
if(k == 114) {
// r
_enableRawColor = !_enableRawColor;
_device->setFlag(FREENECT_RAW_COLOR, _enableRawColor);
cout << "FREENECT_RAW_COLOR: " << (_enableRawColor ? "on" : "off") << endl;
}
if(k == 115) {
// s
save = !save;
if(save) {
resultDirectoriesCreated = false;
}
if(rgbDir.size() > 0 && depthDir.size() > 0 && resDir.size() > 0){
associateFiles(rgbDir, depthDir, resDir);
}
cout << (save ? "start saving stream" : "stop saving stream") << endl;
}
if(k == 100) {
// d
depthMode++;
if(depthMode % 6 == 0) {
depthMode = 0;
}
setDepthMode(depthMode);
}
if(k == 32 || save) {
// space
if(!resultDirectoriesCreated) {
string subOutputDir = getCurrentDateTime();
resDir = _outputDir + "results" + separator + subOutputDir + separator;
rgbDir = resDir + "rgb" + separator;
depthDir = resDir + "depth" + separator;
createDirectory(rgbDir);
createDirectory(depthDir);
resultDirectoriesCreated = true;
}
cout << "saving rgb: " << _prefix << rgbTimestamp << _suffix << "." << _extension;
cout << " depth: " << _prefix << depthTimestamp << _suffix << "." << _extension << endl;
ostringstream rgbFile;
ostringstream depthFile;
rgbFile << rgbDir << _prefix << rgbTimestamp << _suffix << "." << _extension;
depthFile << depthDir << _prefix << depthTimestamp << _suffix << "." << _extension;
cv::imwrite(rgbFile.str(), rgbMat);
cv::imwrite(depthFile.str(), depthMat);
}
}
stopCapturing();
}
/**
* @brief Stop capturing frames from the connected Kinect device.
*/
void KinectHandler::stopCapturing() {
if(_isRunning) {
cvDestroyWindow(cvWindowTitleRgb);
cvDestroyWindow(cvWindowTitleDepth);
}
if(_device) {
_device->stopVideo();
_device->stopDepth();
}
}
/**
* @brief Set the result output main directory.
* @param outputDir Output directory.
*/
void KinectHandler::setOutputDir(const string &outputDir) {
if(outputDir.size() == 0) {
throw runtime_error("Output directory is empty.");
}
if(_outputDir.compare(outputDir) == 0) {
return;
}
_outputDir = outputDir;
const string separator = "/";
if(_outputDir.rfind(separator) != _outputDir.size()) {
_outputDir += separator;
}
}
/**
* @brief Associate RGB with depth image files. Takes in account that the closest
* time difference between the files is used.
* @param rgbDir Output directory that contains RGB data.
* @param depthDir Output directory that contains depth data.
* @param resultDir Base result directory to store the file associations.
* @param maxDifferenceMs Maximum difference between timestamps, otherwise skip.
*/
void KinectHandler::associateFiles(const string &rgbDir, const string &depthDir, const string &resultDir, const bool &cleanUp, const int &maxDifferenceMs)
{
string resDir = resultDir;
if(!checkDir(resDir)) {
throw runtime_error("Result direcory error: " + resultDir);
}
vector<string> rgbFiles = getFiles(rgbDir, "*." + _extension);
vector<string> depthFiles = getFiles(depthDir, "*." + _extension);
map<int, string> usedDepthFiles;
ofstream resFile;
resFile.open(resDir + _outputFile);
resFile << "# Associated RGB and depth files with max difference of " << maxDifferenceMs << "ms\n";
resFile << "# rgbFileName depthFileName\n";
for(int i = 0; i < rgbFiles.size(); i++) {
int64_t rgbTimestamp = stol(extractFileName(rgbFiles[i]).c_str(), nullptr);
int64_t minDiff = numeric_limits<int64_t>::max();
int foundCandidateIndex = -1;
for(int j = 0, jLength = depthFiles.size(); j < jLength; j++) {
int64_t depthTimestamp = stol(extractFileName(depthFiles[j]).c_str(), nullptr);
int64_t diff = abs(depthTimestamp - rgbTimestamp);
if(diff <= maxDifferenceMs) {
if(diff < minDiff) {
minDiff = diff;
foundCandidateIndex = j;
}
}
}
if(foundCandidateIndex != -1) {
resFile << rgbFiles[i] << " " << depthFiles[foundCandidateIndex] << "\n";
usedDepthFiles[foundCandidateIndex] = depthFiles[foundCandidateIndex];
}
}
resFile.close();
if(cleanUp) {
cout << "Cleaning up." << endl;
for(int i = 0, iLength = depthFiles.size(); i < iLength; i++) {
if(usedDepthFiles.find(i) == usedDepthFiles.end()) {
if(remove((depthDir + "/" + depthFiles[i]).c_str()) == 0) {
cout << depthFiles[i] << endl;
}
}
}
}
}
/**
* @brief Display results in an OpenCV output window.
* @param rgb Captured RGB image.
* @param depth Captured depth image.
*/
void KinectHandler::displayResults(const cv::Mat &rgb, const cv::Mat &depth) noexcept
{
cv::Mat depthf(cv::Size(640,480), CV_8UC1);
depth.convertTo(depthf, CV_8UC1, 255.0/2048.0);
cv::applyColorMap(depthf, depthf, cv::COLORMAP_JET);
cv::imshow(cvWindowTitleRgb, rgb);
cv::imshow(cvWindowTitleDepth, depthf);
}
/**
* @brief Create directory.
* @param dirPath Directory path that should be created.
*/
void KinectHandler::createDirectory(const string &dirPath)
{
if(dirPath.size() == 0) {
throw runtime_error("Directory path is empty.");
}
const QDir dir(QString::fromStdString(dirPath));
if(dir.exists()) {
return;
}
QDir::root().mkpath(dir.absolutePath());
}
/**
* @brief Checks directory path and corrects it if necessary.
* @param dir Director path to check.
* @return True/false if directory check is successful.
*/
bool KinectHandler::checkDir(string &dir) noexcept
{
if(dir.size() == 0) {
return false;
}
if(dir.rfind("/") != dir.size()) {
dir += "/";
}
return true;
}
/**
* @brief Extract the filename from the file.
* @param file File path.
* @return Base filename, e.g. 'file.tar.gz' will be 'file'.
*/
string KinectHandler::extractFileName(const string &file)
{
if(file.size() == 0) {
throw runtime_error("Filename is empty.");
}
QFileInfo fileInfo(QString::fromStdString(file));
string basename = fileInfo.baseName().toStdString();
return basename;
}
/**
* @brief KinectHandler::getFiles
* @param dir Directory that should be listed.
* @param filter File filter, e.g. "*.png"
*/
vector<string> KinectHandler::getFiles(const string &dir, const string &filter) noexcept
{
const QStringList nameFilter(QString::fromStdString(filter));
const QDir directory(QString::fromStdString(dir));
const QStringList files = directory.entryList(nameFilter);
vector<string> res;
for(int i = 0, iLength = files.size(); i < iLength; i++) {
res.push_back(files[i].toStdString());
}
sort(res.begin(), res.end());
return res;
}
/**
* @brief Set depth mode:
* @param depthMode
* FREENECT_DEPTH_11BIT = 0, 11 bit depth information in one uint16_t/pixel
* FREENECT_DEPTH_10BIT = 1, 10 bit depth information in one uint16_t/pixel
* FREENECT_DEPTH_11BIT_PACKED = 2, 11 bit packed depth information
* FREENECT_DEPTH_10BIT_PACKED = 3, 10 bit packed depth information
* FREENECT_DEPTH_REGISTERED = 4, processed depth data in mm, aligned to 640x480 RGB
* FREENECT_DEPTH_MM = 5, depth to each pixel in mm, but left unaligned to RGB image
*/
void KinectHandler::setDepthMode(const short &depthMode)
{
if(depthMode < 0 || depthMode > 5) {
return;
}
if(!_device) {
return;
}
switch(depthMode) {
case 0:
_device->setDepthFormat(FREENECT_DEPTH_11BIT);
cout << "depth format: FREENECT_DEPTH_11BIT" << endl;
break;
case 1:
_device->setDepthFormat(FREENECT_DEPTH_10BIT);
cout << "depth format: FREENECT_DEPTH_10BIT" << endl;
break;
case 2:
_device->setDepthFormat(FREENECT_DEPTH_11BIT_PACKED);
cout << "depth format: FREENECT_DEPTH_11BIT_PACKED" << endl;
break;
case 3:
_device->setDepthFormat(FREENECT_DEPTH_10BIT_PACKED);
cout << "depth format: FREENECT_DEPTH_10BIT_PACKED" << endl;
break;
case 4:
_device->setDepthFormat(FREENECT_DEPTH_REGISTERED);
cout << "depth format: FREENECT_DEPTH_REGISTERED" << endl;
break;
case 5:
_device->setDepthFormat(FREENECT_DEPTH_MM);
cout << "depth format: FREENECT_DEPTH_MM" << endl;
break;
}
}
/**
* @brief KinectHandler::getDate
* @return Curent date time, e.g. 2019-06-26_16:03:02
*/
string KinectHandler::getCurrentDateTime() noexcept
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d_%H-%M-%S");
return oss.str();
}