Repository navigation
Expand file tree
/
Copy pathkernel.cc
More file actions
314 lines (305 loc) · 11.7 KB
/
Copy pathkernel.cc
File metadata and controls
314 lines (305 loc) · 11.7 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
#include <chrono>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "ipl/filters.h"
#include "ipl/fixed.h"
#include "ipl/fixed_study.h"
#include "ipl/isp.h"
#include "ipl/streaming.h"
namespace {
using ipl::Border;
using ipl::Image;
using Clock = std::chrono::steady_clock;
int Integer(const std::string& text) {
std::size_t used = 0;
const int value = std::stoi(text, &used);
if (used != text.size()) throw std::invalid_argument("Invalid integer");
return value;
}
double Real(const std::string& text) {
std::size_t used = 0;
const double value = std::stod(text, &used);
if (used != text.size() || !std::isfinite(value)) {
throw std::invalid_argument("Invalid real");
}
return value;
}
Border ParseBorder(const std::string& text) {
if (text == "zero") return Border::kZero;
if (text == "replicate") return Border::kReplicate;
if (text == "reflect") return Border::kReflect;
throw std::invalid_argument("Unknown border");
}
int Run(const std::vector<std::string>& args) {
if (args == std::vector<std::string>{"info"}) {
std::cout << IPL_COMPILER << '\n' << IPL_FLAGS << '\n' << IPL_BUILD << '\n';
return 0;
}
if (args.size() < 7) {
throw std::invalid_argument(
"Usage: ipl_kernel OP ROWS COLS CHANNELS BORDER REPS WARMUPS "
"[PARAMETERS]");
}
const auto& op = args[0];
auto arg = [&](std::size_t i) -> const std::string& {
return args.at(i + 7);
};
const auto border = ParseBorder(args[4]);
const int repetitions = Integer(args[5]);
const int warmups = Integer(args[6]);
if (repetitions < 1 || repetitions > 1000 || warmups < 0 || warmups > 100) {
throw std::invalid_argument("Invalid timing counts");
}
const bool demosaic = op == "bilinear" || op == "nearest";
const bool mosaic = op == "mosaic";
Image input(Integer(args[1]), Integer(args[2]), Integer(args[3]));
Image output(input.rows, input.cols,
demosaic ? 3
: mosaic ? 1
: input.channels);
const auto bytes =
static_cast<std::streamsize>(input.pixels.size() * sizeof(double));
if (!std::cin.read(reinterpret_cast<char*>(input.pixels.data()), bytes) ||
std::cin.peek() != EOF ||
!std::all_of(input.pixels.begin(), input.pixels.end(),
[](double x) { return std::isfinite(x); })) {
throw std::invalid_argument("Invalid image buffer");
}
const bool study = op == "study";
std::unique_ptr<ipl::FixedStudy> fixed_study;
ipl::StudyStats study_stats;
auto variant = ipl::StudyVariant::kGolden;
const bool fixed = op == "fixed" || op == "fixed-gaussian";
const bool gaussian = op == "gaussian" || op == "separable" ||
op == "fixed-gaussian" || op == "unsharp";
const bool edge = op == "sobel-x" || op == "sobel-y" || op == "gradient" ||
op == "laplacian" || op == "lap-sharp";
const bool gamma = op == "gamma" || op == "gamma-lut";
int kr = 1;
int kc = 1;
double strength = 0;
double exponent = 1;
double black = 0;
double white = 1;
std::vector<double> weights, vertical, scratch, lut, matrix;
const std::vector<double> sx = {-1, 0, 1, -2, 0, 2, -1, 0, 1};
const std::vector<double> sy = {-1, -2, -1, 0, 0, 0, 1, 2, 1};
std::unique_ptr<Image> temp;
if (study) {
kr = Integer(arg(0));
kc = Integer(arg(1));
if ((arg(7) != "nearest" && arg(7) != "truncate") ||
(arg(8) != "tap" && arg(8) != "end")) {
throw std::invalid_argument("Unknown arithmetic policy");
}
if (arg(9) == "interior")
variant = ipl::StudyVariant::kInterior;
else if (arg(9) == "proof")
variant = ipl::StudyVariant::kProof;
else if (arg(9) == "silent")
variant = ipl::StudyVariant::kSilent;
else if (arg(9) != "golden")
throw std::invalid_argument("Unknown study variant");
for (std::size_t i = 17; i < args.size(); ++i)
weights.push_back(Real(args[i]));
fixed_study = std::make_unique<ipl::FixedStudy>(
input, weights, kr, kc,
ipl::StudyFormat{Integer(arg(2)), Integer(arg(3)), Integer(arg(4)),
Integer(arg(5)), Integer(arg(6)), arg(7) == "truncate",
arg(8) == "end"});
} else if (op == "correlate" || op == "fixed" || op == "stream") {
kr = Integer(arg(0));
kc = Integer(arg(1));
const std::size_t start = fixed ? 12 : 9;
for (std::size_t i = start; i < args.size(); ++i)
weights.push_back(Real(args[i]));
ipl::ValidateKernel(kr, kc, weights.size());
} else if (gaussian) {
kr = kc = Integer(arg(0));
vertical = ipl::Gaussian(kr, Real(arg(1)));
weights = ipl::Outer(vertical);
if (op == "unsharp") strength = Real(arg(2));
} else if (op == "box" || op == "median") {
kr = kc = Integer(arg(0));
const auto count = static_cast<std::size_t>(kr) * kr;
ipl::ValidateKernel(kr, kc, count);
if (op == "box")
weights.assign(count, 1.0 / count);
else
scratch.resize(count);
} else if (edge) {
kr = kc = 3;
weights = op == "sobel-x" || op == "gradient" ? sx
: op == "sobel-y"
? sy
: std::vector<double>{0, 1, 0, 1, -4, 1, 0, 1, 0};
if (op == "lap-sharp") strength = Real(arg(0));
} else if (gamma) {
exponent = Real(arg(0));
if (exponent <= 0)
throw std::invalid_argument("Gamma exponent must be positive");
if (op == "gamma-lut") {
const int levels = Integer(arg(1));
if (levels < 2 || levels > 65536)
throw std::invalid_argument("Invalid LUT size");
for (int i = 0; i < levels; ++i)
lut.push_back(std::pow(double(i) / (levels - 1), exponent));
}
} else if (op == "black") {
black = Real(arg(0));
white = Real(arg(1));
if (input.channels != 1 || black < 0 || white <= black) {
throw std::invalid_argument("Invalid black or white code");
}
} else if (demosaic || mosaic) {
ipl::ValidatePattern(arg(0));
if (mosaic && input.channels != 3)
throw std::invalid_argument("Mosaic requires RGB");
} else if (op == "matrix") {
for (std::size_t i = 7; i < args.size(); ++i)
matrix.push_back(Real(args[i]));
} else if (op != "gray-world" && op != "white-patch") {
throw std::invalid_argument("Unknown operation");
}
if (op == "gradient" || op == "separable") {
temp = std::make_unique<Image>(input.rows, input.cols, input.channels);
}
std::vector<int> codes;
std::vector<std::int64_t> coefficients;
ipl::FixedStats stats;
std::size_t coefficient_saturation = 0;
int fraction = 0;
int accumulator = 0;
if (fixed) {
fraction = Integer(arg(3));
accumulator = Integer(arg(4));
coefficient_saturation = ipl::PrepareFixed(input, weights, Integer(arg(2)),
fraction, codes, coefficients);
}
std::array<double, 3> gains{1, 1, 1};
auto process = [&] {
if (study) {
study_stats = fixed_study->Run(input, output, border, variant);
} else if (fixed) {
ipl::FixedCorrelate(input, output, codes, coefficients, kr, kc, fraction,
accumulator, border, stats);
} else if (op == "separable") {
ipl::Correlate(input, *temp, vertical, 1, kc, border);
ipl::Correlate(*temp, output, vertical, kr, 1, border);
} else if (op == "stream") {
if (input.channels != 1)
throw std::invalid_argument("Stream requires grayscale");
std::size_t source = 0, target = 0;
ipl::StreamCorrelate(
input.rows, input.cols, weights, kr, kc, border,
[&] { return input.pixels.at(source++); },
[&](double value) { output.pixels.at(target++) = value; });
} else if (!weights.empty()) {
ipl::Correlate(input, output, weights, kr, kc, border);
if (op == "gradient") {
ipl::Correlate(input, *temp, sy, 3, 3, border);
for (std::size_t i = 0; i < output.pixels.size(); ++i) {
output.pixels[i] = std::hypot(output.pixels[i], temp->pixels[i]);
}
}
if (op == "unsharp" || op == "lap-sharp") {
for (std::size_t i = 0; i < output.pixels.size(); ++i) {
const double detail = op == "unsharp"
? input.pixels[i] - output.pixels[i]
: -output.pixels[i];
output.pixels[i] = input.pixels[i] + strength * detail;
}
}
} else if (op == "median") {
ipl::Median(input, output, kr, border, scratch);
} else if (demosaic) {
ipl::Demosaic(input, output, arg(0), op == "nearest");
} else if (mosaic) {
for (int y = 0; y < input.rows; ++y) {
for (int x = 0; x < input.cols; ++x) {
output.At(y, x) = input.At(y, x, ipl::BayerChannel(arg(0), y, x));
}
}
} else if (op == "gray-world" || op == "white-patch") {
gains = ipl::WhiteBalance(input, output, op == "white-patch");
} else if (op == "matrix") {
ipl::ColorMatrix(input, output, matrix);
} else {
for (std::size_t i = 0; i < input.pixels.size(); ++i) {
const double value = input.pixels[i];
if (op == "black")
output.pixels[i] = ipl::Unit((value - black) / (white - black));
else if (lut.empty())
output.pixels[i] = std::pow(ipl::Unit(value), exponent);
else
output.pixels[i] =
lut[std::lround(ipl::Unit(value) * (lut.size() - 1))];
}
}
};
std::vector<double> samples(repetitions);
for (int i = -warmups; i < repetitions; ++i) {
const auto start = Clock::now();
process();
const auto stop = Clock::now();
if (i >= 0)
samples[i] =
std::chrono::duration<double, std::milli>(stop - start).count();
}
for (double value : output.pixels) {
if (!std::isfinite(value))
throw std::overflow_error("Nonfinite kernel output");
}
std::cerr << std::setprecision(17) << "{\"ms\":[";
for (int i = 0; i < repetitions; ++i) {
if (i) std::cerr << ',';
std::cerr << samples[i];
}
if (study) {
const auto [plo, phi] = fixed_study->product_range();
const auto [alo, ahi] = fixed_study->prefix_range();
std::cerr << "],\"study\":{\"taps\":" << study_stats.taps
<< ",\"products\":" << study_stats.products
<< ",\"accumulators\":" << study_stats.accumulators
<< ",\"outputs\":" << study_stats.outputs
<< ",\"affected\":" << study_stats.affected
<< ",\"product_min\":" << study_stats.product_min
<< ",\"product_max\":" << study_stats.product_max
<< ",\"prefix_min\":" << study_stats.prefix_min
<< ",\"prefix_max\":" << study_stats.prefix_max
<< ",\"product_range\":[" << plo << ',' << phi
<< "],\"prefix_range\":[" << alo << ',' << ahi << "]}}\n";
std::cout.write(reinterpret_cast<const char*>(output.pixels.data()),
output.pixels.size() * sizeof(double));
return std::cout ? 0 : 1;
}
std::cerr << "],\"overflow\":" << stats.overflow
<< ",\"saturation\":" << stats.saturation
<< ",\"coefficient_saturation\":" << coefficient_saturation
<< ",\"gains\":[" << gains[0] << ',' << gains[1] << ',' << gains[2]
<< "]}\n";
std::cout.write(reinterpret_cast<const char*>(output.pixels.data()),
output.pixels.size() * sizeof(double));
return std::cout ? 0 : 1;
}
} // namespace
int main(int argc, char** argv) {
#ifdef _WIN32
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
try {
return Run(std::vector<std::string>(argv + 1, argv + argc));
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 2;
}
}