-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind.cpp
More file actions
386 lines (330 loc) · 13.4 KB
/
find.cpp
File metadata and controls
386 lines (330 loc) · 13.4 KB
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
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cppoptlib/meta.h>
#include <cppoptlib/problem.h>
#include <cppoptlib/solver/bfgssolver.h>
#include <cppoptlib/solver/conjugatedgradientdescentsolver.h>
#include <cppoptlib/solver/newtondescentsolver.h>
#include <cppoptlib/solver/neldermeadsolver.h>
#include <cppoptlib/solver/lbfgssolver.h>
#include <cppoptlib/solver/cmaessolver.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <math.h>
#include <stdio.h>
#include <omp.h>
#include "find_args.h"
#include "cfa_mask.h"
#include "progressbar.h"
#include "termcolor.h"
using namespace std;
using namespace cv;
using namespace termcolor;
static bool verbose;
static bool exr_mode;
static int run = 0;
static int work_plane_color = UNKNOWN;
static Mat ref_plane, work_plane;
static Mat blank, mask;
static Mat dst, map_x, map_y;
static progressbar *pbar;
static int iteration = 0;
static bool first_iteration = true;
static bool trace_simplices = false;
static ofstream *trace_stream;
static double diff (double a, double b, double c, double d);
namespace cppoptlib {
// Define the target function (Lens::value())
template<typename T> class Lens : public Problem<T, 4> {
public:
using typename cppoptlib::Problem<T, 4>::Scalar;
using typename cppoptlib::Problem<T, 4>::TVector;
using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
// this is just the objective (NOT optional)
T value(const TVector &x) {
return diff(x[0], x[1], x[2], x[3]);
}
bool detailed_callback(const cppoptlib::Criteria<T> &state, SimplexOp op, int index, const MatrixType &x, vector<Scalar> f) {
iteration = (int)state.iterations;
TVector xp = x.col(index).transpose();
if (verbose) {
cerr << green << setw(12) << op << lightgrey <<
setw(10) << setprecision(6) << xp[0] <<
setw(10) << setprecision(6) << xp[1] <<
setw(10) << setprecision(6) << xp[2] <<
setw(10) << setprecision(6) << xp[3];
color_switch(cerr, work_plane_color);
cerr << bold << setw(9) << setprecision(2) << f[index] << reset << endl << endl;
}
else {
color_switch(cerr, work_plane_color);
progressbar_inc(pbar);
}
printf("%f\t%f\t%f\t%f\t%f\n", xp[0], xp[1], xp[2], xp[3], f[index]);
if (trace_simplices) {
TVector x0 = x.col(0).transpose();
TVector x1 = x.col(1).transpose();
TVector x2 = x.col(2).transpose();
TVector x3 = x.col(3).transpose();
TVector x4 = x.col(4).transpose();
*trace_stream << (first_iteration ? "" : ",\n") <<
" {\n"
" \"iter\": " << state.iterations << ",\n"
" \"op\": \"" << op << "\",\n"
" \"index\": " << index << ",\n"
" \"x\": [\n"
" [" << x0[0] << ", " << x0[1] << ", " << x0[2] << ", " << x0[3] << "],\n"
" [" << x1[0] << ", " << x1[1] << ", " << x1[2] << ", " << x1[3] << "],\n"
" [" << x2[0] << ", " << x2[1] << ", " << x2[2] << ", " << x2[3] << "],\n"
" [" << x3[0] << ", " << x3[1] << ", " << x3[2] << ", " << x3[3] << "],\n"
" [" << x4[0] << ", " << x4[1] << ", " << x4[2] << ", " << x4[3] << "]\n"
" ],\n"
" \"f\": [" << f[0] << ", " << f[1] << ", " << f[2] << ", " << f[3] << ", " << f[4] << "],\n"
" \"xDelta\": " << state.xDelta << ",\n"
" \"fDelta\": " << state.fDelta << "\n"
" }";
first_iteration = false;
}
return true;
}
};
template <typename ProblemType> class ModifiedNelderMeadSolver: public NelderMeadSolver<ProblemType> {
public:
using Superclass = ISolver<ProblemType, 0>;
using typename Superclass::Scalar;
using typename Superclass::TVector;
using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
MatrixType makeInitialSimplex (TVector &x) {
size_t dim = x.rows();
// create initial simplex
MatrixType s = MatrixType::Zero(dim, dim + 1);
for (int c = 0; c < (int)dim + 1; ++c) {
for (int r = 0; r < (int)dim; ++r) {
s(r, c) = x(r);
if (r == c - 1) {
s(r, c) = x(r) + 0.005;
}
}
}
NelderMeadSolver<ProblemType>::initialSimplexCreated = true;
return s;
}
};
}
double diff (double a, double b, double c, double d) {
// private thread variables
long i, j, pa, pb;
double x, y, r, rd;
unsigned width = work_plane.cols;
unsigned height = work_plane.rows;
clock_t start_time = clock(), end_time;
double elapsed;
// Fill the CFA area with white
if (verbose) cerr << right << setw(8) << iteration << setw(4) << run << reset << lightgrey << ": making mask ... " << reset;
blank.create(work_plane.size(), work_plane.type());
#pragma omp parallel shared(blank, exr_mode) private(i, j)
{
#pragma omp for
for (j = 0; j < width; j++ ) {
for (i = 0; i < height; i++ ) {
if (exr_mode) {
if ( // CFA interior
i + j >= width - 1 && // NW boundary
j > i - width - 1 && // NE boundary
i + j < width + 2 * height - 1 && // SE boundary
i > j - width // SW boundary
) {
blank.at<ushort>(i, j) = 65535;
}
else {
blank.at<ushort>(i, j) = 0;
}
}
else {
blank.at<ushort>(i, j) = 65535;
}
}
}
} /* end of parallel section */
/// Create dst, map_x and map_y with the same size as work_plane:
dst.create( work_plane.size(), work_plane.type() );
map_x.create( work_plane.size(), CV_32FC1 );
map_y.create( work_plane.size(), CV_32FC1 );
// Map computation in the following two sections consists of two
// slightly different variants for portrait and landscape orientation.
// In both cases, the shorter dimension is used for radius normalization.
run++;
if (verbose) cerr << lightgrey << "computing maps ... " << reset;
if (width >= height) { // landscape
#pragma omp parallel shared(map_x, map_y, a, b, c, d) private(i, j, x, y, r, rd)
{
#pragma omp for
for (j = 0; j < height; j++ ) {
// Normalize to half-height as in IM and PanoTools.
// The offset of 0.5 points at pixel center.
y = (double)(2 * (j + 0.5) - height) / height;
for (i = 0; i < width; i++ ) {
if (blank.at<ushort>(j, i) == 65535) { // don't move masked pixels (black outer triangles)
x = (double)(2 * (i + 0.5) - width) / height;
r = sqrt(x * x + y * y);
rd = a * r + b * pow(r, 2) + c * pow(r, 3) + d * pow(r, 4);
map_x.at<float>(j, i) = (height * x * rd / r + width) / 2;
map_y.at<float>(j, i) = (height * y * rd / r + height) / 2;
}
}
}
} /* end of parallel section */
}
if (width < height) { // portrait
#pragma omp parallel shared(width, height, map_x, map_y, a, b, c, d) private(i, j, x, y, r, rd)
{
#pragma omp for
for (j = 0; j < height; j++ ) {
// Normalize to half-width as in IM and PanoTools.
// The offset of 0.5 points at pixel center.
y = (double)(2 * (j + 0.5) - height) / width;
for (i = 0; i < width; i++ ) {
if (blank.at<ushort>(j, i) == 65535) { // don't move masked pixels (black outer triangles)
x = (double)(2 * (i + 0.5) - width) / width;
r = sqrt(x * x + y * y);
rd = a * r + b * pow(r, 2) + c * pow(r, 3) + d * pow(r, 4);
map_x.at<float>(j, i) = (width * x * rd / r + width) / 2;
map_y.at<float>(j, i) = (width * y * rd / r + height) / 2;
}
}
}
} /* end of parallel section */
}
if (verbose) cerr << lightgrey << "remapping ... " << reset;
remap( blank, mask, map_x, map_y, CV_INTER_LINEAR, BORDER_CONSTANT, Scalar(0,0, 0) );
remap( work_plane, dst, map_x, map_y, CV_INTER_LINEAR, BORDER_CONSTANT, Scalar(0,0, 0) );
/// Compute difference
if (verbose) cerr << lightgrey << "computing difference ... " << reset;
unsigned long num = 0;
unsigned long quot = 0;
#pragma omp parallel shared(dst, ref_plane) private(i, j, pa, pb) reduction(+:num,quot)
{
#pragma omp for collapse(2)
for ( j = 0; j < work_plane.rows; j++ ) {
for ( i = 0; i < work_plane.cols; i++ ) {
if (mask.at<ushort>(j, i) == 65535) { // select unmasked
pa = dst.at<ushort>(j, i);
pb = ref_plane.at<ushort>(j,i);
num += abs((double)pa - (double)pb);
quot += 1;
}
}
}
} /* end of parallel section */
double tca = 1.0 * num / quot;
if (verbose) {
end_time = clock();
elapsed = double(end_time - start_time) / CLOCKS_PER_SEC;
cerr << "\r" << string(100, ' ') << "\r" << flush; // blank line
cerr << lightgrey << right << setw(8) << iteration << setw(4) << run << reset <<
setw(10) << setprecision(6) << a <<
setw(10) << setprecision(6) << b <<
setw(10) << setprecision(6) << c <<
setw(10) << setprecision(6) << d;
color_switch(cerr, work_plane_color);
cerr << setw(9) << setprecision(2) << tca << reset <<
lightgrey << setw(7) << setprecision(2) << elapsed << "s" << reset << endl;
}
return tca;
}
// --------------------------------------------------------------------
void run_find (struct argp_state* state) {
PARSE_ARGS_FIND;
verbose = args.verbose;
exr_mode = args.exr;
typedef double T;
typedef cppoptlib::Lens<T> Lens;
// TVector lb(4); lb << 1 - 0.05, 0 - 0.05, 0 - 0.05, 0 - 0.05;
// TVector ub(4); lb << 1 + 0.05, 0 + 0.05, 0 + 0.05, 0 + 0.05;
// Load the images
cerr << lightgrey << "loading reference plane " << reset << args.ref_file << "\r" << flush;
ref_plane = imread( args.ref_file, CV_LOAD_IMAGE_ANYDEPTH ); // grayscale
cerr << "\r" << string(100, ' ') << "\r" << flush; // blank line
cerr << lightgrey << "reference plane: " << reset << lightgreen << args.ref_file << reset << endl;
cerr << lightgrey << "loading work plane " << reset << args.work_plane_file << "\r" << flush;
work_plane = imread( args.work_plane_file, CV_LOAD_IMAGE_ANYDEPTH );
cerr << "\r" << string(100, ' ') << "\r" << flush; // blank line
if (ref_plane.cols != work_plane.cols or ref_plane.rows != work_plane.rows) {
cerr << on_red << "Input images must have identical geometry. Got "
<< bold << ref_plane.rows << reset << on_red << "×" << bold << ref_plane.cols << reset
<< on_red << " and "
<< bold << work_plane.rows << reset << on_red << "×" << bold << work_plane.cols << reset
<< endl;
exit(EXIT_FAILURE);
}
string work_plane = args.work_plane_file;
if (work_plane.find("-0.") != string::npos) work_plane_color = RED;
if (work_plane.find("-1.") != string::npos) work_plane_color = GREEN;
if (work_plane.find("-2.") != string::npos) work_plane_color = BLUE;
if (work_plane.find("red.") != string::npos) work_plane_color = RED;
if (work_plane.find("green.") != string::npos) work_plane_color = GREEN;
if (work_plane.find("blue.") != string::npos) work_plane_color = BLUE;
cerr << lightgrey << "work plane: " << reset;
color_switch(cerr, work_plane_color);
cerr << work_plane << reset;
if (work_plane_color != RED and work_plane_color != GREEN and work_plane_color != BLUE) {
cerr << lightgrey << " (filename does not indicate which channel it is)";
}
cerr << endl;
cerr.setf(ios::fixed, ios::floatfield);
// initialize the optimization problem
Lens f;
// f.setLowerBound(lb);
// f.setUpperBound(ub);
// choose a starting point
//Eigen::VectorXd x(4); x << a, b, c, d;
Lens::TVector x(4); x << args.a, args.b, args.c, args.d;
// choose a solver
//cppoptlib::BfgsSolver<Lens> solver;
//cppoptlib::LbfgsSolver<Lens> solver;
//cppoptlib::ConjugatedGradientDescentSolver<Lens> solver;
//cppoptlib::NewtonDescentSolver<Lens> solver;
// cppoptlib::NelderMeadSolver<Lens> solver;
cppoptlib::ModifiedNelderMeadSolver<Lens> solver;
//cppoptlib::CMAesSolver<Lens> solver;
// Create a Criteria class to set the solver's stop conditions
Lens::TCriteria crit = Lens::TCriteria::defaults();
crit.iterations = 100;
crit.fDelta = 0.05;
solver.x0 = solver.makeInitialSimplex(x);
solver.setStopCriteria(crit);
if (not verbose) {
color_switch(cerr, work_plane_color);
pbar = progressbar_new("", crit.iterations + 1);
}
// Prepare output
if (args.trace) {
trace_simplices = args.trace;
trace_stream = &(args.trace_file);
*trace_stream <<
"{\n"
" \"simplex\": [\n";
}
// minimize the function
solver.minimize(f, x);
// Close output
if (trace_simplices) {
*trace_stream <<
"\n"
" ],\n"
" \"stop\": \"" << solver.stop_condition << "\"\n"
"}\n";
trace_stream->close();
}
if (not verbose) {
color_switch(cerr, work_plane_color);
progressbar_finish(pbar);
cerr << reset;
}
verbose = false;
cerr << yellow << setw(12) << "stop:" << " " << lightgrey << solver.stop_condition << reset << endl;
cerr << lightgrey << setw(12) << "solution:" << " " << reset << setprecision(6) << x.transpose() << endl;
color_switch(cerr, work_plane_color);
cerr << setw(12) << "TCA:" << " " << setprecision(2) << f(x) << reset << endl;
}