-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmatrix_c.cc
104 lines (83 loc) · 2.55 KB
/
matrix_c.cc
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
#include "matrix_c.h"
namespace Renzoku {
template <>
void MatrixC<Rgb>::save(const char *file) const {
FILE *f = fopen(file, "wb");
if (f == NULL)
throw FileException("Cannot open file.");
fprintf(f, "%d %d\n", rows, cols);
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
Float v[3] = { data[j * rows + i].red(),
data[j * rows + i].green(),
data[j * rows + i].blue() };
fwrite(v, sizeof(Float), 3, f);
}
}
fclose(f);
}
template <>
void MatrixC<Rgb>::load(const char *file) {
FILE *f = fopen(file, "rb");
if (f == NULL)
throw FileException("Cannot open file.");
fscanf(f, "%d %d\n", &rows, &cols);
max_rows = rows;
max_cols = cols;
data = new Rgb[rows * cols];
if (!data) error_alloc(__FILE__, __LINE__);
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
Float v[3];
fread(data, sizeof(Float), 3, f);
data[j * rows + i] = Rgb(v[0], v[1], v[2]);
}
}
fclose(f);
}
template <>
void MatrixC<Rgb>::flatten_magnitude(MatrixC<Float> &d) {
d.resize(rows, cols);
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
d(i, j) = sqrt((*this)(i, j).r * (*this)(i, j).r +
(*this)(i, j).g * (*this)(i, j).g +
(*this)(i, j).b * (*this)(i, j).b);
}
}
}
template <>
void MatrixC<Rgb>::flatten(MatrixC<Float> &d) const {
d.resize(3 * rows, cols);
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
d(3 * i, j) = (*this)(i, j).r;
d(3 * i + 1, j) = (*this)(i, j).g;
d(3 * i + 2, j) = (*this)(i, j).b;
}
}
}
template <>
void MatrixC<Rgb>::get_column_norm(vector<Float> &norms) const {
norms.resize(cols);
for (int c = 0; c < cols; ++c) {
Float magnitude = 0.f;
for (int r = 0; r < rows; ++r) {
Rgb v = (*this)(r, c);
magnitude += v.red() * v.red() + v.green() * v.green() + v.blue() * v.blue();
}
norms[c] = sqrt(magnitude);
}
}
template <>
void MatrixC<Float>::get_column_norm(vector<Float> &norms) const {
norms.resize(cols);
for (int c = 0; c < cols; ++c) {
Float magnitude = 0.f;
for (int r = 0; r < rows; ++r) {
magnitude += (*this)(r, c) * (*this)(r, c);
}
norms[c] = sqrt(magnitude);
}
}
} // end namespace