-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathultrastack.py
More file actions
1495 lines (1255 loc) · 64.3 KB
/
ultrastack.py
File metadata and controls
1495 lines (1255 loc) · 64.3 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
╔══════════════════════════════════════════════════════════════════════════════════╗
║ U L T R A S T A C K ║
║ GPU-Accelerated Image & Video Stacking / Stitching Pipeline ║
║ with full Astronomical SER support ║
╠══════════════════════════════════════════════════════════════════════════════════╣
║ INPUT SOURCES ║
║ • Folder of images — any single format: JPG, PNG, TIFF, BMP, WEBP, FIT/FITS ║
║ • Video files — MP4, AVI, MOV, MKV, WMV, WEBM, M4V, SER ║
║ • SER files — astronomical capture format (mono/Bayer/RGB/BGR/YUV) ║
║ ║
║ STACKING MODES ║
║ • Average stack — classic mean, best for photon noise reduction ║
║ • Median stack — robust against outliers/satellites/hot pixels ║
║ • Sigma-clipping — astronomers' favourite: iterative outlier rejection ║
║ • Maximum stack — keep brightest pixel per position (star trails etc.) ║
║ • Minimum stack — keep darkest pixel (background subtraction helpers) ║
║ ║
║ ALIGNMENT ║
║ • ORB feature matching — fast, great for planetary/landscape ║
║ • ECC (Enhanced Correlation Coefficient) — sub-pixel accuracy, ideal for astro ║
║ ║
║ PIPELINE FEATURES ║
║ • SIFT + FLANN intelligent image grouping before stacking ║
║ • Optional panorama stitching of stacked groups ║
║ • Adaptive VRAM-safe batch processing ║
║ • Parallel image loading with ThreadPoolExecutor ║
║ • Frame skipping and max_frames controls for video/SER ║
║ • Dark frame subtraction (calibration frames) ║
║ • Hot pixel removal (cosmetic correction) ║
║ • Histogram stretch / auto-levels for faint targets ║
║ • Post-processing: denoise + sharpen ║
║ • Output: JPG, PNG, TIFF (16-bit TIFF for FITS/SER data) ║
║ • Google Colab support + CLI interface ║
╠══════════════════════════════════════════════════════════════════════════════════╣
║ Requirements ║
║ pip install opencv-contrib-python numpy torch tqdm ║
║ Optional for FITS: pip install astropy ║
╚══════════════════════════════════════════════════════════════════════════════════╝
Usage:
# Stack a folder of PNGs (auto-detected format):
python ultrastack.py --input ./frames --output result.png
# Stack with median + sigma clipping (astronomical mode):
python ultrastack.py --input ./lights --output deep.tif --mode sigma --align ecc
# Stack with dark frame subtraction:
python ultrastack.py --input ./lights --dark ./darks --output result.tif
# Stack a SER file:
python ultrastack.py --input capture.ser --output stacked.tif --mode sigma
# Stack + stitch panorama:
python ultrastack.py --input ./mosaic_tiles --output pano.jpg --stitch
# Stack video, every 3rd frame, max 500:
python ultrastack.py --input timelapse.mp4 --skip 3 --max-frames 500 --output out.jpg
"""
import cv2
import numpy as np
import os
import gc
import sys
import struct
import warnings
import argparse
from pathlib import Path
from datetime import datetime
from typing import List, Tuple, Optional, Generator
from concurrent.futures import ThreadPoolExecutor, as_completed
warnings.filterwarnings("ignore")
# ══════════════════════════════════════════════════════════════════════════════
# CONSTANTS
# ══════════════════════════════════════════════════════════════════════════════
IMAGE_EXTENSIONS = {
".jpg", ".jpeg",
".png",
".tif", ".tiff",
".bmp",
".webp",
".fit", ".fits", # astronomical FITS (requires astropy)
".ppm", ".pgm", # portable bitmap formats
".exr", # OpenEXR (HDR)
}
VIDEO_EXTENSIONS = {
".mp4", ".avi", ".mov", ".mkv",
".wmv", ".webm", ".m4v", ".flv",
".ts", ".mts", ".m2ts", # transport stream / AVCHD
}
SER_EXTENSION = ".ser"
# SER colour IDs (from SER spec)
SER_MONO = 0
SER_BAYER_RGGB = 8
SER_BAYER_GRBG = 9
SER_BAYER_GBRG = 10
SER_BAYER_BGGR = 11
SER_BAYER_CYYM = 16
SER_BAYER_YCMY = 17
SER_BAYER_YMCY = 18
SER_BAYER_MYYC = 19
SER_RGB = 100
SER_BGR = 101
BAYER_CODES = {
SER_BAYER_RGGB: cv2.COLOR_BayerRG2BGR,
SER_BAYER_GRBG: cv2.COLOR_BayerGR2BGR,
SER_BAYER_GBRG: cv2.COLOR_BayerGB2BGR,
SER_BAYER_BGGR: cv2.COLOR_BayerBG2BGR,
}
STACK_MODES = ["average", "median", "sigma", "maximum", "minimum"]
ALIGN_MODES = ["none", "orb", "ecc"]
OUTPUT_EXTENSIONS = {".jpg", ".jpeg", ".png", ".tif", ".tiff"}
# ══════════════════════════════════════════════════════════════════════════════
# DISPLAY / UTILITIES
# ══════════════════════════════════════════════════════════════════════════════
def banner(text: str, width: int = 64, char: str = "═"):
print(f"\n{char * width}\n {text}\n{char * width}")
def info(msg: str): print(f" {msg}")
def warn(msg: str): print(f" ⚠ {msg}")
def ok(msg: str): print(f" ✓ {msg}")
def err(msg: str): print(f" ✗ {msg}")
def print_image_stats(img: np.ndarray, filepath: str):
h, w = img.shape[:2]
mp = (h * w) / 1_000_000
size_kb = os.path.getsize(filepath) / 1024
channels = img.shape[2] if img.ndim == 3 else 1
print()
info(f"Resolution : {w} × {h} px ({mp:.2f} MP)")
info(f"File size : {size_kb:.0f} KB ({size_kb/1024:.2f} MB)")
info(f"Channels : {channels}")
info(f"dtype : {img.dtype}")
info(f"Min / Max : {img.min()} / {img.max()}")
info(f"Mean : {float(img.mean()):.2f}")
info(f"Std dev : {float(img.std()):.2f}")
info(f"Saved to : {filepath}")
# ══════════════════════════════════════════════════════════════════════════════
# GPU SETUP
# ══════════════════════════════════════════════════════════════════════════════
def setup_device(force_cpu: bool = False):
"""Return (device_string, torch_module_or_None)."""
if force_cpu:
info("GPU disabled — using CPU (numpy)")
return "cpu", None
try:
import torch
if torch.cuda.is_available():
name = torch.cuda.get_device_name(0)
vram = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
ok(f"GPU: {name} ({vram:.1f} GB VRAM)")
return "cuda", torch
else:
warn("CUDA not available — using CPU")
return "cpu", torch
except ImportError:
warn("PyTorch not installed — using CPU (numpy only)")
return "cpu", None
def estimate_safe_batch(img_shape: Tuple, device: str, torch_module) -> int:
if device != "cuda" or torch_module is None:
return 16
try:
props = torch_module.cuda.get_device_properties(0)
avail = props.total_memory * 0.70
h, w = img_shape[:2]
c = img_shape[2] if len(img_shape) == 3 else 1
bytes_per = h * w * c * 4
return max(1, int(avail // (bytes_per * 1.5)))
except Exception:
return 4
# ══════════════════════════════════════════════════════════════════════════════
# SER FILE READER
# ══════════════════════════════════════════════════════════════════════════════
class SERFile:
"""
Full SER (Sequence of images for astronomical Recording) file reader.
SER format specification:
- 178-byte header
- Raw frame data (little-endian, 8 or 16 bit)
- Optional UTC timestamp trailer
Colour IDs handled: MONO, all Bayer patterns, RGB, BGR.
16-bit frames are normalised to uint8 or kept as uint16 depending on caller.
"""
HEADER_SIZE = 178
HEADER_FMT = "<14siiiii40s40siqq" # 14+4+4+4+4+4+40+40+8+8+8 = 178 bytes? let's parse manually
def __init__(self, path: str):
self.path = path
self.file = open(path, "rb")
self._parse_header()
def _parse_header(self):
hdr = self.file.read(self.HEADER_SIZE)
if len(hdr) < self.HEADER_SIZE:
raise ValueError("File too small to be a valid SER file")
# FileID: 14 bytes
file_id = hdr[0:14].decode("ascii", errors="ignore").rstrip("\x00")
if not file_id.startswith("LUCAM-RECORDER"):
warn(f"SER FileID is '{file_id}' — may not be a standard SER file, continuing anyway")
# Unpack fixed fields (all little-endian int32)
self.lu_id = struct.unpack_from("<i", hdr, 14)[0]
self.color_id = struct.unpack_from("<i", hdr, 18)[0]
self.little_endian = struct.unpack_from("<i", hdr, 22)[0] # 0=big, non-0=little
self.image_width = struct.unpack_from("<i", hdr, 26)[0]
self.image_height= struct.unpack_from("<i", hdr, 30)[0]
self.pixel_depth = struct.unpack_from("<i", hdr, 34)[0] # bits per pixel per plane
self.frame_count = struct.unpack_from("<i", hdr, 38)[0]
# Observer / Telescope / Instrument strings (40 bytes each, null-padded)
self.observer = hdr[42:82].decode("ascii", errors="ignore").rstrip("\x00")
self.instrument = hdr[82:122].decode("ascii", errors="ignore").rstrip("\x00")
self.telescope = hdr[122:162].decode("ascii", errors="ignore").rstrip("\x00")
# Date / DateUTC (8 bytes each, int64 Windows FILETIME)
# We don't strictly need these for stacking
# Determine channel count from color_id
if self.color_id in (SER_RGB, SER_BGR):
self.channels = 3
elif self.color_id == SER_MONO:
self.channels = 1
elif self.color_id in BAYER_CODES:
self.channels = 1 # raw Bayer stored as mono, debayered on read
else:
warn(f"Unknown SER color_id {self.color_id} — treating as mono")
self.channels = 1
self.bytes_per_pixel = (self.pixel_depth + 7) // 8 # e.g. 8→1, 12/16→2
self.frame_bytes = self.image_width * self.image_height * self.channels * self.bytes_per_pixel
self.data_offset = self.HEADER_SIZE
info(f"SER {self.image_width}×{self.image_height} "
f"{self.frame_count} frames "
f"{self.pixel_depth}-bit "
f"color_id={self.color_id}")
if self.observer: info(f"Observer : {self.observer}")
if self.instrument: info(f"Instrument : {self.instrument}")
if self.telescope: info(f"Telescope : {self.telescope}")
def read_frame(self, index: int) -> np.ndarray:
"""
Read a single frame by index (0-based).
Returns a BGR uint8 (or uint16 for 16-bit) numpy array.
"""
if index < 0 or index >= self.frame_count:
raise IndexError(f"Frame {index} out of range (0..{self.frame_count-1})")
offset = self.data_offset + index * self.frame_bytes
self.file.seek(offset)
raw = self.file.read(self.frame_bytes)
if len(raw) < self.frame_bytes:
raise ValueError(f"Unexpected EOF at frame {index}")
dtype = np.uint8 if self.bytes_per_pixel == 1 else np.uint16
arr = np.frombuffer(raw, dtype=dtype)
# Handle endianness for 16-bit
if dtype == np.uint16 and self.little_endian == 0:
arr = arr.byteswap()
# Reshape
if self.channels == 3:
frame = arr.reshape((self.image_height, self.image_width, 3))
else:
frame = arr.reshape((self.image_height, self.image_width))
# Normalise 16-bit to 8-bit for downstream processing
# We keep full 16-bit depth here; callers can normalise if needed
if dtype == np.uint16 and self.pixel_depth < 16:
# e.g. 12-bit packed in 16-bit: shift down
frame = (frame >> (self.pixel_depth - 8)).astype(np.uint16)
# Debayer if necessary
if self.color_id in BAYER_CODES:
if dtype == np.uint16:
frame8 = (frame >> 8).astype(np.uint8)
frame = cv2.cvtColor(frame8, BAYER_CODES[self.color_id])
else:
frame = cv2.cvtColor(frame, BAYER_CODES[self.color_id])
# SER_RGB → convert to BGR for OpenCV
if self.color_id == SER_RGB:
if frame.ndim == 3:
frame = frame[:, :, ::-1].copy()
# Mono: expand to 3-channel BGR for consistent downstream handling
if frame.ndim == 2:
frame = cv2.cvtColor(
frame.astype(np.uint8) if frame.dtype == np.uint8
else (frame >> 8).astype(np.uint8),
cv2.COLOR_GRAY2BGR
)
elif frame.dtype == np.uint16:
frame = (frame >> 8).astype(np.uint8)
return frame # always uint8 BGR after this point
def frames(self, frame_skip: int = 1,
max_frames: Optional[int] = None) -> Generator[Tuple[int, np.ndarray], None, None]:
"""Generator yielding (index, frame_bgr) respecting skip and max."""
yielded = 0
for i in range(0, self.frame_count, frame_skip):
yield i, self.read_frame(i)
yielded += 1
if max_frames and yielded >= max_frames:
break
def close(self):
self.file.close()
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
# ══════════════════════════════════════════════════════════════════════════════
# FITS READER (optional, requires astropy)
# ══════════════════════════════════════════════════════════════════════════════
def load_fits(path: str) -> np.ndarray:
"""
Load a FITS image using astropy and return a BGR uint8 numpy array.
Handles 2D (mono) and 3D (RGB cube) FITS files.
Auto-stretches for display.
"""
try:
from astropy.io import fits
except ImportError:
raise ImportError("astropy is required to load FITS files.\n"
"Install with: pip install astropy")
with fits.open(path) as hdul:
data = hdul[0].data
if data is None:
# Try first extension with data
with fits.open(path) as hdul:
for hdu in hdul:
if hdu.data is not None:
data = hdu.data
break
if data is None:
raise ValueError(f"No image data found in FITS file: {path}")
data = data.astype(np.float32)
# Normalise to 0-255
lo, hi = np.percentile(data, 1), np.percentile(data, 99)
if hi > lo:
data = np.clip((data - lo) / (hi - lo) * 255, 0, 255).astype(np.uint8)
else:
data = np.zeros_like(data, dtype=np.uint8)
# Shape handling
if data.ndim == 2:
bgr = cv2.cvtColor(data, cv2.COLOR_GRAY2BGR)
elif data.ndim == 3:
if data.shape[0] == 3: # (3, H, W) cube
data = np.moveaxis(data, 0, -1) # → (H, W, 3)
bgr = cv2.cvtColor(data, cv2.COLOR_RGB2BGR)
else:
raise ValueError(f"Unsupported FITS data shape: {data.shape}")
return bgr
# ══════════════════════════════════════════════════════════════════════════════
# IMAGE LOADING
# ══════════════════════════════════════════════════════════════════════════════
def load_single_image(path: Path) -> np.ndarray:
"""Load one image file → BGR uint8, regardless of format."""
ext = path.suffix.lower()
if ext in (".fit", ".fits"):
return load_fits(str(path))
img = cv2.imread(str(path), cv2.IMREAD_COLOR)
if img is None:
# Try with UNCHANGED and convert (handles 16-bit TIFF etc.)
img = cv2.imread(str(path), cv2.IMREAD_UNCHANGED)
if img is None:
raise ValueError(f"Cannot read: {path}")
if img.dtype == np.uint16:
img = (img >> 8).astype(np.uint8)
if img.ndim == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
elif img.shape[2] == 4:
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
return img
def detect_folder_format(folder_path: str) -> Tuple[str, List[Path]]:
"""
Auto-detect the predominant image format in a folder.
All images must be the same format.
Returns (extension, sorted_list_of_paths).
"""
folder = Path(folder_path)
counts = {}
for p in folder.iterdir():
ext = p.suffix.lower()
if ext in IMAGE_EXTENSIONS:
counts[ext] = counts.get(ext, 0) + 1
if not counts:
raise FileNotFoundError(f"No supported images found in: {folder_path}")
# Pick the most common extension
dominant_ext = max(counts, key=counts.__getitem__)
if len(counts) > 1:
other = {k: v for k, v in counts.items() if k != dominant_ext}
warn(f"Multiple image formats found: {counts}")
warn(f"Using dominant format: '{dominant_ext}' ({counts[dominant_ext]} files)")
warn(f"Ignoring: {other}")
paths = sorted(folder.glob(f"*{dominant_ext}"))
info(f"Found {len(paths)} '{dominant_ext}' files in folder")
return dominant_ext, paths
def load_images_parallel(paths: List[Path], max_workers: int = 8) -> List[np.ndarray]:
"""Load a list of image paths in parallel."""
images = [None] * len(paths)
done = 0
def _load(idx_path):
idx, path = idx_path
return idx, load_single_image(path)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(_load, (i, p)): i for i, p in enumerate(paths)}
for future in as_completed(futures):
try:
idx, img = future.result()
images[idx] = img
done += 1
print(f"\r Loading... {done}/{len(paths)}", end="", flush=True)
except Exception as e:
i = futures[future]
warn(f"\nSkipping {paths[i].name}: {e}")
print()
return [img for img in images if img is not None]
# ══════════════════════════════════════════════════════════════════════════════
# CALIBRATION: DARK FRAME SUBTRACTION + HOT PIXEL REMOVAL
# ══════════════════════════════════════════════════════════════════════════════
def make_master_dark(dark_folder: str) -> np.ndarray:
"""
Stack all images in dark_folder (median stack) to produce a master dark frame.
"""
banner("Building Master Dark Frame", char="-")
_, paths = detect_folder_format(dark_folder)
darks = load_images_parallel(paths)
if not darks:
raise FileNotFoundError("No dark frames found")
info(f"Stacking {len(darks)} dark frames (median)...")
stack = np.stack([d.astype(np.float32) for d in darks], axis=0)
master = np.median(stack, axis=0).astype(np.uint8)
ok("Master dark ready")
return master
def subtract_dark(image: np.ndarray, master_dark: np.ndarray) -> np.ndarray:
"""Subtract master dark from image (clamped at 0)."""
result = image.astype(np.int32) - master_dark.astype(np.int32)
return np.clip(result, 0, 255).astype(np.uint8)
def remove_hot_pixels(image: np.ndarray, threshold: int = 70) -> np.ndarray:
"""
Cosmetic correction: replace hot pixels with the local median.
A pixel is 'hot' if it deviates > threshold from its 3×3 neighbourhood median.
Operates per-channel.
"""
result = image.copy()
for c in range(image.shape[2] if image.ndim == 3 else 1):
ch = image[:, :, c] if image.ndim == 3 else image
med = cv2.medianBlur(ch, 3)
diff = cv2.absdiff(ch, med)
mask = diff > threshold
if image.ndim == 3:
result[:, :, c] = np.where(mask, med, ch)
else:
result = np.where(mask, med, ch)
return result
# ══════════════════════════════════════════════════════════════════════════════
# HISTOGRAM STRETCH (for faint targets)
# ══════════════════════════════════════════════════════════════════════════════
def auto_stretch(image: np.ndarray,
lo_pct: float = 0.5,
hi_pct: float = 99.5) -> np.ndarray:
"""
Auto-stretch: remap the lo_pct–hi_pct intensity range to 0–255.
Useful for revealing faint nebulae / galaxies after stacking.
Works per-channel to avoid colour shifts.
"""
result = np.zeros_like(image, dtype=np.uint8)
for c in range(image.shape[2] if image.ndim == 3 else 1):
ch = image[:, :, c] if image.ndim == 3 else image
lo = np.percentile(ch, lo_pct)
hi = np.percentile(ch, hi_pct)
if hi > lo:
stretched = np.clip((ch.astype(np.float32) - lo) / (hi - lo) * 255, 0, 255)
else:
stretched = ch.astype(np.float32)
if image.ndim == 3:
result[:, :, c] = stretched.astype(np.uint8)
else:
result = stretched.astype(np.uint8)
return result
# ══════════════════════════════════════════════════════════════════════════════
# ALIGNMENT
# ══════════════════════════════════════════════════════════════════════════════
def align_orb(base_gray: np.ndarray, frame_bgr: np.ndarray,
max_features: int = 5000) -> np.ndarray:
"""
Align frame_bgr to base_gray using ORB feature matching + homography.
Grayscale used for detection; full-colour frame is warped.
"""
orb = cv2.ORB_create(max_features)
frame_gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
kp1, des1 = orb.detectAndCompute(base_gray, None)
kp2, des2 = orb.detectAndCompute(frame_gray, None)
if des1 is None or des2 is None or len(kp1) < 4 or len(kp2) < 4:
return frame_bgr
matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = sorted(matcher.match(des1, des2), key=lambda m: m.distance)
if len(matches) < 4:
return frame_bgr
src = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
dst = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
H, mask = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)
if H is None:
return frame_bgr
return cv2.warpPerspective(frame_bgr, H,
(base_gray.shape[1], base_gray.shape[0]))
def align_ecc(base_gray: np.ndarray, frame_bgr: np.ndarray) -> np.ndarray:
"""
Sub-pixel alignment using Enhanced Correlation Coefficient (ECC).
Best for astronomical images with stars — finds translational + rotational shift.
Falls back to ORB if ECC fails to converge.
"""
frame_gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
# Use affine (6 DOF) — handles translation + rotation + shear
warp_mode = cv2.MOTION_EUCLIDEAN # rotation + translation only for astro
warp_matrix = np.eye(2, 3, dtype=np.float32)
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 200, 1e-7)
try:
_, warp_matrix = cv2.findTransformECC(
base_gray.astype(np.float32),
frame_gray.astype(np.float32),
warp_matrix,
warp_mode,
criteria,
None, 5
)
h, w = base_gray.shape
aligned = cv2.warpAffine(frame_bgr, warp_matrix, (w, h),
flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
return aligned
except cv2.error:
# ECC failed (low contrast, etc.) — fallback to ORB
return align_orb(base_gray, frame_bgr)
def align_frame(base_gray: np.ndarray, frame_bgr: np.ndarray,
method: str = "orb") -> np.ndarray:
"""Dispatch alignment to chosen method."""
if method == "orb":
return align_orb(base_gray, frame_bgr)
elif method == "ecc":
return align_ecc(base_gray, frame_bgr)
else:
return frame_bgr # "none"
# ══════════════════════════════════════════════════════════════════════════════
# STACKING CORE
# ══════════════════════════════════════════════════════════════════════════════
def stack_images(images_bgr: List[np.ndarray],
mode: str = "average",
sigma_low: float = 2.0,
sigma_high: float = 2.0,
sigma_iters: int = 3,
device: str = "cpu",
torch_module=None) -> np.ndarray:
"""
Stack a list of BGR images using the chosen mode.
Modes:
average — mean of all frames (GPU-accelerated)
median — median per pixel (robust against outliers)
sigma — sigma-clipping then mean (astronomical standard)
maximum — max per pixel (star trails, lightning)
minimum — min per pixel (background extraction)
"""
if len(images_bgr) == 1:
return images_bgr[0]
n = len(images_bgr)
if mode == "average":
return _stack_average_gpu(images_bgr, device, torch_module)
elif mode == "maximum":
result = images_bgr[0].astype(np.float32)
for img in images_bgr[1:]:
result = np.maximum(result, img.astype(np.float32))
return result.astype(np.uint8)
elif mode == "minimum":
result = images_bgr[0].astype(np.float32)
for img in images_bgr[1:]:
result = np.minimum(result, img.astype(np.float32))
return result.astype(np.uint8)
elif mode == "median":
# Load into float stack — memory-intensive but accurate
info(f" Building median stack ({n} frames)...")
stack = np.stack([img.astype(np.float32) for img in images_bgr], axis=0)
result = np.median(stack, axis=0)
del stack
gc.collect()
return np.clip(result, 0, 255).astype(np.uint8)
elif mode == "sigma":
return _stack_sigma_clip(images_bgr, sigma_low, sigma_high, sigma_iters)
else:
raise ValueError(f"Unknown stack mode '{mode}'. Choose from: {STACK_MODES}")
def _stack_average_gpu(images_bgr: List[np.ndarray],
device: str, torch_module) -> np.ndarray:
"""
GPU-accelerated average stack.
Converts BGR→RGB internally, accumulates on-device, returns BGR uint8.
"""
if torch_module is not None:
t = torch_module
total = None
for img in images_bgr:
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
tensor = t.from_numpy(rgb).float().to(device)
total = tensor if total is None else total + tensor
avg = (total / len(images_bgr)).clamp(0, 255).byte().cpu().numpy()
del total
if device == "cuda":
t.cuda.empty_cache()
return cv2.cvtColor(avg, cv2.COLOR_RGB2BGR)
else:
# Stable incremental mean (avoids float64 overflow on large stacks)
acc = images_bgr[0].astype(np.float64)
for k, img in enumerate(images_bgr[1:], start=1):
acc += (img.astype(np.float64) - acc) / (k + 1)
gc.collect()
return np.clip(acc, 0, 255).astype(np.uint8)
def _stack_sigma_clip(images_bgr: List[np.ndarray],
sigma_low: float, sigma_high: float,
n_iters: int) -> np.ndarray:
"""
Sigma-clipping stack:
1. Compute mean + std across all frames per pixel per channel
2. Mask pixels outside [mean - sigma_low*std, mean + sigma_high*std]
3. Recompute mean using only unmasked pixels
4. Repeat for n_iters iterations
The standard approach used by DSS, Siril, and other astro stacking software.
"""
info(f" Sigma-clipping stack ({len(images_bgr)} frames, "
f"σ={sigma_low}/{sigma_high}, iters={n_iters})...")
stack = np.stack([img.astype(np.float32) for img in images_bgr], axis=0)
# stack shape: (N, H, W, C)
# Start with all pixels included
mask = np.ones(stack.shape[0], dtype=bool) # per-frame mask (simplified)
# Per-pixel mask: (N, H, W, C)
valid = np.ones_like(stack, dtype=bool)
for iteration in range(n_iters):
# Compute masked mean and std
# Use np.ma for proper masked-array stats
masked = np.ma.array(stack, mask=~valid)
mean = masked.mean(axis=0).data
std = masked.std(axis=0).data
lo = mean - sigma_low * std
hi = mean + sigma_high * std
# Update validity mask
valid = (stack >= lo[np.newaxis]) & (stack <= hi[np.newaxis])
n_clipped = np.sum(~valid)
info(f" Iter {iteration+1}: clipped {n_clipped:,} pixel-samples")
# Final mean of valid pixels
masked_final = np.ma.array(stack, mask=~valid)
result = masked_final.mean(axis=0).filled(fill_value=0)
del stack, valid, masked, masked_final
gc.collect()
return np.clip(result, 0, 255).astype(np.uint8)
# ══════════════════════════════════════════════════════════════════════════════
# ENHANCEMENT
# ══════════════════════════════════════════════════════════════════════════════
def enhance_image(image: np.ndarray,
denoise: bool = True,
sharpen: bool = True,
stretch: bool = False) -> np.ndarray:
"""
Post-process the final stacked image.
- denoise : fastNlMeansDenoisingColored
- sharpen : unsharp mask via filter2D (Laplacian kernel)
- stretch : auto histogram stretch (for faint astronomical targets)
"""
result = image.copy()
if stretch:
info("Applying histogram stretch...")
result = auto_stretch(result)
if denoise:
info("Applying denoising...")
result = cv2.fastNlMeansDenoisingColored(
result, None,
h=5, hColor=5,
templateWindowSize=7,
searchWindowSize=21
)
if sharpen:
info("Applying unsharp mask...")
kernel = np.array([[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]], dtype=np.float32)
result = cv2.filter2D(result, -1, kernel)
return result
# ══════════════════════════════════════════════════════════════════════════════
# STITCHING
# ══════════════════════════════════════════════════════════════════════════════
def stitch_images(images: List[np.ndarray]) -> np.ndarray:
"""Stitch images into a panorama using cv2.Stitcher."""
if len(images) == 1:
return images[0]
banner("STITCHING PANORAMA", char="-")
stitcher = cv2.Stitcher_create(cv2.Stitcher_PANORAMA)
stitcher.setPanoConfidenceThresh(0.5)
stitcher.setWaveCorrection(True)
stitcher.setWaveCorrectKind(cv2.detail.WAVE_CORRECT_HORIZ)
status, pano = stitcher.stitch(images)
if status != cv2.Stitcher_OK:
codes = {
cv2.Stitcher_ERR_NEED_MORE_IMGS:
"Need more images with sufficient overlap",
cv2.Stitcher_ERR_HOMOGRAPHY_EST_FAIL:
"Homography estimation failed — images may not overlap enough",
cv2.Stitcher_ERR_CAMERA_PARAMS_ADJUST_FAIL:
"Camera parameter adjustment failed",
}
raise RuntimeError(f"Stitching failed: {codes.get(status, f'code {status}')}")
ok("Stitching successful")
return pano
# ══════════════════════════════════════════════════════════════════════════════
# SIFT GROUPING
# ══════════════════════════════════════════════════════════════════════════════
def build_sift_matcher():
detector = cv2.SIFT_create(nfeatures=5000, contrastThreshold=0.03, edgeThreshold=15)
FLANN_INDEX_KDTREE = 1
matcher = cv2.FlannBasedMatcher(
dict(algorithm=FLANN_INDEX_KDTREE, trees=5),
dict(checks=50)
)
return detector, matcher
def detect_features(images: List[np.ndarray], detector):
kps, descs = [], []
for i, img in enumerate(images):
kp, des = detector.detectAndCompute(img, None)
kps.append(kp)
descs.append(des)
print(f"\r Feature detection... {i+1}/{len(images)}", end="", flush=True)
print()
return kps, descs
def find_overlap_groups(descs: List[np.ndarray], matcher,
ratio_thresh: float = 0.7,
min_matches: int = 20) -> List[List[int]]:
n = len(descs)
match_matrix = np.zeros((n, n), dtype=int)
for i in range(n):
for j in range(i + 1, n):
if descs[i] is None or descs[j] is None:
continue
raw = matcher.knnMatch(descs[i], descs[j], k=2)
good = []
for pair in raw:
if len(pair) == 2:
m, n2 = pair
if m.distance < ratio_thresh * n2.distance:
good.append(m)
match_matrix[i, j] = match_matrix[j, i] = len(good)
visited = set()
groups = []
for i in range(n):
if i in visited:
continue
group = [i]
visited.add(i)
for j in range(i + 1, n):
if j not in visited and match_matrix[i, j] >= min_matches:
group.append(j)
visited.add(j)
groups.append(group)
return groups
# ══════════════════════════════════════════════════════════════════════════════
# OUTPUT SAVING
# ══════════════════════════════════════════════════════════════════════════════
def save_output(image: np.ndarray, output_path: str):
"""
Save the final image.
- .jpg/.jpeg : JPEG quality 97
- .png : lossless PNG
- .tif/.tiff : 16-bit TIFF (converts uint8 → uint16 by scaling ×257)
Useful for preserving dynamic range for further processing.
"""
ext = Path(output_path).suffix.lower()
if ext in (".tif", ".tiff"):
# Save as 16-bit TIFF for maximum downstream flexibility
img16 = image.astype(np.uint16) * 257 # 0-255 → 0-65535
cv2.imwrite(output_path, img16)
info(f"Saved 16-bit TIFF: {output_path}")
elif ext in (".jpg", ".jpeg"):
cv2.imwrite(output_path, image, [cv2.IMWRITE_JPEG_QUALITY, 97])
elif ext == ".png":
cv2.imwrite(output_path, image, [cv2.IMWRITE_PNG_COMPRESSION, 6])
else:
cv2.imwrite(output_path, image)
# ══════════════════════════════════════════════════════════════════════════════
# FOLDER PIPELINE
# ══════════════════════════════════════════════════════════════════════════════
def run_folder_pipeline(folder_path: str,
output_path: str,
stack_mode: str = "average",
align_method: str = "orb",
stitch: bool = False,
enhance: bool = True,
stretch: bool = False,
stack_threshold: int = 20,
master_dark: Optional[np.ndarray] = None,
hot_pixel_thresh: int = 0,
sigma_low: float = 2.0,
sigma_high: float = 2.0,
sigma_iters: int = 3,
device: str = "cpu",
torch_module=None):
"""
Full pipeline for stacking a folder of images.
1 Auto-detect image format in folder
2 Parallel load all images
3 Optional: dark subtraction + hot pixel removal
4 SIFT feature detection + overlap grouping
5 For each group: align then stack (chosen mode + adaptive batching)
6 Optional: stitch groups into panorama
7 Optional: enhance (denoise, sharpen, stretch)
8 Save + stats
"""
banner("FOLDER STACKING PIPELINE")
info(f"Input : {folder_path}")
info(f"Output : {output_path}")
info(f"Mode : {stack_mode} | Align: {align_method} | Stitch: {stitch}")
# Step 1 & 2 — Detect format + Load
banner("STEP 1 — Detecting Format & Loading Images", char="-")
_, paths = detect_folder_format(folder_path)
images = load_images_parallel(paths)
info(f"Loaded {len(images)} images ({images[0].shape[1]}×{images[0].shape[0]} px each)")
# Step 3 — Calibration
if master_dark is not None:
info("Subtracting master dark frame...")
images = [subtract_dark(img, master_dark) for img in images]
ok("Dark subtraction done")
if hot_pixel_thresh > 0:
info(f"Removing hot pixels (threshold={hot_pixel_thresh})...")
images = [remove_hot_pixels(img, hot_pixel_thresh) for img in images]
ok("Hot pixel removal done")
# Step 4 — SIFT grouping
banner("STEP 2 — Feature Detection & Grouping (SIFT)", char="-")
detector, matcher = build_sift_matcher()
_, descs = detect_features(images, detector)
groups = find_overlap_groups(descs, matcher, min_matches=stack_threshold)
info(f"Found {len(groups)} group(s):")
for i, g in enumerate(groups):
info(f" Group {i+1}: {len(g)} image(s)")
# Step 5 — Align + Stack
banner("STEP 3 — Aligning & Stacking", char="-")
batch_size = estimate_safe_batch(images[0].shape, device, torch_module)
info(f"Adaptive batch size: {batch_size}")
stacked_results = []
for gi, group in enumerate(groups):
group_imgs = [images[i] for i in group]
info(f"\nGroup {gi+1}/{len(groups)} ({len(group_imgs)} images)...")
if align_method != "none" and len(group_imgs) > 1:
base_gray = cv2.cvtColor(group_imgs[0], cv2.COLOR_BGR2GRAY)
aligned = [group_imgs[0]]
for j, img in enumerate(group_imgs[1:], 1):
aligned.append(align_frame(base_gray, img, align_method))
print(f"\r Aligning {j}/{len(group_imgs)-1}...", end="", flush=True)
print()
group_imgs = aligned
# Batch stacking for memory safety
if len(group_imgs) <= batch_size:
stacked = stack_images(group_imgs, stack_mode,
sigma_low, sigma_high, sigma_iters,
device, torch_module)
else:
# Weighted incremental mean across batches
running = group_imgs[0].astype(np.float64)
for b in range(1, len(group_imgs), batch_size):
batch = group_imgs[b:b + batch_size]
br = stack_images(batch, stack_mode,