-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprecompute.py
More file actions
142 lines (119 loc) · 6.59 KB
/
precompute.py
File metadata and controls
142 lines (119 loc) · 6.59 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
Pre-compute all default practical outputs and save as static JSON cache.
Run this once at deploy time: python precompute.py
Results are served as static files — zero server computation at runtime.
"""
import json
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from app.processors.common import get_chapter_images, ensure_chapter
from app.processors import (
p01_display, p02_downsampling, p03_negation_subtraction,
p04_gamma, p05_histogram_eq, p06_histogram_matching,
p07_convolution, p08_filtering,
)
CACHE_DIR = os.path.join(os.path.dirname(__file__), "app", "static", "cache")
os.makedirs(CACHE_DIR, exist_ok=True)
DEFAULT_CHAPTER = 'CH02'
def save(name, data):
path = os.path.join(CACHE_DIR, f"{name}.json")
with open(path, "w") as f:
json.dump(data, f)
size_kb = os.path.getsize(path) / 1024
print(f" {name}.json ({size_kb:.0f} KB)")
def main():
# Ensure default chapter is downloaded
ensure_chapter(DEFAULT_CHAPTER)
images = get_chapter_images(DEFAULT_CHAPTER)
if not images:
print("ERROR: No images found. Check network/dataset availability.")
return
# Default images
cameraman = next((i["filename"] for i in images if "cameraman" in i["filename"]), images[0]["filename"])
body_scan = next((i["filename"] for i in images if "partial_body" in i["filename"]), images[0]["filename"])
einstein_low = next((i["filename"] for i in images if "einstein low" in i["filename"]), images[0]["filename"])
angio_mask = next((i["filename"] for i in images if "angiography_mask" in i["filename"]), None)
angio_live = next((i["filename"] for i in images if "angiography_live" in i["filename"]), None)
skull = next((i["filename"] for i in images if "ctskull" in i["filename"]), images[1]["filename"])
galaxy = next((i["filename"] for i in images if "galaxy" in i["filename"]), images[2]["filename"])
dental = next((i["filename"] for i in images if "dental_xray).tif" in i["filename"]), images[3]["filename"])
ch = DEFAULT_CHAPTER
print(f"Dataset: {len(images)} images from {ch}")
print(f"Defaults: {cameraman}, {body_scan}, {einstein_low}")
print()
# === Practical 1 ===
print("Practical 1: Display")
save("p1_display", p01_display.display_image(cameraman, chapter=ch))
save("p1_histogram", p01_display.display_histogram(cameraman, chapter=ch))
save("p1_multi", p01_display.display_multiple([
{"chapter": ch, "filename": cameraman},
{"chapter": ch, "filename": skull},
{"chapter": ch, "filename": dental},
{"chapter": ch, "filename": galaxy},
]))
# === Practical 2 ===
print("Practical 2: Downsampling")
save("p2_downsample", p02_downsampling.downsample_series(cameraman, chapter=ch, steps=5))
save("p2_comparison", p02_downsampling.downsample_comparison_plot(cameraman, chapter=ch))
save("p2_upscale", p02_downsampling.upscale_comparison_plot(cameraman, chapter=ch))
# === Practical 3 ===
print("Practical 3: Negation/Subtraction")
save("p3_negate", p03_negation_subtraction.compute_negation(body_scan, chapter=ch))
if angio_mask and angio_live:
save("p3_subtract", p03_negation_subtraction.compute_subtraction(angio_mask, angio_live, chapter1=ch, chapter2=ch))
save("p3_pipeline", p03_negation_subtraction.compute_pipeline(angio_mask, angio_live, chapter1=ch, chapter2=ch))
# === Practical 4 ===
print("Practical 4: Gamma")
save("p4_gamma", p04_gamma.apply_gamma(einstein_low, chapter=ch, gamma=0.4))
save("p4_series", p04_gamma.gamma_series(einstein_low, chapter=ch))
save("p4_curves", p04_gamma.transformation_curves())
save("p4_log", p04_gamma.log_transform(einstein_low, chapter=ch))
save("p4_contrast", p04_gamma.contrast_enhancement(einstein_low, chapter=ch, mode="dark"))
# === Practical 5 ===
print("Practical 5: Histogram Equalization")
save("p5_original_histogram", p05_histogram_eq.compute_original_histogram(einstein_low, chapter=ch))
save("p5_equalize", p05_histogram_eq.compute_equalization(einstein_low, chapter=ch))
save("p5_transfer", p05_histogram_eq.compute_transfer_function(einstein_low, chapter=ch))
save("p5_multi", p05_histogram_eq.compute_multi_equalize([
{"chapter": ch, "filename": einstein_low},
{"chapter": ch, "filename": cameraman},
{"chapter": ch, "filename": skull},
{"chapter": ch, "filename": galaxy},
]))
# === Practical 6 ===
einstein_high = next((i["filename"] for i in images if "einstein high" in i["filename"]), cameraman)
print("Practical 6: Histogram Matching")
save("p6_source_histogram", p06_histogram_matching.compute_source_histogram(einstein_low, chapter=ch))
save("p6_equalize", p06_histogram_matching.compute_equalize_baseline(einstein_low, chapter=ch))
save("p6_match", p06_histogram_matching.compute_matching(einstein_low, cameraman, src_chapter=ch, tgt_chapter=ch))
save("p6_multi_target", p06_histogram_matching.compute_multi_target(einstein_low, [
{"filename": einstein_high, "chapter": ch, "label": "High Contrast"},
{"filename": cameraman, "chapter": ch, "label": "Cameraman"},
], src_chapter=ch))
save("p6_transfer", p06_histogram_matching.compute_transfer_analysis(einstein_low, cameraman, src_chapter=ch, tgt_chapter=ch))
# === Practical 7: Correlation & Convolution ===
print("Practical 7: Correlation & Convolution")
save("p7_impulse", p07_convolution.compute_impulse_demo())
save("p7_filter", p07_convolution.compute_image_filtering(cameraman, chapter=ch))
save("p7_verify", p07_convolution.compute_verify_cv2(cameraman, chapter=ch))
# === Practical 8: Spatial Filtering ===
# Needs CH03 (test pattern, salt-pepper, moon, contact lens). Pre-fetch it.
print("Practical 8: Spatial Filtering")
if ensure_chapter('CH03'):
ch3_imgs = get_chapter_images('CH03')
if ch3_imgs:
save("p8_box", p08_filtering.compute_box_series(chapter='CH03'))
save("p8_median", p08_filtering.compute_median_series(chapter='CH03'))
save("p8_compare", p08_filtering.compute_box_vs_median(chapter='CH03'))
save("p8_laplacian", p08_filtering.compute_laplacian(chapter='CH03'))
save("p8_sobel", p08_filtering.compute_sobel(chapter='CH03'))
else:
print(" CH03 download failed; skipping P8 cache")
else:
print(" CH03 unavailable; skipping P8 cache")
# === Image list (legacy) ===
save("images", {"images": images, "count": len(images)})
print(f"\nDone! {len(os.listdir(CACHE_DIR))} cache files in {CACHE_DIR}")
if __name__ == "__main__":
main()