Repository navigation
Expand file tree
/
Copy pathstreaming.cc
More file actions
62 lines (61 loc) · 2.22 KB
/
Copy pathstreaming.cc
File metadata and controls
62 lines (61 loc) · 2.22 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
#include "ipl/streaming.h"
namespace ipl {
void StreamCorrelate(int rows, int cols, const std::vector<double>& kernel,
int kh, int kw, Border border,
const std::function<double()>& read,
const std::function<void(double)>& write) {
ValidateKernel(kh, kw, kernel.size());
if (rows < 1 || cols < 1 || rows > 16384 || cols > 16384 || !read || !write) {
throw std::invalid_argument("Invalid streaming geometry or callbacks");
}
const int line_count = std::min(kh, rows);
std::vector<double> lines(static_cast<std::size_t>(line_count) * cols);
std::vector<double> window(kernel.size());
std::vector<int> source_rows(kh);
std::vector<bool> valid_columns(kw);
int loaded = -1;
for (int y = 0; y < rows; ++y) {
int required = -1;
for (int ky = 0; ky < kh; ++ky) {
source_rows[ky] = BorderIndex(y + ky - kh / 2, rows, border);
required = std::max(required, source_rows[ky]);
}
// Pull just enough complete rows, then emit the next output row.
while (loaded < required) {
++loaded;
double* line = lines.data() + (loaded % line_count) * cols;
for (int x = 0; x < cols; ++x) line[x] = read();
}
auto load_column = [&](int slot, int column) {
const int sx = BorderIndex(column, cols, border);
valid_columns[slot] = sx >= 0;
if (sx < 0) return;
for (int ky = 0; ky < kh; ++ky) {
const int sy = source_rows[ky];
if (sy >= 0)
window[ky * kw + slot] = lines[(sy % line_count) * cols + sx];
}
};
for (int kx = 0; kx < kw; ++kx) load_column(kx, kx - kw / 2);
int head = 0;
for (int x = 0; x < cols; ++x) {
double sum = 0;
for (int ky = 0; ky < kh; ++ky) {
if (source_rows[ky] < 0) continue;
for (int kx = 0, slot = head; kx < kw; ++kx) {
if (valid_columns[slot]) {
sum += window[ky * kw + slot] * kernel[ky * kw + kx];
}
if (++slot == kw) slot = 0;
}
}
write(sum);
// The last rows and columns flush using the same border mapper.
if (x + 1 < cols) {
load_column(head, x + 1 + kw / 2);
if (++head == kw) head = 0;
}
}
}
}
} // namespace ipl