pmlpp/mlpp/transforms/transforms.cpp

59 lines
1.2 KiB
C++
Raw Normal View History

//
// Transforms.cpp
//
// Created by Marc Melikyan on 11/13/20.
//
2023-01-24 18:12:23 +01:00
#include "transforms.h"
#include "../lin_alg/lin_alg.h"
2023-12-28 14:41:45 +01:00
#include "core/math/math_funcs.h"
2023-01-24 19:00:54 +01:00
// DCT ii.
// https://www.mathworks.com/help/images/discrete-cosine-transform.html
2023-12-28 14:41:45 +01:00
Ref<MLPPMatrix> MLPPTransforms::discrete_cosine_transform(const Ref<MLPPMatrix> &p_A) {
Ref<MLPPMatrix> A = p_A->scalar_addn(-128); // Center around 0.
Size2i size = A->size();
Ref<MLPPMatrix> B;
B.instance();
B->resize(size);
2023-01-24 19:00:54 +01:00
2023-12-28 14:41:45 +01:00
real_t M = size.y;
real_t inv_sqrt_M = 1 / Math::sqrt(M);
real_t s2M = Math::sqrt(real_t(2) / real_t(M));
2023-01-24 19:00:54 +01:00
2023-12-28 14:41:45 +01:00
for (int i = 0; i < size.y; i++) {
for (int j = 0; j < size.x; j++) {
2023-01-27 13:01:16 +01:00
real_t sum = 0;
2023-12-28 14:41:45 +01:00
2023-01-27 13:01:16 +01:00
real_t alphaI;
2023-01-24 19:00:54 +01:00
if (i == 0) {
2023-12-28 14:41:45 +01:00
alphaI = inv_sqrt_M;
2023-01-24 19:00:54 +01:00
} else {
2023-12-28 14:41:45 +01:00
alphaI = s2M;
2023-01-24 19:00:54 +01:00
}
2023-12-28 14:41:45 +01:00
2023-01-27 13:01:16 +01:00
real_t alphaJ;
2023-01-24 19:00:54 +01:00
if (j == 0) {
2023-12-28 14:41:45 +01:00
alphaJ = inv_sqrt_M;
2023-01-24 19:00:54 +01:00
} else {
2023-12-28 14:41:45 +01:00
alphaJ = s2M;
2023-01-24 19:00:54 +01:00
}
2023-12-28 14:41:45 +01:00
for (int k = 0; k < size.y; k++) {
for (int f = 0; f < size.x; f++) {
sum += A->element_get(k, f) * Math::cos((Math_PI * i * (2 * k + 1)) / (2 * M)) * Math::cos((Math_PI * j * (2 * f + 1)) / (2 * M));
2023-01-24 19:00:54 +01:00
}
}
2023-12-28 14:41:45 +01:00
B->element_set(i, j, sum * alphaI * alphaJ);
2023-01-24 19:00:54 +01:00
}
}
return B;
}
void MLPPTransforms::_bind_methods() {
}