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
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
// VideoStitch Autocrop
// VideoStitch SDK
#include <libvideostitch/logging.hpp>
#include <libvideostitch/parse.hpp>
#include <libvideostitch/imageProcessingUtils.hpp>
#include <fstream>
#include <iostream>
#include <sstream>
#include <opencv2/imgproc.hpp>
// System-dependant filesystem stuff.
#ifdef _MSC_VER
#include <opencv2/imgcodecs.hpp>
#include <direct.h>
#define chdir _chdir
#define snprintf _snprintf
#define getcwd _getcwd
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
const char dirSep = '\\';
#else
#include <unistd.h>
const char dirSep = '/';
#endif
#ifdef _MSC_VER
#include <Windows.h>
#endif
#include <iostream>
#include <cassert>
#include <memory>
#ifndef _MSC_VER
#include <dirent.h>
#include <dlfcn.h>
#else
#include <libvideostitch/win32/dirent.h>
#endif
using namespace VideoStitch;
namespace {
/**
* @brief Prints the executable usage.
* @param execName Name of the executable (argv[0]).
* @param os Output stream: e.g; std::cerr to output in the standard error stream.
*/
void printUsage(const char* execName, ThreadSafeOstream& os) {
os << "Usage: " << execName << " -i <template> -o <output.json> [options]" << std::endl;
os << " -i <template.png>: can be an image file / or directory that contains all inputs for detection" << std::endl
#ifdef _MSC_VER
<< " Note that only PNG, JPEG, JPG files are supported." << std::endl
#else
<< " Note that only PNG file is supported." << std::endl
#endif
<< " This option can be used several times." << std::endl;
os << "<output.json> the output json file to be written." << std::endl;
os << "[options] are:" << std::endl;
os << " -d: Set this option to dump debug images." << std::endl;
os << std::endl;
}
/**
* @brief fileExists checks the existence of a file.
* @param filename The input full filename.
* @return true if the file exists, false otherwise.
*/
bool fileExists(const std::string& filename) {
std::ifstream file(filename.c_str());
if (file.good()) {
file.close();
return true;
} else {
file.close();
return false;
}
}
/**
* Give a pointer on the file component of a full input filename.
* @param input The input full filename.
* @return the filename, belonging to the same char* as @input.
*/
const char* extractFilename(const char* input) {
const char* file = input;
// separator is '\' or '/'
for (const char* p = input; *p != 0; ++p) {
if (*p == '/' || *p == '\\') {
file = p + 1;
}
}
return file;
}
/**
* List files with a certain extension in a directory.
* @param directory: directory to list.
* @param ext: the file prefix (may begin with '.').
* @return A list of matching files.
*/
std::vector<std::string> listDirectory(const std::string& directory, const std::string& ext) {
size_t extSize = ext.size();
std::vector<std::string> filenames;
DIR* dir = opendir(directory.c_str());
if (dir) {
/*print all the files and directories within directory*/
struct dirent* ent = readdir(dir);
while (ent) {
std::string str(ent->d_name);
ent = readdir(dir);
if (str.size() > extSize) {
std::string strLower = str;
std::transform(strLower.begin(), strLower.end(), strLower.begin(), ::tolower);
if (strLower.substr(strLower.size() - extSize) == ext) {
filenames.push_back(directory + dirSep + str);
continue;
}
}
}
closedir(dir);
}
return filenames;
}
Status readImage(const std::string& filename, int64_t& width, int64_t& height, std::vector<unsigned char>& data) {
int channelCount;
return VideoStitch::Util::ImageProcessing::readImage(filename, width, height, channelCount, data);
}
int extractArg(int argc, char** argv, std::vector<std::string>& inputFilenames, std::string& outputFilename,
bool& outputDebugImage, std::string& algoSettingFilename) {
// Check if the output folder/file is writable
const std::string program = std::string(argv[0]);
const size_t found = program.find_last_of("/\\");
std::string executableDirectory = program.substr(0, found);
auto& errLog = Logger::get(Logger::Error);
char currentDir[1024];
if (getcwd(currentDir, 1024)) {
executableDirectory = (executableDirectory.empty() || executableDirectory == std::string(argv[0]))
? std::string(currentDir)
: executableDirectory;
}
// Parse command line
std::vector<std::string> inputDirs;
outputDebugImage = false;
outputFilename = "";
for (int i = 1; i < argc; ++i) {
if (argv[i][0] != '\0' && argv[i][1] != '\0' && argv[i][0] == '-') {
switch (argv[i][1]) {
case 'i': /* input-directory or input-file*/
if (i >= argc - 1) {
errLog << "The -i option takes a parameter." << std::endl;
printUsage(argv[0], errLog);
return -1;
}
++i;
while (argv[i][0] != '-') {
inputDirs.push_back(argv[i]);
i++;
if (i == argc) {
break;
}
}
i--;
break;
case 'o': /* output-file name*/
outputFilename = argv[++i];
break;
case 'd': /* output debug images*/
outputDebugImage = true;
break;
case 's':
algoSettingFilename = argv[++i];
break;
default:
errLog << "No such option: " << argv[i] << std::endl << std::endl;
printUsage(argv[0], errLog);
return -1;
}
} else {
errLog << "No such option: " << argv[i] << std::endl;
printUsage(argv[0], errLog);
return -1;
}
}
#ifdef _MSC_VER
const std::vector<std::string> exts = {std::string("png"), std::string("jpeg"), std::string("jpg")};
#else
const std::vector<std::string> exts = {std::string("png")};
#endif
for (auto inputDir : inputDirs) {
if (fileExists(inputDir)) {
std::string strLower = inputDir;
std::transform(strLower.begin(), strLower.end(), strLower.begin(), ::tolower);
for (auto ext : exts) {
if ((strLower.substr(strLower.size() - ext.size()) == ext)) {
inputFilenames.push_back(inputDir);
break;
}
}
} else {
for (auto ext : exts) {
std::vector<std::string> newFilenames = listDirectory(inputDir, ext);
inputFilenames.insert(inputFilenames.end(), newFilenames.begin(), newFilenames.end());
}
}
}
if (!inputFilenames.size()) {
errLog << "Missing input file. Use -i for file or folder." << std::endl;
printUsage(argv[0], errLog);
return -1;
}
if (!outputFilename.size()) {
errLog << "Missing output file. Use -o to specify the output file." << std::endl;
printUsage(argv[0], errLog);
return -1;
}
return 0;
}
} // namespace
int main(int argc, char** argv) {
std::vector<std::string> inputFilenames;
std::string outputFilename;
bool outputDebugImage;
std::string algoSettingFilename;
auto& errorLog = Logger::get(Logger::Error);
// Extract command-line parameters
if (extractArg(argc, argv, inputFilenames, outputFilename, outputDebugImage, algoSettingFilename) < 0) {
return -1;
}
// Extract algorithm parameters
std::unique_ptr<Ptv::Value> algoConfig = nullptr;
if (algoSettingFilename.length() > 0) {
auto& errLog = Logger::get(Logger::Error);
Potential<Ptv::Parser> algoParser = Ptv::Parser::create();
if (!algoParser->parse(algoSettingFilename)) {
errLog << "Error: Cannot parse algos config PTV file: " << algoSettingFilename << std::endl;
errLog << algoParser->getErrorMessage() << std::endl;
return -1;
}
const Ptv::Value& algos = algoParser->getRoot();
if (!(algos.has("algorithms") && algos.has("algorithms")->getType() == Ptv::Value::LIST)) {
errLog << "Invalid algorithms file." << std::endl;
return -1;
}
const std::vector<Ptv::Value*>& algoDefs = algos.has("algorithms")->asList();
for (size_t i = 0; i < algoDefs.size(); ++i) {
const Ptv::Value* algoDef = algoDefs[i];
if (algoDef->has("name")->asString().compare("autocrop") == 0) {
algoConfig.reset(algoDef->has("config")->clone());
break;
}
}
} else {
algoConfig.reset(Ptv::Value::stringObject("fake"));
}
std::unique_ptr<Ptv::Value> jsonInputs(Ptv::Value::emptyObject());
jsonInputs->asList();
int success = 0;
int fail = 0;
for (auto filename : inputFilenames) {
bool getCircle = true;
// This likely is the visualization file --> skip it
if (filename.find("_circle.png") != std::string::npos) {
continue;
}
int64_t width, height;
std::vector<unsigned char> data;
readImage(filename, width, height, data);
int x, y, radius;
Status status = VideoStitch::Util::ImageProcessing::findCropCircle(
(int)width, (int)height, &data[0], x, y, radius, algoConfig.get(), outputDebugImage ? &filename : nullptr);
errorLog << "Input File '" << filename << "': ";
if (status.ok()) {
errorLog << "crop circle found!" << std::endl;
} else {
errorLog << "could not find crop circle!" << std::endl;
getCircle = false;
}
Ptv::Value* res = Ptv::Value::emptyObject();
res->push("reader_config", Ptv::Value::stringObject(filename));
res->push("width", Ptv::Value::intObject(width));
res->push("height", Ptv::Value::intObject(height));
res->push("proj", Ptv::Value::stringObject(std::string("circular_fisheye_opt")));
res->push("crop_left", Ptv::Value::intObject(x - radius));
res->push("crop_right", Ptv::Value::intObject(x + radius));
res->push("crop_top", Ptv::Value::intObject(y - radius));
res->push("crop_bottom", Ptv::Value::intObject(y + radius));
// Supplementary data
res->push("center_x", Ptv::Value::intObject(x));
res->push("center_y", Ptv::Value::intObject(y));
res->push("radius", Ptv::Value::intObject(radius));
if (outputDebugImage) {
std::string outputFilePath = filename + "_circle.png";
res->push("output_circle", Ptv::Value::stringObject(outputFilePath));
}
jsonInputs->asList().push_back(res);
std::ofstream ofs(outputFilename);
jsonInputs->printJson(ofs);
if (ofs.fail()) {
errorLog << "Could not write result to json file!" << std::endl;
getCircle = false;
}
ofs.close();
if (getCircle) {
success++;
} else {
fail++;
}
}
if (fail == 0) {
std::cout << "Output Json file was written to: " << outputFilename << std::endl;
} else if (success > 0) {
std::cout << "Only " << success << " over " << success + fail << " results were written to: " << outputFilename
<< std::endl;
} else {
std::cout << "Failed to write result to: " << outputFilename << std::endl;
}
if (fail == 0) {
return 0;
} else {
return -1;
}
}