From 31351ea91ddeab7df2cddfd4545f4c1c6e1ad3ba Mon Sep 17 00:00:00 2001 From: Mark Hoekveen Date: Tue, 7 May 2024 01:31:26 +0200 Subject: [PATCH] refactor idct --- src/descriptors/dct.rs | 66 +++++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/src/descriptors/dct.rs b/src/descriptors/dct.rs index 39b33e7..de0d91f 100644 --- a/src/descriptors/dct.rs +++ b/src/descriptors/dct.rs @@ -38,6 +38,41 @@ impl DCT { } quantization_matrix } + + /// TODO + // pub fn dct(&self, img: image::DynamicImage) -> [f64; 64] { + // } + + pub fn idct(&self, dct_values: [f64; 64]) -> [u8; 64] { + let mut reconstructed: [u8; 64] = [0; 64]; + for k in 0..64 { + let x = (k%8) as f64; + let y = (k/8) as f64; + let mut sum = 0.0; + for u in 0..8 { + for v in 0..8 { + let mut alpha = 1.0; + if u == 0 { + alpha = alpha / SQRT_2 + } + if v == 0 { + alpha = alpha / SQRT_2 + } + let uv = (v*8)+u; + let v = v as f64; + let u = u as f64; + sum += + alpha * + dct_values[uv] * + ((2.0 * x + 1.0) * u * PI / 16.0).cos() * + ((2.0 * y + 1.0) * v * PI / 16.0).cos() + } + } + sum = 127.0 + (0.25 * sum).round(); + reconstructed[k] = std::cmp::min(255_u8, sum as u8); + } + reconstructed + } } impl Descriptor for DCT { @@ -48,7 +83,6 @@ impl Descriptor for DCT { println!("Base quantization matrix:\n{}", print_matrix(self.quantization_matrix)); println!("Q-{} quantization matrix:\n{}", quality, print_matrix(qmatrix)); let mut dct_values: [f64; 64] = [0.0; 64]; - let mut reconstructed: [u8; 64] = [0; 64]; let img = self.resize(img); img.save("resize.png").expect("Error saving file"); for u in 0..8 { @@ -88,34 +122,8 @@ impl Descriptor for DCT { dct_values[i] = dct_values[i] * qmatrix[i] as f64; } println!("DCT-coefficients, de-quantized:\n {}", print_matrix(dct_values)); - for k in 0..64 { - let x = (k%8) as f64; - let y = (k/8) as f64; - let mut sum = 0.0; - for u in 0..8 { - for v in 0..8 { - let mut alpha = 1.0; - if u == 0 { - alpha = alpha / SQRT_2 - } - if v == 0 { - alpha = alpha / SQRT_2 - } - let uv = (v*8)+u; - let v = v as f64; - let u = u as f64; - sum += - alpha * - dct_values[uv] * - ((2.0 * x + 1.0) * u * PI / 16.0).cos() * - ((2.0 * y + 1.0) * v * PI / 16.0).cos() - } - } - sum = 127.0 + (0.25 * sum).round(); - //println!("Reconstructed pixel: {}", sum); - reconstructed[k] = std::cmp::min(255_u8, sum as u8); - } - //println!("{}", print_matrix(reconstructed)); + let reconstructed = self.idct(dct_values); + println!("Reconstructed pixel values:\n{}", print_matrix(reconstructed)); save_buffer( "reconstructed.png", &reconstructed,