-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathstacking.c
1669 lines (1501 loc) · 55.4 KB
/
stacking.c
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
/*
* This file is part of Siril, an astronomy image processor.
* Copyright (C) 2005-2011 Francois Meyer (dulle at free.fr)
* Copyright (C) 2012-2019 team free-astro (see more in AUTHORS file)
* Reference site is https://free-astro.org/index.php/Siril
*
* Siril is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Siril is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Siril. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_statistics_ushort.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef MAC_INTEGRATION
#include <gtkosxapplication.h>
#endif
#include "core/siril.h"
#include "core/proto.h"
#include "core/initfile.h"
#include "gui/callbacks.h"
#include "gui/progress_and_log.h"
#include "gui/PSF_list.h"
#include "gui/histogram.h" // update_gfit_histogram_if_needed();
#include "io/sequence.h"
#include "io/single_image.h"
#include "io/ser.h"
#include "registration/registration.h"
#include "algos/PSF.h"
#include "algos/sorting.h"
#include "stacking.h"
#include "sum.h"
#include "opencv/opencv.h"
static struct stacking_args stackparam = { // parameters passed to stacking
NULL, NULL, -1, NULL, -1.0, 0, NULL, NULL, NULL, FALSE, { 0, 0 }, -1, 0,
{ 0, 0 }, NO_REJEC, NO_NORM, { NULL, NULL, NULL}, FALSE, -1
};
#define MAX_FILTERS 5
static struct filtering_tuple stackfilters[MAX_FILTERS];
stack_method stacking_methods[] = {
stack_summing_generic, stack_mean_with_rejection, stack_median, stack_addmax, stack_addmin
};
static gboolean end_stacking(gpointer p);
static int stack_addminmax(struct stacking_args *args, gboolean ismax);
void initialize_stacking_methods() {
GtkComboBoxText *stackcombo, *rejectioncombo;
stackcombo = GTK_COMBO_BOX_TEXT(gtk_builder_get_object(builder, "comboboxstack_methods"));
rejectioncombo = GTK_COMBO_BOX_TEXT(gtk_builder_get_object(builder, "comborejection"));
gtk_combo_box_set_active(GTK_COMBO_BOX(stackcombo), com.stack.method);
gtk_combo_box_set_active(GTK_COMBO_BOX(rejectioncombo), com.stack.rej_method);
}
static void normalize_to16bit(int bitpix, double *mean) {
switch(bitpix) {
case BYTE_IMG:
*mean *= (USHRT_MAX_DOUBLE / UCHAR_MAX_DOUBLE);
break;
default:
case SHORT_IMG:
case USHORT_IMG:
; // do nothing
}
}
/******************************* MEDIAN STACKING ******************************
* Median stacking requires all images to be in memory, so we dont use the
* generic readfits but directly the cfitsio routines, and allocates as many
* pix tables as needed.
* Median stacking does not use registration data, as it's generally used for
* preprocessing master file creation.
* ****************************************************************************/
int stack_median(struct stacking_args *args) {
int nb_frames; /* number of frames actually used */
int bitpix, i, naxis, cur_nb = 0, retval = 0, pool_size = 1;
long npixels_in_block, naxes[3];
double exposure;
struct _data_block *data_pool = NULL;
struct _image_block *blocks = NULL;
fits fit = { 0 };
nb_frames = args->nb_images_to_stack;
naxes[0] = naxes[1] = 0; naxes[2] = 1;
if (nb_frames < 2) {
siril_log_message(_("Select at least two frames for stacking. Aborting.\n"));
return -1;
}
g_assert(nb_frames <= args->seq->number);
set_progress_bar_data(NULL, PROGRESS_RESET);
/* first loop: open all fits files and check they are of same size */
if ((retval = stack_open_all_files(args, &bitpix, &naxis, naxes, &exposure, &fit))) {
goto free_and_close;
}
if (naxes[0] == 0) {
// no image has been loaded
siril_log_message(_("Median stack error: uninitialized sequence\n"));
retval = -2;
goto free_and_close;
}
fprintf(stdout, "image size: %ldx%ld, %ld layers\n", naxes[0], naxes[1], naxes[2]);
/* initialize result image */
if ((retval = stack_create_result_fit(&fit, bitpix, naxis, naxes))) {
goto free_and_close;
}
if (args->norm_to_16 || fit.orig_bitpix != BYTE_IMG) {
fit.bitpix = USHORT_IMG;
if (args->norm_to_16)
fit.orig_bitpix = USHORT_IMG;
}
/* Define some useful constants */
double total = (double)(naxes[2] * naxes[1] + 2); // only used for progress bar
int nb_threads;
#ifdef _OPENMP
nb_threads = com.max_thread;
if (nb_threads > 1 && args->seq->type == SEQ_REGULAR) {
if (fits_is_reentrant()) {
fprintf(stdout, "cfitsio was compiled with multi-thread support,"
" stacking will be executed by several cores\n");
} else {
nb_threads = 1;
fprintf(stdout, "cfitsio was compiled without multi-thread support,"
" stacking will be executed on only one core\n");
siril_log_message(_("Your version of cfitsio does not support multi-threading\n"));
}
}
#else
nb_threads = 1;
#endif
int nb_channels = naxes[2];
if (sequence_is_rgb(args->seq) && nb_channels != 3) {
siril_log_message(_("Processing the sequence as RGB\n"));
nb_channels = 3;
}
long largest_block_height;
int nb_blocks;
/* Compute parallel processing data: the data blocks, later distributed to threads */
if ((retval = stack_compute_parallel_blocks(&blocks, args->max_number_of_rows, nb_channels,
naxes, &largest_block_height, &nb_blocks))) {
goto free_and_close;
}
/* Allocate the buffers.
* We allocate as many as the number of threads, each thread will pick one of the buffers.
* Buffers are allocated to the largest block size calculated above.
*/
#ifdef _OPENMP
pool_size = nb_threads;
g_assert(pool_size > 0);
#endif
npixels_in_block = largest_block_height * naxes[0];
g_assert(npixels_in_block > 0);
fprintf(stdout, "allocating data for %d threads (each %'lu MB)\n", pool_size,
(unsigned long) (nb_frames * npixels_in_block * sizeof(WORD)) / BYTES_IN_A_MB);
data_pool = calloc(pool_size, sizeof(struct _data_block));
for (i = 0; i < pool_size; i++) {
int j;
data_pool[i].pix = calloc(nb_frames, sizeof(WORD *));
data_pool[i].tmp = calloc(nb_frames, npixels_in_block * sizeof(WORD));
data_pool[i].stack = calloc(nb_frames, sizeof(WORD));
if (!data_pool[i].pix || !data_pool[i].tmp || !data_pool[i].stack) {
PRINT_ALLOC_ERR;
fprintf(stderr, "CHANGE MEMORY SETTINGS if stacking takes too much.\n");
retval = -1;
goto free_and_close;
}
for (j=0; j<nb_frames; ++j) {
data_pool[i].pix[j] = data_pool[i].tmp + j * npixels_in_block;
}
}
update_used_memory();
siril_log_message(_("Starting stacking...\n"));
set_progress_bar_data(_("Median stacking in progress..."), PROGRESS_RESET);
#ifdef _OPENMP
#pragma omp parallel for num_threads(nb_threads) private(i) schedule(dynamic) if (nb_threads > 1 && (args->seq->type == SEQ_SER || fits_is_reentrant()))
#endif
for (i = 0; i < nb_blocks; i++)
{
/**** Step 1: get allocated memory for the current thread ****/
struct _image_block *my_block = blocks+i;
struct _data_block *data;
int data_idx = 0, frame;
long x, y;
if (!get_thread_run()) retval = -1;
if (retval) continue;
#ifdef _OPENMP
data_idx = omp_get_thread_num();
#ifdef STACK_DEBUG
fprintf(stdout, "Thread %d takes block %d.\n", data_idx, i);
#endif
#endif
data = &data_pool[data_idx];
/**** Step 2: load image data for the corresponding image block ****/
stack_read_block_data(args, 0, my_block, data, naxes);
/**** Step 3: iterate over the y and x of the image block and stack ****/
for (y = 0; y < my_block->height; y++)
{
/* index of the pixel in the result image
* we read line y, but we need to store it at
* ry - y - 1 to not have the image mirrored. */
int pixel_idx = (naxes[1] - (my_block->start_row + y) - 1) * naxes[0];
/* index of the line in the read data, data->pix[frame] */
int pix_idx = y * naxes[0];
if (retval) break;
// update progress bar
#ifdef _OPENMP
#pragma omp atomic
#endif
cur_nb++;
if (!get_thread_run()) {
retval = -1;
break;
}
if (!(cur_nb % 16)) // every 16 iterations
set_progress_bar_data(NULL, (double)cur_nb/total);
for (x = 0; x < naxes[0]; ++x){
/* copy all images pixel values in the same row array `stack'
* to optimize caching and improve readability */
for (frame = 0; frame < nb_frames; ++frame) {
double tmp;
switch (args->normalize) {
default:
case NO_NORM:
// no normalization (scale[frame] = 1, offset[frame] = 0, mul[frame] = 1)
data->stack[frame] = data->pix[frame][pix_idx+x];
/* it's faster if we don't convert it to double
* to make identity operations */
break;
case ADDITIVE:
// additive (scale[frame] = 1, mul[frame] = 1)
case ADDITIVE_SCALING:
// additive + scale (mul[frame] = 1)
tmp = (double)data->pix[frame][pix_idx+x] * args->coeff.scale[frame];
data->stack[frame] = round_to_WORD(tmp - args->coeff.offset[frame]);
break;
case MULTIPLICATIVE:
// multiplicative (scale[frame] = 1, offset[frame] = 0)
case MULTIPLICATIVE_SCALING:
// multiplicative + scale (offset[frame] = 0)
tmp = (double)data->pix[frame][pix_idx+x] * args->coeff.scale[frame];
data->stack[frame] = round_to_WORD(tmp * args->coeff.mul[frame]);
break;
}
}
double median = quickmedian(data->stack, nb_frames);
if (args->norm_to_16) {
normalize_to16bit(bitpix, &median);
}
fit.pdata[my_block->channel][pixel_idx] = round_to_WORD(median);
pixel_idx++;
}
}
} /* end of loop over parallel stacks */
if (retval)
goto free_and_close;
set_progress_bar_data(_("Finalizing stacking..."), (double)cur_nb/total);
/* copy result to gfit if success */
clearfits(&gfit);
copyfits(&fit, &gfit, CP_FORMAT, 0);
gfit.data = fit.data;
for (i = 0; i < fit.naxes[2]; i++)
gfit.pdata[i] = fit.pdata[i];
free_and_close:
fprintf(stdout, "free and close (%d)\n", retval);
for (i=0; i<nb_frames; ++i) {
seq_close_image(args->seq, args->image_indices[i]);
}
if (data_pool) {
for (i=0; i<pool_size; i++) {
if (data_pool[i].stack) free(data_pool[i].stack);
if (data_pool[i].pix) free(data_pool[i].pix);
if (data_pool[i].tmp) free(data_pool[i].tmp);
}
free(data_pool);
}
if (blocks) free(blocks);
if (args->coeff.offset) free(args->coeff.offset);
if (args->coeff.mul) free(args->coeff.mul);
if (args->coeff.scale) free(args->coeff.scale);
if (retval) {
/* if retval is set, gfit has not been modified */
if (fit.data) free(fit.data);
set_progress_bar_data(_("Median stacking failed. Check the log."), PROGRESS_RESET);
siril_log_message(_("Stacking failed.\n"));
} else {
set_progress_bar_data(_("Median stacking complete."), PROGRESS_DONE);
siril_log_message(_("Median stacking complete. %d have been stacked.\n"), nb_frames);
}
update_used_memory();
return retval;
}
/******************************* ADDMIN AND ADDMAX STACKING ******************************
* These methods are very close to summing stacking instead that the result
* takes only the pixel if it is brighter (max) or dimmer (min) than the
* previous one at the same coordinates.
*/
int stack_addmax(struct stacking_args *args) {
return stack_addminmax(args, TRUE);
}
int stack_addmin(struct stacking_args *args) {
return stack_addminmax(args, FALSE);
}
static int stack_addminmax(struct stacking_args *args, gboolean ismax) {
int x, y, nx, ny, i, ii, j, shiftx, shifty, layer, reglayer;
WORD *final_pixel[3], *from, *to, minmaxim = ismax ? 0 : USHRT_MAX;;
double exposure=0.0;
unsigned int nbdata = 0;
char filename[256];
int retval = 0;
int nb_frames, cur_nb = 0;
fits fit;
char *tmpmsg;
memset(&fit, 0, sizeof(fits));
/* should be pre-computed to display it in the stacking tab */
nb_frames = args->nb_images_to_stack;
reglayer = get_registration_layer(args->seq);
if (nb_frames <= 1) {
siril_log_message(_("No frame selected for stacking (select at least 2). Aborting.\n"));
return -1;
}
final_pixel[0] = NULL;
g_assert(args->seq->nb_layers == 1 || args->seq->nb_layers == 3);
g_assert(nb_frames <= args->seq->number);
for (j=0; j<args->seq->number; ++j){
if (!get_thread_run()) {
retval = -1;
goto free_and_reset_progress_bar;
}
if (!args->filtering_criterion(args->seq, j, args->filtering_parameter)) {
fprintf(stdout, "image %d is excluded from stacking\n", j);
continue;
}
if (!seq_get_image_filename(args->seq, j, filename)) {
retval = -1;
goto free_and_reset_progress_bar;
}
tmpmsg = strdup(_("Processing image "));
tmpmsg = str_append(&tmpmsg, filename);
set_progress_bar_data(tmpmsg, (double)cur_nb/((double)nb_frames+1.));
free(tmpmsg);
cur_nb++; // only used for progress bar
if (seq_read_frame(args->seq, j, &fit)) {
siril_log_message(_("Stacking: could not read frame, aborting\n"));
retval = -3;
goto free_and_reset_progress_bar;
}
g_assert(args->seq->nb_layers == 1 || args->seq->nb_layers == 3);
g_assert(fit.naxes[2] == args->seq->nb_layers);
/* first loaded image: init data structures for stacking */
if (!nbdata) {
nbdata = fit.ry * fit.rx;
final_pixel[0] = malloc(nbdata * fit.naxes[2] * sizeof(WORD));
memset(final_pixel[0], ismax ? 0 : USHRT_MAX, nbdata * fit.naxes[2] * sizeof(WORD));
if (final_pixel[0] == NULL){
printf("Stacking: memory allocation failure\n");
retval = -2;
goto free_and_reset_progress_bar;
}
if(args->seq->nb_layers == 3){
final_pixel[1] = final_pixel[0] + nbdata; // index of green layer in final_pixel[0]
final_pixel[2] = final_pixel[0] + nbdata*2; // index of blue layer in final_pixel[0]
}
} else if (fit.ry * fit.rx != nbdata) {
siril_log_message(_("Stacking: image in sequence doesn't has the same dimensions\n"));
retval = -3;
goto free_and_reset_progress_bar;
}
update_used_memory();
/* load registration data for current image */
if(reglayer != -1 && args->seq->regparam[reglayer]) {
shiftx = round_to_int(args->seq->regparam[reglayer][j].shiftx * args->seq->upscale_at_stacking);
shifty = round_to_int(args->seq->regparam[reglayer][j].shifty * args->seq->upscale_at_stacking);
} else {
shiftx = 0;
shifty = 0;
}
#ifdef STACK_DEBUG
printf("stack image %d with shift x=%d y=%d\n", j, shiftx, shifty);
#endif
/* Summing the exposure */
exposure += fit.exposure;
/* stack current image */
i=0; // index in final_pixel[0]
for (y=0; y < fit.ry; ++y){
for (x=0; x < fit.rx; ++x){
nx = x - shiftx;
ny = y - shifty;
//printf("x=%d y=%d sx=%d sy=%d i=%d ii=%d\n",x,y,shiftx,shifty,i,ii);
if (nx >= 0 && nx < fit.rx && ny >= 0 && ny < fit.ry) {
ii = ny * fit.rx + nx; // index in final_pixel[0] too
//printf("shiftx=%d shifty=%d i=%d ii=%d\n",shiftx,shifty,i,ii);
if (ii > 0 && ii < fit.rx * fit.ry){
for(layer=0; layer<args->seq->nb_layers; ++layer){
WORD current_pixel = fit.pdata[layer][ii];
if ((ismax && current_pixel > final_pixel[layer][i]) || // we take the brighter pixel
(!ismax && current_pixel < final_pixel[layer][i])) // we take the darker pixel
final_pixel[layer][i] = current_pixel;
if ((ismax && final_pixel[layer][i] > minmaxim) ||
(!ismax && final_pixel[layer][i] < minmaxim)){
minmaxim = final_pixel[layer][i];
}
}
}
}
++i;
}
}
}
if (!get_thread_run()) {
retval = -1;
goto free_and_reset_progress_bar;
}
set_progress_bar_data(_("Finalizing stacking..."), (double)nb_frames/((double)nb_frames+1.));
copyfits(&fit, &gfit, CP_ALLOC|CP_FORMAT, 0);
gfit.hi = round_to_WORD(minmaxim);
gfit.bitpix = USHORT_IMG;
if (final_pixel[0]) {
g_assert(args->seq->nb_layers == 1 || args->seq->nb_layers == 3);
for (layer=0; layer<args->seq->nb_layers; ++layer){
from = final_pixel[layer];
to = gfit.pdata[layer];
for (y=0; y < fit.ry * fit.rx; ++y) {
*to++ = *from++;
}
}
}
free_and_reset_progress_bar:
if (final_pixel[0]) free(final_pixel[0]);
if (retval) {
set_progress_bar_data(_("Stacking failed. Check the log."), PROGRESS_RESET);
siril_log_message(_("Stacking failed.\n"));
} else {
set_progress_bar_data(_("Stacking complete."), PROGRESS_DONE);
}
update_used_memory();
return retval;
}
/******************************* REJECTION STACKING ******************************
* The functions below are those managing the rejection, the stacking code is
* after and similar to median but takes into account the registration data and
* does a different operation to keep the final pixel values.
*********************************************************************************/
static int percentile_clipping(WORD pixel, double sig[], double median, uint64_t rej[]) {
double plow = sig[0];
double phigh = sig[1];
if ((median - (double)pixel) / median > plow) {
rej[0]++;
return -1;
}
else if (((double)pixel - median) / median > phigh) {
rej[1]++;
return 1;
}
else return 0;
}
/* Rejection of pixels, following sigma_(high/low) * sigma.
* The function returns 0 if no rejections are required, 1 if it's a high
* rejection and -1 for a low-rejection */
static int sigma_clipping(WORD pixel, double sig[], double sigma, double median, uint64_t rej[]) {
double sigmalow = sig[0];
double sigmahigh = sig[1];
if (median - (double)pixel > sigmalow * sigma) {
rej[0]++;
return -1;
}
else if ((double)pixel - median > sigmahigh * sigma) {
rej[1]++;
return 1;
}
else return 0;
}
static void Winsorize(WORD *pixel, double m0, double m1) {
if (*pixel < m0) *pixel = round_to_WORD(m0);
else if (*pixel > m1) *pixel = round_to_WORD(m1);
}
static int line_clipping(WORD pixel, double sig[], double sigma, int i, double a, double b, uint64_t rej[]) {
double sigmalow = sig[0];
double sigmahigh = sig[1];
if (((a * (double)i + b - (double)pixel) / sigma) > sigmalow) {
rej[0]++;
return -1;
}
else if ((((double)pixel - a * (double)i - b) / sigma) > sigmahigh) {
rej[1]++;
return 1;
}
else return 0;
}
int stack_mean_with_rejection(struct stacking_args *args) {
int nb_frames; /* number of frames actually used */
uint64_t irej[3][2] = {{0,0}, {0,0}, {0,0}};
int bitpix;
int naxis, cur_nb = 0;
long npixels_in_block;
long naxes[3];
int i;
double exposure = 0.0;
int retval = 0;
struct _data_block *data_pool = NULL;
int pool_size = 1;
fits fit = { 0 };
struct _image_block *blocks = NULL;
regdata *layerparam = NULL;
nb_frames = args->nb_images_to_stack;
naxes[0] = naxes[1] = 0; naxes[2] = 1;
if (nb_frames < 2) {
siril_log_message(_("Select at least two frames for stacking. Aborting.\n"));
return -1;
}
g_assert(nb_frames <= args->seq->number);
if (args->reglayer < 0)
fprintf(stderr, "No registration layer passed, ignoring regdata!\n");
else layerparam = args->seq->regparam[args->reglayer];
set_progress_bar_data(NULL, PROGRESS_RESET);
/* first loop: open all fits files and check they are of same size */
if ((retval = stack_open_all_files(args, &bitpix, &naxis, naxes, &exposure, &fit))) {
goto free_and_close;
}
if (naxes[0] == 0) {
// no image has been loaded
siril_log_message(_("Rejection stack error: uninitialized sequence\n"));
retval = -2;
goto free_and_close;
}
fprintf(stdout, "image size: %ldx%ld, %ld layers\n", naxes[0], naxes[1], naxes[2]);
/* initialize result image */
if ((retval = stack_create_result_fit(&fit, bitpix, naxis, naxes))) {
goto free_and_close;
}
if (args->norm_to_16 || fit.orig_bitpix != BYTE_IMG) {
fit.bitpix = USHORT_IMG;
if (args->norm_to_16)
fit.orig_bitpix = USHORT_IMG;
}
/* Define some useful constants */
double total = (double)(naxes[2] * naxes[1] + 2); // only used for progress bar
int nb_threads;
#ifdef _OPENMP
nb_threads = com.max_thread;
if (nb_threads > 1 && args->seq->type == SEQ_REGULAR) {
if (fits_is_reentrant()) {
fprintf(stdout, "cfitsio was compiled with multi-thread support,"
" stacking will be executed by several cores\n");
} else {
nb_threads = 1;
fprintf(stdout, "cfitsio was compiled without multi-thread support,"
" stacking will be executed on only one core\n");
siril_log_message(_("Your version of cfitsio does not support multi-threading\n"));
}
}
#else
nb_threads = 1;
#endif
int nb_channels = naxes[2];
if (sequence_is_rgb(args->seq) && nb_channels != 3) {
siril_log_message(_("Processing the sequence as RGB\n"));
nb_channels = 3;
}
long largest_block_height;
int nb_blocks;
/* Compute parallel processing data: the data blocks, later distributed to threads */
if ((retval = stack_compute_parallel_blocks(&blocks, args->max_number_of_rows, nb_channels,
naxes, &largest_block_height, &nb_blocks))) {
goto free_and_close;
}
/* Allocate the buffers.
* We allocate as many as the number of threads, each thread will pick one of the buffers.
* Buffers are allocated to the largest block size calculated above.
*/
#ifdef _OPENMP
pool_size = nb_threads;
g_assert(pool_size > 0);
#endif
npixels_in_block = largest_block_height * naxes[0];
g_assert(npixels_in_block > 0);
fprintf(stdout, "allocating data for %d threads (each %'lu MB)\n", pool_size,
(unsigned long) (nb_frames * npixels_in_block * sizeof(WORD)) / BYTES_IN_A_MB);
data_pool = calloc(pool_size, sizeof(struct _data_block));
for (i = 0; i < pool_size; i++) {
int j;
data_pool[i].pix = malloc(nb_frames * sizeof(WORD *));
data_pool[i].tmp = malloc(nb_frames * npixels_in_block * sizeof(WORD));
data_pool[i].stack = malloc(nb_frames * sizeof(WORD));
data_pool[i].rejected = calloc(nb_frames, sizeof(int));
if (!data_pool[i].pix || !data_pool[i].tmp || !data_pool[i].stack || !data_pool[i].rejected) {
PRINT_ALLOC_ERR;
fprintf(stderr, "CHANGE MEMORY SETTINGS if stacking takes too much.\n");
retval = -1;
goto free_and_close;
}
if (args->type_of_rejection == WINSORIZED) {
data_pool[i].w_stack = malloc(nb_frames * sizeof(WORD));
if (!data_pool[i].w_stack) {
PRINT_ALLOC_ERR;
fprintf(stderr, "CHANGE MEMORY SETTINGS if stacking takes too much.\n");
retval = -1;
goto free_and_close;
}
}
if (args->type_of_rejection == LINEARFIT) {
data_pool[i].xf = malloc(nb_frames * sizeof(double));
data_pool[i].yf = malloc(nb_frames * sizeof(double));
if (!data_pool[i].xf || !data_pool[i].yf) {
PRINT_ALLOC_ERR;
fprintf(stderr, "CHANGE MEMORY SETTINGS if stacking takes too much.\n");
retval = -1;
goto free_and_close;
}
}
for (j=0; j<nb_frames; ++j) {
data_pool[i].pix[j] = data_pool[i].tmp + j * npixels_in_block;
}
}
update_used_memory();
siril_log_message(_("Starting stacking...\n"));
set_progress_bar_data(_("Rejection stacking in progress..."), PROGRESS_RESET);
#ifdef _OPENMP
#pragma omp parallel for num_threads(nb_threads) private(i) schedule(dynamic) if (nb_threads > 1 && (args->seq->type == SEQ_SER || fits_is_reentrant()))
#endif
for (i = 0; i < nb_blocks; i++)
{
/**** Step 1: get allocated memory for the current thread ****/
struct _image_block *my_block = blocks+i;
struct _data_block *data;
int data_idx = 0;
long x, y;
if (!get_thread_run()) retval = -1;
if (retval) continue;
#ifdef _OPENMP
data_idx = omp_get_thread_num();
#ifdef STACK_DEBUG
struct timeval thread_start;
gettimeofday(&thread_start, NULL);
fprintf(stdout, "Thread %d takes block %d.\n", data_idx, i);
#endif
#endif
//fprintf(stdout, "thread %d working on block %d gets data\n", data_idx, i);
data = &data_pool[data_idx];
/**** Step 2: load image data for the corresponding image block ****/
stack_read_block_data(args, 1, my_block, data, naxes);
#if defined _OPENMP && defined STACK_DEBUG
{
struct timeval thread_mid;
int min, sec;
gettimeofday(&thread_mid, NULL);
get_min_sec_from_timevals(thread_start, thread_mid, &min, &sec);
fprintf(stdout, "Thread %d loaded block %d after %d min %02d s.\n\n",
data_idx, i, min, sec);
}
#endif
/**** Step 3: iterate over the y and x of the image block and stack ****/
for (y = 0; y < my_block->height; y++)
{
/* index of the pixel in the result image
* we read line y, but we need to store it at
* ry - y - 1 to not have the image mirrored. */
int pdata_idx = (naxes[1] - (my_block->start_row + y) - 1) * naxes[0];
/* index of the line in the read data, data->pix[frame] */
int pix_idx = y * naxes[0];
if (retval) break;
// update progress bar
#ifdef _OPENMP
#pragma omp atomic
#endif
cur_nb++;
if (!get_thread_run()) {
retval = -1;
break;
}
if (!(cur_nb % 16)) // every 16 iterations
set_progress_bar_data(NULL, (double)cur_nb/total);
double sigma = -1.0;
uint64_t crej[2] = {0, 0};
for (x = 0; x < naxes[0]; ++x){
int frame;
/* copy all images pixel values in the same row array `stack'
* to optimize caching and improve readability */
for (frame = 0; frame < nb_frames; ++frame) {
int shiftx = 0;
if (layerparam) {
shiftx = round_to_int(
layerparam[args->image_indices[frame]].shiftx *
args->seq->upscale_at_stacking);
}
if (shiftx && (x - shiftx >= naxes[0] || x - shiftx < 0)) {
/* outside bounds, images are black. We could
* also set the background value instead, if available */
data->stack[frame] = 0;
}
else {
WORD pixel = data->pix[frame][pix_idx+x-shiftx];
double tmp;
switch (args->normalize) {
default:
case NO_NORM:
// no normalization (scale[frame] = 1, offset[frame] = 0, mul[frame] = 1)
data->stack[frame] = pixel;
/* it's faster if we don't convert it to double
* to make identity operations */
break;
case ADDITIVE:
// additive (scale[frame] = 1, mul[frame] = 1)
case ADDITIVE_SCALING:
// additive + scale (mul[frame] = 1)
tmp = (double)pixel * args->coeff.scale[frame];
data->stack[frame] = round_to_WORD(tmp - args->coeff.offset[frame]);
break;
case MULTIPLICATIVE:
// multiplicative (scale[frame] = 1, offset[frame] = 0)
case MULTIPLICATIVE_SCALING:
// multiplicative + scale (offset[frame] = 0)
tmp = (double)pixel * args->coeff.scale[frame];
data->stack[frame] = round_to_WORD(tmp * args->coeff.mul[frame]);
break;
}
}
}
int N = nb_frames;// N is the number of pixels kept from the current stack
double median;
int pixel, output, changed, n, r = 0;
switch (args->type_of_rejection) {
case PERCENTILE:
median = quickmedian (data->stack, N);
for (frame = 0; frame < N; frame++) {
data->rejected[frame] = percentile_clipping(data->stack[frame], args->sig, median, crej);
}
for (pixel = 0, output = 0; pixel < N; pixel++) {
if (!data->rejected[pixel]) {
// copy only if there was a rejection
if (pixel != output)
data->stack[output] = data->stack[pixel];
output++;
}
}
N = output;
break;
case SIGMA:
do {
sigma = gsl_stats_ushort_sd(data->stack, 1, N);
median = quickmedian (data->stack, N);
for (frame = 0; frame < N; frame++) {
data->rejected[frame] = sigma_clipping(data->stack[frame], args->sig, sigma, median, crej);
if (data->rejected[frame])
r++;
if (N - r <= 4) break;
}
for (pixel = 0, output = 0; pixel < N; pixel++) {
if (!data->rejected[pixel]) {
// copy only if there was a rejection
if (pixel != output)
data->stack[output] = data->stack[pixel];
output++;
}
}
changed = N != output;
N = output;
} while (changed && N > 3);
break;
case SIGMEDIAN:
do {
sigma = gsl_stats_ushort_sd(data->stack, 1, N);
median = quickmedian (data->stack, N);
n = 0;
for (frame = 0; frame < N; frame++) {
if (sigma_clipping(data->stack[frame], args->sig, sigma, median, crej)) {
data->stack[frame] = median;
n++;
}
}
} while (n > 0 && N > 3);
break;
case WINSORIZED:
do {
double sigma0;
sigma = gsl_stats_ushort_sd(data->stack, 1, N);
median = quickmedian (data->stack, N);
memcpy(data->w_stack, data->stack, N * sizeof(WORD));
do {
int jj;
double m0 = median - 1.5 * sigma;
double m1 = median + 1.5 * sigma;
for (jj = 0; jj < N; jj++)
Winsorize(data->w_stack+jj, m0, m1);
median = quickmedian (data->w_stack, N);
sigma0 = sigma;
sigma = 1.134 * gsl_stats_ushort_sd(data->w_stack, 1, N);
} while ((fabs(sigma - sigma0) / sigma0) > 0.0005);
for (frame = 0; frame < N; frame++) {
data->rejected[frame] = sigma_clipping(
data->stack[frame], args->sig, sigma,
median, crej);
if (data->rejected[frame] != 0)
r++;
if (N - r <= 4) break;
}
for (pixel = 0, output = 0; pixel < N; pixel++) {
if (!data->rejected[pixel]) {
// copy only if there was a rejection
if (pixel != output)
data->stack[output] = data->stack[pixel];
output++;
}
}
changed = N != output;
N = output;
} while (changed && N > 3);
break;
case LINEARFIT:
do {
double a, b, cov00, cov01, cov11, sumsq;
quicksort_s(data->stack, N);
for (frame = 0; frame < N; frame++) {
data->xf[frame] = (double)frame;
data->yf[frame] = (double)data->stack[frame];
}
gsl_fit_linear(data->xf, 1, data->yf, 1, N, &b, &a, &cov00, &cov01, &cov11, &sumsq);
sigma = 0.0;
for (frame = 0; frame < N; frame++)
sigma += (fabs((double)data->stack[frame] - (a*(double)frame + b)));
sigma /= (double)N;
for (frame = 0; frame < N; frame++) {
data->rejected[frame] =
line_clipping(data->stack[frame], args->sig, sigma, frame, a, b, crej);
if (data->rejected[frame] != 0)
r++;
if (N - r <= 4) break;
}
for (pixel = 0, output = 0; pixel < N; pixel++) {
if (!data->rejected[pixel]) {
// copy only if there was a rejection
if (pixel != output)
data->stack[output] = data->stack[pixel];
output++;
}
}
changed = N != output;
N = output;
} while (changed && N > 3);
break;
default:
case NO_REJEC:
; // Nothing to do, no rejection
}
int64_t sum = 0L;
double mean;
for (frame = 0; frame < N; ++frame) {
sum += data->stack[frame];
}
mean = sum / (double)N;
if (args->norm_to_16) {
normalize_to16bit(bitpix, &mean);
}
fit.pdata[my_block->channel][pdata_idx++] = round_to_WORD(mean);
} // end of for x
#ifdef _OPENMP
#pragma omp critical
#endif
{
irej[my_block->channel][0] += crej[0];
irej[my_block->channel][1] += crej[1];
}
} // end of for y
#if defined _OPENMP && defined STACK_DEBUG
{
struct timeval thread_end;
int min, sec;
gettimeofday(&thread_end, NULL);
get_min_sec_from_timevals(thread_start, thread_end, &min, &sec);
fprintf(stdout, "Thread %d finishes block %d after %d min %02d s.\n",
data_idx, i, min, sec);
}
#endif
} /* end of loop over parallel stacks */
if (retval)
goto free_and_close;
set_progress_bar_data(_("Finalizing stacking..."), (double)cur_nb/total);
double nb_tot = (double) naxes[0] * naxes[1] * nb_frames;
long channel;
for (channel = 0; channel < naxes[2]; channel++) {
siril_log_message(_("Pixel rejection in channel #%d: %.3lf%% - %.3lf%%\n"),
channel, irej[channel][0] / (nb_tot) * 100.0,
irej[channel][1] / (nb_tot) * 100.0);
}
/* copy result to gfit if success */
clearfits(&gfit);
copyfits(&fit, &gfit, CP_FORMAT, 0);
gfit.exposure = exposure;
gfit.data = fit.data;
for (i = 0; i < fit.naxes[2]; i++)
gfit.pdata[i] = fit.pdata[i];
free_and_close:
fprintf(stdout, "free and close (%d)\n", retval);
for (i = 0; i < nb_frames; ++i) {