Repository navigation
Expand file tree
/
Copy pathwavelet_test.py
More file actions
98 lines (80 loc) · 4.04 KB
/
Copy pathwavelet_test.py
File metadata and controls
98 lines (80 loc) · 4.04 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
import os
import cv2
import pandas as pd
from tqdm import tqdm
from skimage.metrics import peak_signal_noise_ratio as psnr, structural_similarity as ssim
# Make sure this script is run from the root of your project directory
from src.wavelet_codec import wavelet_compress, wavelet_decompress, wavelet_save, wavelet_load
def estimate_bitrate(filesize_bytes, img_shape):
# Rough bitrate: size in bits divided by number of pixels
num_pixels = img_shape[0] * img_shape[1]
return (filesize_bytes * 8) / num_pixels
def run_wavelet_test(data_dirs, output_csv_name):
"""
Tests the wavelet encoding and decoding process on all images in the provided directories
and saves the reconstructed images and metrics.
"""
# --- Configuration ---
base_results_dir = "results"
output_image_dir = os.path.join(base_results_dir, "wavelet")
metrics_dir = "results/metrics/"
# --- Setup ---
os.makedirs(output_image_dir, exist_ok=True)
os.makedirs(metrics_dir, exist_ok=True)
print(f"Output images will be saved to: {output_image_dir}")
print(f"Metrics will be saved to: {metrics_dir}")
collected_metrics = []
# --- Processing Loop for each dataset ---
for dataset_name, dataset_path in data_dirs.items():
print(f"\nProcessing dataset: {dataset_name}")
try:
image_files = [f for f in os.listdir(dataset_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff'))]
if not image_files:
print(f"Warning: No images found in '{dataset_path}'. Skipping.")
continue
except FileNotFoundError:
print(f"Error: Input directory not found at '{dataset_path}'. Skipping.")
continue
# Create a specific output directory for this dataset's reconstructed images
dataset_output_dir = os.path.join(output_image_dir, dataset_name)
os.makedirs(dataset_output_dir, exist_ok=True)
for image_name in tqdm(image_files, desc=f"Processing {dataset_name}", unit="image"):
image_path = os.path.join(dataset_path, image_name)
# 1. Read the image
img_color = cv2.imread(image_path)
img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
# 2. Compress the image
coeffs_quant = wavelet_compress(img_color)
# 3. Save compressed data to measure file size
wavelet_file_path = os.path.join(dataset_output_dir, f"{os.path.splitext(image_name)[0]}_wavelet.npz")
wavelet_save(coeffs_quant, wavelet_file_path)
# 4. Decompress the image to reconstruct it
reconstructed_img = wavelet_decompress(coeffs_quant)
# --- FIX: Ensure reconstructed image has the same dimensions as the original ---
if reconstructed_img.shape != img_gray.shape:
reconstructed_img = cv2.resize(reconstructed_img, (img_gray.shape[1], img_gray.shape[0]))
# 5. Save the reconstructed image
output_path = os.path.join(dataset_output_dir, f"wavelet_recon_{image_name}")
cv2.imwrite(output_path, reconstructed_img)
# 6. Calculate and store metrics
metrics = {
'dataset': dataset_name,
'image': image_name,
'psnr': psnr(img_gray, reconstructed_img),
'ssim': ssim(img_gray, reconstructed_img),
'bitrate': estimate_bitrate(os.path.getsize(wavelet_file_path), img_gray.shape)
}
collected_metrics.append(metrics)
# --- Save Metrics to CSV ---
df = pd.DataFrame(collected_metrics)
csv_output_path = os.path.join(metrics_dir, output_csv_name)
df.to_csv(csv_output_path, index=False)
print(f"\nTest complete. Reconstructed images are saved in '{output_image_dir}'.")
print(f"Metrics saved to '{csv_output_path}'.")
if __name__ == "__main__":
data_dirs = {
"kodak": "data/kodak",
"standard_test": "data/standard_test",
"clic_subset": "data/clic_subset"
}
run_wavelet_test(data_dirs, "wavelet.csv")