-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZ_Decon.js
2427 lines (2098 loc) · 73.3 KB
/
EZ_Decon.js
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
// Copyright (C) 2020-2023 S Dimant (aka darkarchon#4313)
// File name: EZ_Decon.js
/*
* ------------------- Version 2020-06-03 --------------------
* tested on PixInsight 1.8.8-5 Ripley
*
* This script allows easy deconvolution on images.
* It can create PSF, StarMasks for star replacement and apply the deconvolution process
* Hands-free flow is
* - create appropriate star mask
* - create appropriate psf
* - apply deconvolution with stf and default settings
* - apply pixelmath several times with a mask to replace the stars in the image
*
* Copyright information
*
* Made by S Dimant (aka darkarchon#4313)
* Original Easy Decon idea by OkeWoke#6745
*
* Create PSF Image code snippets, ellipsoid creation as well as drawing adapted from the GAME script by Hartmut v. Bornemann
* Acknowledgements for the ellispoid creation also go to Adam Block
*/
// #region "IncludesAndDefines"
#feature-id EZ Processing Suite > EZ Decon
var NAME = 'EZ Decon';
var VERSION = '0.13HF6';
var AUTHOR = "S. Dimant";
#include "EZ_Common.js"
#define PSF_starIndex 0
#define PSF_function 1
#define PSF_circular 2
#define PSF_status 3
#define PSF_B 4
#define PSF_A 5
#define PSF_cx 6
#define PSF_cy 7
#define PSF_sx 8
#define PSF_sy 9
#define PSF_theta 10
#define PSF_beta 11
#define PSF_residual 12
#define PSF_mad 12
#define PSF_x0 13
#define PSF_y0 14
#define PSF_x1 15
#define PSF_y1 16
// VARIABLE NAMING SCHEME
// - Generally, if applicable, variables end with the type of the variable (i.e. View, Window, etc.)
// - Global declared variables use UpperCamelCase
// - local used variables are lowerCamelCase
// - avoid using var inside functions, prefer let
// #endregion "IncludesAndDefines"
// #region "Main"
function saveSettings() {
Settings.write("EZDecon.DownsampleStarNet", 0, CurrentProcessingInfo.downsampleStarnet);
Settings.write("EZDecon.PSFMaxStars", 1, CurrentProcessingInfo.psfMaxStars);
Settings.write("EZDecon.DeconIterations", 1, CurrentProcessingInfo.deconIterations);
Settings.write("EZDecon.PixelMathIterations", 1, CurrentProcessingInfo.pixelMathIterations);
Settings.write("EZDecon.StarSensitivity", 10, CurrentProcessingInfo.starSensitivity);
Settings.write("EZDecon.BackgroundReplacement", 0, CurrentProcessingInfo.backgroundReplacement);
Settings.write("EZDecon.BackgroundBlending", 10, CurrentProcessingInfo.backgroundBlending);
Settings.write("EZDecon.WaveletStr1", 10, CurrentProcessingInfo.waveletStr[0]);
Settings.write("EZDecon.WaveletStr2", 10, CurrentProcessingInfo.waveletStr[1]);
Settings.write("EZDecon.WaveletStr3", 10, CurrentProcessingInfo.waveletStr[2]);
Settings.write("EZDecon.WaveletStr4", 10, CurrentProcessingInfo.waveletStr[3]);
Settings.write("EZDecon.WaveletStr5", 10, CurrentProcessingInfo.waveletStr[4]);
Settings.write("EZDecon.WaveletThr1", 10, CurrentProcessingInfo.waveletThr[0]);
Settings.write("EZDecon.WaveletThr2", 10, CurrentProcessingInfo.waveletThr[1]);
Settings.write("EZDecon.WaveletThr3", 10, CurrentProcessingInfo.waveletThr[2]);
Settings.write("EZDecon.WaveletThr4", 10, CurrentProcessingInfo.waveletThr[3]);
Settings.write("EZDecon.WaveletThr5", 10, CurrentProcessingInfo.waveletThr[4]);
}
function generateProcessingInfo() {
let deconInfo = new DeconInfo();
deconInfo.mainViewId = null;
deconInfo.workingViewId = null;
deconInfo.originalViewId = null;
deconInfo.starMaskId = null;
deconInfo.backgroundMaskId = null;
deconInfo.backgroundReplacement = readFromSettingsOrDefault("EZDecon.BackgroundReplacement", 0, false);
deconInfo.backgroundBlending = readFromSettingsOrDefault("EZDecon.BackgroundBlending", 10, 1);
deconInfo.starSensitivity = readFromSettingsOrDefault("EZDecon.StarSensitivity", 10, 1.0);
deconInfo.downsampleStarnet = readFromSettingsOrDefault("EZDecon.DownsampleStarNet", 0, false);
deconInfo.psfViewId = null;
deconInfo.psfMaxStars = readFromSettingsOrDefault("EZDecon.PSFMaxStars", 1, 50);
deconInfo.waveletStr = [readFromSettingsOrDefault("EZDecon.WaveletStr1", 10, 1),
readFromSettingsOrDefault("EZDecon.WaveletStr2", 10, 0.9),
readFromSettingsOrDefault("EZDecon.WaveletStr3", 10, 0.8),
readFromSettingsOrDefault("EZDecon.WaveletStr4", 10, 0.7),
readFromSettingsOrDefault("EZDecon.WaveletStr5", 10, 0.7)];
deconInfo.waveletThr = [readFromSettingsOrDefault("EZDecon.WaveletThr1", 10, 10),
readFromSettingsOrDefault("EZDecon.WaveletThr2", 10, 8),
readFromSettingsOrDefault("EZDecon.WaveletThr3", 10, 6),
readFromSettingsOrDefault("EZDecon.WaveletThr4", 10, 4),
readFromSettingsOrDefault("EZDecon.WaveletThr5", 10, 2)];
deconInfo.deconIterations = readFromSettingsOrDefault("EZDecon.DeconIterations", 1, 25);
deconInfo.pixelMathIterations = readFromSettingsOrDefault("EZDecon.PixelMathIterations", 1, 5);
deconInfo.createProcesesOnly = false;
deconInfo.currentDeconRun = 0;
return deconInfo;
}
function execute(window, bringToFront = true, runOnMain = false) {
startProcessing();
writeMessageStart("Executing on " + window.currentView.id);
let mainView = window.mainView;
CurrentProcessingInfo.originalViewId = cloneView(mainView, "_ez_" + mainView.id + "_org").id;
View.viewById(CurrentProcessingInfo.originalViewId).window.iconize();
if (bringToFront) {
mainView.window.bringToFront();
}
let workingView = window.mainView;
let runningOnPreview = workingView.id != CurrentProcessingInfo.workingViewId;
if (runningOnPreview && !runOnMain) {
workingView = cloneView(View.viewById(CurrentProcessingInfo.workingViewId), "_ez_temp_working_" + CurrentProcessingInfo.mainViewId);
}
writeMessageBlock("Running Deconvolution");
let orgVisible = workingView.window.visible;
if (orgVisible) {
workingView.window.hide();
}
workingView.window.removeMask();
doDecon(workingView);
writeMessageBlock("Running PixelMath to replace stars");
doPixelMathMask(workingView,
CurrentProcessingInfo.originalViewId,
CurrentProcessingInfo.starMaskId, CurrentProcessingInfo.pixelMathIterations,
View.viewById(CurrentProcessingInfo.workingViewId).isPreview && !runOnMain);
if(CurrentProcessingInfo.backgroundReplacement) {
writeMessageBlock("Running PixelMath to blend background");
doPixelMath(View.viewById(CurrentProcessingInfo.backgroundMaskId), "$T*{0}".format(CurrentProcessingInfo.backgroundBlending));
doPixelMathMask(workingView, CurrentProcessingInfo.originalViewId,
CurrentProcessingInfo.backgroundMaskId, 1,
View.viewById(CurrentProcessingInfo.workingViewId).isPreview && !runOnMain);
View.viewById(CurrentProcessingInfo.backgroundMaskId).window.undo();
}
if (orgVisible) {
workingView.window.show();
}
if (runningOnPreview && !runOnMain) {
View.viewById(CurrentProcessingInfo.originalViewId).window.forceClose();
}
writeMessageEnd("Done.");
stopProcessing();
return workingView;
}
function onExit() { }
function onInit() { }
// #endregion "Main"
// #region "Do"
function doPixelMathMask(view, expression, maskId, iterations, isPreview) {
let starMask = View.viewById(maskId);
let originalViewId = CurrentProcessingInfo.originalViewId;
let originalView = View.viewById(originalViewId);
if (isPreview) {
let previewRect = View.viewById(CurrentProcessingInfo.mainViewId).window.previewRect(View.viewById(CurrentProcessingInfo.workingViewId));
let starMaskPart = null;
for (let i = 0; i < starMask.window.previews.length; i++) {
console.writeln("Checking preview " + i);
let tempRect = starMask.window.previewRect(starMask.window.previews[i]);
if (tempRect.x0 == previewRect.x0 && tempRect.x1 == previewRect.x1 && tempRect.y0 == previewRect.y0 && tempRect.y1 == previewRect.y1) {
starMaskPart = starMask.window.previews[i];
break;
}
}
if (starMaskPart == null) starMaskPart = starMask.window.createPreview(previewRect);
starMask = cloneView(starMaskPart, "_ez_temp_working_" + starMask.id);
let originalViewPart = originalView.window.createPreview(View.viewById(CurrentProcessingInfo.mainViewId).window.previewRect(View.viewById(CurrentProcessingInfo.workingViewId)));
let orgId = originalView.id;
originalView = cloneView(originalViewPart, "_ez_temp_working_" + orgId);
expression = expression.replace(originalViewId, originalView.id);
}
view.window.mask = starMask.window;
view.window.maskVisible = false;
view.window.maskInverted = false;
var pixelMath = new PixelMath;
pixelMath.expression = expression;
pixelMath.expression1 = "";
pixelMath.expression2 = "";
pixelMath.expression3 = "";
pixelMath.useSingleExpression = true;
pixelMath.symbols = "";
pixelMath.generateOutput = true;
pixelMath.singleThreaded = false;
pixelMath.use64BitWorkingImage = false;
pixelMath.rescale = false;
pixelMath.rescaleLower = 0;
pixelMath.rescaleUpper = 1;
pixelMath.truncate = true;
pixelMath.truncateLower = 0;
pixelMath.truncateUpper = 1;
pixelMath.createNewImage = false;
pixelMath.showNewImage = true;
pixelMath.newImageId = "";
pixelMath.newImageWidth = 0;
pixelMath.newImageHeight = 0;
pixelMath.newImageAlpha = false;
pixelMath.newImageColorSpace = PixelMath.prototype.SameAsTarget;
pixelMath.newImageSampleFormat = PixelMath.prototype.SameAsTarget;
if (CurrentProcessingInfo.createProcesesOnly) {
pixelMath.launch();
} else {
for (let i = 0; i < iterations; i++) {
pixelMath.executeOn(view);
}
}
if (isPreview) {
starMask.window.forceClose();
originalView.window.forceClose();
}
view.window.removeMask();
}
function doBinarize(view) {
let binarize = new Binarize;
binarize.thresholdRK = 0.1;
binarize.thresholdG = 0.1;
binarize.thresholdB = 0.1;
binarize.isGlobal = true;
binarize.executeOn(view);
}
function doDilate(view) {
let dilute = new MorphologicalTransformation;
dilute.operator = MorphologicalTransformation.prototype.Dilation;
dilute.interlacingDistance = 1;
dilute.lowThreshold = 0.000000;
dilute.highThreshold = 0.000000;
dilute.numberOfIterations = 1;
dilute.amount = 1.00;
dilute.selectionPoint = 0.50;
dilute.structureName = "5x5 Circular Structure";
dilute.structureSize = 5;
dilute.structureWayTable = [ // mask
[[
0x00, 0x01, 0x01, 0x01, 0x00,
0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01,
0x00, 0x01, 0x01, 0x01, 0x00
]]
];
dilute.executeOn(view);
}
function doConvolve(view) {
let convolve = new Convolution;
convolve.mode = Convolution.prototype.Parametric;
convolve.sigma = 4.50;
convolve.shape = 2.00;
convolve.aspectRatio = 1.00;
convolve.rotationAngle = 0.00;
convolve.filterSource = "";
convolve.rescaleHighPass = false;
convolve.viewId = "";
convolve.executeOn(view);
}
function doBoost(view) {
let boostCurves = new CurvesTransformation;
boostCurves.K = [ // x, y
[0.00000, 0.00000],
[0.44082, 0.58367],
[1.00000, 1.00000]
];
boostCurves.St = CurvesTransformation.prototype.AkimaSubsplines;
boostCurves.executeOn(view);
}
function doDecon(view) {
var decon = new Deconvolution;
decon.algorithm = Deconvolution.prototype.RichardsonLucy;
decon.numberOfIterations = CurrentProcessingInfo.deconIterations;
decon.deringing = false;
decon.toLuminance = true;
decon.psfMode = Deconvolution.prototype.External;
decon.psfViewId = CurrentProcessingInfo.psfViewId;
decon.psfFFTSizeLimit = 15;
decon.useRegularization = true;
decon.waveletLayers = [ // noiseThreshold, noiseReduction
[CurrentProcessingInfo.waveletThr[0], CurrentProcessingInfo.waveletStr[0]],
[CurrentProcessingInfo.waveletThr[1], CurrentProcessingInfo.waveletStr[1]],
[CurrentProcessingInfo.waveletThr[2], CurrentProcessingInfo.waveletStr[2]],
[CurrentProcessingInfo.waveletThr[3], CurrentProcessingInfo.waveletStr[3]],
[CurrentProcessingInfo.waveletThr[4], CurrentProcessingInfo.waveletStr[4]]
];
decon.noiseModel = Deconvolution.prototype.Gaussian;
decon.numberOfWaveletLayers = 5;
decon.scalingFunction = Deconvolution.prototype.B3Spline5x5;
decon.iterations = [ // count
[CurrentProcessingInfo.deconIterations],
[CurrentProcessingInfo.deconIterations],
[CurrentProcessingInfo.deconIterations]
];
if (CurrentProcessingInfo.createProcesesOnly) {
decon.launch();
} else {
decon.executeOn(view);
}
}
//#endregion "Do"
// #region "Create"
function createRawStarMask(deconInfo) {
startProcessing();
writeMessageStart("Creating raw star mask based on " + deconInfo.mainViewId);
// clone main image
let mainImageView = View.viewById(deconInfo.mainViewId).window.mainView;
let lightness = extractLightness(mainImageView);
// apply stf
doSTF(lightness);
// apply ht
doHistogramTransformation(lightness);
// check downsampling
// downsample if necessary
if (deconInfo.downsampleStarnet) {
writeMessageBlock("Downsampling " + lightness.id);
var downSample = new IntegerResample;
downSample.zoomFactor = -2;
downSample.downsamplingMode = IntegerResample.prototype.Average;
downSample.xResolution = 72.000;
downSample.yResolution = 72.000;
downSample.metric = false;
downSample.forceResolution = false;
downSample.noGUIMessages = false;
downSample.executeOn(lightness);
}
// run starnet
let starNet = getStarNet();
starNet.mask = true;
starNet.stride = 0;
writeMessageBlock("Running StarNet++ on " + lightness.id + " - hold tight, this might take a while.");
starNet.executeOn(lightness);
let oldCloned = lightness;
lightness = ImageWindow.activeWindow.currentView;
lightness.id = oldCloned.id;
oldCloned.window.forceClose();
// upscale if necessary
if (deconInfo.downsampleStarnet) {
writeMessageBlock("Upscaling " + lightness.id);
var upSample = new Resample;
upSample.xSize = mainImageView.image.width / lightness.image.width;
upSample.ySize = mainImageView.image.height / lightness.image.height;
upSample.mode = Resample.prototype.RelativeDimensions;
upSample.absoluteMode = Resample.prototype.ForceWidthAndHeight;
upSample.xResolution = 72.000;
upSample.yResolution = 72.000;
upSample.metric = false;
upSample.forceResolution = false;
upSample.interpolation = Resample.prototype.Auto;
upSample.clampingThreshold = 0.30;
upSample.smoothness = 1.50;
upSample.noGUIMessages = false;
upSample.executeOn(lightness);
}
// reset stf
doResetSTF(lightness);
let newClonedView = cloneView(lightness, "_ez_Decon_" + View.viewById(deconInfo.mainViewId).window.mainView.id + "_StarMask");
lightness.window.forceClose();
deconInfo.starMaskId = newClonedView.id;
writeMessageEnd("Raw Mask Creation done", false, true);
stopProcessing();
}
function createPSF(deconInfo) {
startProcessing();
writeMessageStart("Generating PSF image");
let usedStars = [];
var sensitivity = CurrentProcessingInfo.starSensitivity;
var Max = 0.8;
var Min = 0.02;
var minMad = 1;
var maxMad = 0;
let selectedStars = [];
//
// collect all fitted stars
//
var functions = [];
functions.push(DynamicPSF.prototype.Function_Moffat);
functions.push(DynamicPSF.prototype.Function_Moffat10);
functions.push(DynamicPSF.prototype.Function_Moffat8);
functions.push(DynamicPSF.prototype.Function_Moffat6);
functions.push(DynamicPSF.prototype.Function_Moffat4);
functions.push(DynamicPSF.prototype.Function_Moffat25);
functions.push(DynamicPSF.prototype.Function_Moffat15);
var functionList = [];
for (var i in functions) {
var functionIndex = functions[i];
var functionName = "";
if (functionIndex == DynamicPSF.prototype.Function_Moffat) functionName = "Moffat";
if (functionIndex == DynamicPSF.prototype.Function_Moffat10) functionName = "Moffat10";
if (functionIndex == DynamicPSF.prototype.Function_Moffat8) functionName = "Moffat8";
if (functionIndex == DynamicPSF.prototype.Function_Moffat6) functionName = "Moffat6";
if (functionIndex == DynamicPSF.prototype.Function_Moffat4) functionName = "Moffat4";
if (functionIndex == DynamicPSF.prototype.Function_Moffat25) functionName = "Moffat25";
if (functionIndex == DynamicPSF.prototype.Function_Moffat15) functionName = "Moffat15";
functionList.push({ functionName: functionName, count: 0 });
}
var A = [];
var B = [];
var SX = [];
var SY = [];
var THETA = [];
var BETA = [];
let mainImageView = View.viewById(deconInfo.mainViewId).window.mainView;
let originalIsColor = mainImageView.image.isColor;
if (originalIsColor) {
writeMessageBlock("Original image is color, extracting luminance", true, false);
var lumExtraction = new ChannelExtraction;
lumExtraction.colorSpace = ChannelExtraction.prototype.CIELab;
lumExtraction.channels = [
[true, ""],
[false, ""],
[false, ""]
];
lumExtraction.sampleFormat = ChannelExtraction.prototype.SameAsSource;
lumExtraction.executeOn(mainImageView);
mainImageView = ImageWindow.activeWindow.currentView;
}
processEvents();
selectedStars = getStars(mainImageView, sensitivity);
if (originalIsColor) mainImageView.window.forceClose();
writeMessageBlock("Computing PSF", true, false);
processEvents();
// get min max MAD
for (let i = 0;i<selectedStars.length;i++) {
var sp = selectedStars[i];
if (sp.mad > maxMad) maxMad = sp.mad;
if (sp.mad < minMad) minMad = sp.mad;
}
for (var i = 0; i < selectedStars.length; i++) {
var sp = selectedStars[i];
var index = functions.indexOf(sp.psf_function);
if (index < 0) continue;
if (sp.a < Min || sp.a > Max) continue;
A.push(sp.a);
B.push(sp.b);
SX.push(sp.sx);
SY.push(sp.sy);
THETA.push(sp.theta);
BETA.push(sp.beta);
usedStars.push(sp);
functionList[index].count += 1;
if (A.length == CurrentProcessingInfo.psfMaxStars) break;
}
if (A.length > 0) {
var b = average(B);
var a = average(A);
var sx = average(SX);
var sy = average(SY);
var theta = average(THETA);
var beta = average(BETA);
let psfImage = createStarImage(b, a, sx, sy, theta, beta);
var psfName = "_ez_PSF_" + View.viewById(deconInfo.mainViewId).window.mainView.id;
var iw = new ImageWindow(psfImage.width, psfImage.height,
1, 32, true, false, psfName);
iw.mainView.beginProcess(UndoFlag_NoSwapFile);
iw.mainView.image.assign(psfImage);
iw.mainView.endProcess();
iw.show();
iw.visible = true;
CurrentProcessingInfo.psfViewId = iw.mainView.id;
}
if (CurrentProcessingInfo.psfViewId == null) {
writeWarningBlock("Could not compute PSF! Adjust sensitivity and try again.");
}
writeMessageEnd("PSF Creation done");
stopProcessing();
}
function createProcessedStarMask(deconInfo) {
startProcessing();
writeMessageStart("Creating processed star mask based on " + deconInfo.mainViewId);
createRawStarMask(deconInfo);
applyStf(deconInfo.starMaskId);
applyBinarize(deconInfo.starMaskId);
if (!deconInfo.downsampleStarnet) {
applyDilate(deconInfo.starMaskId);
}
applyConvolute(deconInfo.starMaskId);
applyDilate(deconInfo.starMaskId);
writeMessageEnd("Mask creation done", false, true);
stopProcessing();
}
// #endregion "Create"
// #region "PSF"
function createStarImage(b, a, sx, sy, theta, beta) {
//
// implements Moffat function
//
var box = boxSize(b, a, beta, sx, sy, theta);
var c = Math.floor(box / 2);
var cx = c + 1;
var cy = c + 1;
var img = new Image(box, box);
var max = moffat(cx, cy, b, a, cx, cy, beta, sx, sy);
var min = moffat(0, 0, b, a, cx, cy, beta, sx, sy);
var f = 1 / (max - min);
for (var y = 0; y < img.height; y++) {
for (var x = 0; x < img.width; x++) {
var t = new transformXY(- c + x, - c + y, theta);
var m = moffat(t.x + cx, t.y + cy, b, a, cx, cy, beta, sx, sy);
m = (m - min) * f;
img.setSample(m, x, img.height - y - 1);
}
}
return img;
}
function boxSize(b, a, beta, sx, sy, theta) {
var max = moffat(0, 0, b, a, 0, 0, beta, sx, sy);
var x = 0;
var y = 0;
var v = 2;
while (true) {
var t = new transformXY(x, 0, theta);
var mx = moffat(x, 0, b, a, 0, 0, beta, sx, sy);
mx /= max;
if (v - mx < 0.01) break;
v = mx;
x += 1;
if (x > 32) break;
}
v = 2;
while (true) {
var t = new transformXY(x, y, theta);
var my = moffat(0, y, b, a, 0, 0, beta, sx, sy);
my /= max;
if (v - my < 0.01) break;
v = my;
y += 1;
if (y > 32) break;
}
var box = Math.max(x - 1, y - 1);
box *= 2;
box += 1;
return box;
}
function transformXY(x, y, theta) {
this.x = x * Math.cos(theta * Math.RAD) + y * Math.sin(theta * Math.RAD);
this.y = -x * Math.sin(theta * Math.RAD) + y * Math.cos(theta * Math.RAD);
}
function moffat(x, y, B, A, cx, cy, beta, sigmax, sigmay) {
var sqx = sigmax * sigmax;
var sqy = sigmay * sigmay;
var dx2 = Math.pow(x - cx, 2);
var dy2 = Math.pow(y - cy, 2);
return B + A / Math.pow((1 + dx2 / sqx + dy2 / sqy), beta);
}
function getStars(view, sensitivity) {
writeMessageStart("Getting stars for " + view.id);
processEvents();
var std = new StarDetector();
std.sensitivity = Math.pow(10.0, sensitivity);
var stars = std.stars(view.image);
if (stars == null) return [];
if (stars.length == 0) return [];
var barycenters = new Array;
var s = stars[0];
var keys = Object.keys(s);
for (var i = 0; i != stars.length; ++i) {
barycenters.push({
position: stars[i].pos,
radius: Math.max(3, Math.ceil(Math.sqrt(stars[i].size)))
});
}
processEvents();
var dynamicPSF = new DynamicPSF;
stars = [];
for (var i = 0; i != barycenters.length; ++i) {
stars.push(new Array(
0, 0, DynamicPSF.prototype.Star_DetectedOk,
barycenters[i].position.x - barycenters[i].radius,
barycenters[i].position.y - barycenters[i].radius,
barycenters[i].position.x + barycenters[i].radius,
barycenters[i].position.y + barycenters[i].radius,
barycenters[i].position.x,
barycenters[i].position.y
));
}
writeMessageBlock("Detected stars " + barycenters.length);
var starProfiles = new Array;
var increment = Math.floor(stars.length / 100);
if (increment == 0) increment = stars.length;
//
// PSF analysis
//
dynamicPSF.autoPSF = true; // start with auto, select by function codes
dynamicPSF.gaussianPSF = false;
var views = new Array;
views.push(new Array(view.id));
dynamicPSF.views = views;
dynamicPSF.views[0] = view.id;
dynamicPSF.signedAngles = true;
dynamicPSF.regenerate = true;
var allStars = [];
dynamicPSF.stars = stars;
dynamicPSF.executeGlobal();
for (var i = 0; i < dynamicPSF.psf.length; ++i) {
var psfRow = dynamicPSF.psf[i];
allStars.push(psfRow);
if (psfRow[3] == DynamicPSF.prototype.PSF_FittedOk) {
starProfiles.push(new starProfile(
psfRow[PSF_function],
psfRow[PSF_circular],
psfRow[PSF_status],
psfRow[PSF_B],
psfRow[PSF_A],
psfRow[PSF_cx],
psfRow[PSF_cy],
psfRow[PSF_sx],
psfRow[PSF_sy],
psfRow[PSF_theta],
psfRow[PSF_beta],
psfRow[PSF_mad]
));
}
}
var a = uniqueArray(starProfiles, starProfileCompareMAD);
if (a.length == 0) {
writeWarningBlock("Could not detect any stars. This works only on linear images!");
}
writeMessageEnd("Getting stars done");
return a;
}
function starProfile(psf_function, psf_circular, psf_status, B, A, cx, cy,
sx, sy, theta, beta, mad) {
this.psf_function = psf_function;
this.psf_circular = psf_circular;
this.psf_status = psf_status;
this.a = A;
this.b = B;
this.cx = cx;
this.cy = cy;
this.sx = sx;
this.sy = sy;
this.theta = theta;
this.beta = beta;
this.mad = mad;
}
function starProfileCompareMAD(a, b) {
return a.mad < b.mad ? -1 : 1;
}
function uniqueArray(values, compareFunction) {
if (values.length < 2) {
return values;
}
values.sort(compareFunction);
var j = 0;
for (var i = 1; i != values.length; ++i) {
if (compareFunction(values[j], values[i]) == -1) {
++j;
values[j] = values[i];
}
}
return values.slice(0, j + 1);
}
function average(a) {
if (a == null) return 0;
if (a.length == 0) return 0;
return Math.sum(a) / a.length;
}
// #endregion "PSF"
// #region "Apply"
function applyStf(viewId) {
startProcessing();
writeMessageBlock("Applying STF to " + viewId, true, false);
let view = View.viewById(viewId);
// apply stf
doSTF(view);
// apply ht
doHistogramTransformation(view);
// reset stf
doResetSTF(view);
stopProcessing();
}
function applyBinarize(viewId) {
startProcessing();
writeMessageBlock("Applying Binarize to " + viewId, true, false);
let view = View.viewById(viewId);
// apply binarize
// threshold 0.10
doBinarize(view);
stopProcessing();
}
function applyDilate(viewId) {
startProcessing();
writeMessageBlock("Applying Dilate to " + viewId, true, false);
let view = View.viewById(viewId);
// apply morphtransform
// dilation, amount 1, 1 iteration, 5x5 circular
doDilate(view);
stopProcessing();
}
function applyConvolute(viewId) {
startProcessing();
writeMessageBlock("Applying Convolve to " + viewId, true, false);
let view = View.viewById(viewId);
// apply convolution
// sigma 4.5, shape 2
doConvolve(view);
stopProcessing();
}
function applyBoost(viewId) {
startProcessing();
writeMessageBlock("Applying boost to " + viewId, true, false);
let view = View.viewById(viewId);
// apply curvestransformation
doBoost(view);
stopProcessing();
}
// #endregion "Apply"
// #region "Dialog"
function customizeDialog() {
dialog.infoBox.text = "<b>EZ Decon:</b> A script to easily deconvolve and sharpen an image. It is based on sharpening the image using deconvolution without deringing and replacing the stars in the image. A good star mask is required and can be generated with this script. For star mask generation, StarNet++ needs to be installed.";
dialog.allowPreviews();
dialog.tutorialPrerequisites = ["Image is cropped properly", "Image is not stretched (image is linear)", "StarNet++ is installed or StarNet++ raw star mask is present"];
dialog.tutorialSteps = ["Select image or preview to apply to",
"Press 'Create New Processed Star Mask' or 'Create new raw Star Mask' or select a already processed or raw star mask",
"Adjust Star Mask if necessary with 'Edit Star Mask' buttons and the custom ellipses in the panel on the right",
"Verify Star Mask is covering all stars well with the 'Alternative Version of Image' view of the 'Star Mask' tab",
"On demand, either specify or create a new background mask. The background mask will be used to replace the background after deconvolution",
"Generate or select a PSF in 'Deconvolution' tab, warning: will take long on large images, might be better to create one manually",
"Press 'Evaluate EZ Decon Run' to evaluate the current settings",
"Verify result is adequate, eventually adjust Star Mask, Wavelets or Iterations and repeat evaluation",
"If image gets noisier increase wavelet strength",
"If image is oversharpened, reduce iterations",
"If stars have ringing increase Star Mask radius to cover stars better",
"Once happy with the result either run EZ Decon or Apply Current of a specified run"];
dialog.starMaskControlIndex = 1;
dialog.psfControlIndex = 2;
dialog.onEvaluateButton.show();
dialog.onExit = function () { }
dialog.onSelectedMainView = function (value, prevMainViewId) {
dialog.starMaskImageSelector.excludedView = value.window.mainView;
dialog.psfImageSelector.excludedView = value.window.mainView;
if (prevMainViewId != CurrentProcessingInfo.mainViewId) {
if (dialog.psfImageSelector.currentView != null)
dialog.psfImageSelector.remove(dialog.psfImageSelector.currentView);
dialog.psfImageSelector.reload();
CurrentProcessingInfo.psfViewId = null;
if (dialog.starMaskImageSelector.currentView != null)
dialog.starMaskImageSelector.remove(dialog.starMaskImageSelector.currentView);
dialog.starMaskImageSelector.reload();
CurrentProcessingInfo.starMaskId = null;
for (let i = dialog.tabBox.numberOfPages - 1; i >= 0; i--) {
dialog.tabBox.pageControlByIndex(i).dispose();
dialog.tabBox.removePage(i);
}
} else {
try {
dialog.tabBox.pageControlByIndex(0).dispose();
dialog.tabBox.removePage(0);
} catch (e) { }
}
dialog.addMainControl(true, CurrentProcessingInfo.workingViewId, null);
dialog.tabBox.currentPageIndex = 0;
if (prevMainViewId == null) dialog.width *= 3;
}
dialog.onEmptyMainView = function () {
dialog.tabBox.hide();
dialog.adjustToContents();
}
dialog.canRun = function () {
return CurrentProcessingInfo.mainViewId != null
&& CurrentProcessingInfo.psfViewId != null
&& CurrentProcessingInfo.starMaskId != null
&& (CurrentProcessingInfo.backgroundReplacement == false
|| (CurrentProcessingInfo.backgroundReplacement == true && CurrentProcessingInfo.backgroundMaskId != null));
}
dialog.canEvaluate = function () { return dialog.canRun(); }
dialog.starMaskImageSelector = new ViewList(dialog);
with (dialog.starMaskImageSelector) {
bindings = function() {
if(CurrentProcessingInfo.starMaskId != null
&& CurrentProcessingInfo.starMaskId != this.currentView.id) {
getMainViews();
this.currentView = View.viewById(CurrentProcessingInfo.starMaskId);
this.onViewSelected(this.currentView);
}
}
toolTip = "Select Star Mask";
onViewSelected = function (value) {
if (value.isNull) {
CurrentProcessingInfo.starMaskId = null;
let oldStarMask = dialog.findControlInTabBox("Star Mask");
if (oldStarMask != null) {
oldStarMask.dispose();
dialog.tabBox.removePage(dialog.findControlIndexInTabBox(oldStarMask));
}
return;
}
if (value.image.isColor) {
dialog.showWarningDialog("Cannot use RGB Star Mask.");
dialog.starMaskImageSelector.remove(value);
} else {
let mainView = View.viewById(CurrentProcessingInfo.mainViewId);
if (value.image.width != mainView.image.width || value.image.height != mainView.image.height) {
dialog.showWarningDialog("Incompatible mask geometry");
dialog.starMaskImageSelector.remove(value);
return;
} else {
CurrentProcessingInfo.starMaskId = value.isPreview ? value.fullId : value.id;
writeMessageBlock("Selected star mask '" + CurrentProcessingInfo.starMaskId + "'", true, true);
dialog.addStarMaskControl();
}
}
}
excludeIdentifiersPattern = "_ez_temp_*";
getMainViews();
}
dialog.backgroundProtectionSelector = new ViewList(dialog);
with (dialog.backgroundProtectionSelector) {
toolTip = "Select Background Replacement";
bindings = function() {
if(CurrentProcessingInfo.backgroundMaskId != null
&& CurrentProcessingInfo.backgroundMaskId != this.currentView.id) {
getMainViews();
this.currentView = View.viewById(CurrentProcessingInfo.backgroundMaskId);
this.onViewSelected(this.currentView);
}
}
onViewSelected = function (value) {
if (value.isNull) {
CurrentProcessingInfo.backgroundMaskId = null;
let backgroundMask = dialog.findControlInTabBox("Background");
if (backgroundMask != null) {
backgroundMask.dispose();
dialog.tabBox.removePage(dialog.findControlIndexInTabBox(backgroundMask));
}
return;
}
if (value.image.isColor) {
dialog.showWarningDialog("Cannot use RGB Background Mask.");
dialog.backgroundProtectionSelector.remove(value);
} else {
let mainView = View.viewById(CurrentProcessingInfo.mainViewId);
if (value.image.width != mainView.image.width || value.image.height != mainView.image.height) {
dialog.showWarningDialog("Incompatible mask geometry");
dialog.backgroundProtectionSelector.remove(value);
return;
} else {
CurrentProcessingInfo.backgroundMaskId = value.isPreview ? value.fullId : value.id;
writeMessageBlock("Selected background mask '" + CurrentProcessingInfo.backgroundMaskId + "'", true, true);
dialog.addBackgroundMaskControl();
}
}
}
excludeIdentifiersPattern = "_ez_temp_*";
getMainViews();
}
dialog.addMainControl = function (clear, viewId) {
if (viewId != null) {
let previewControl = new PreviewControl(dialog, true, true);
previewControl.swap = function () {