-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZ_Common.js
1904 lines (1622 loc) · 54.4 KB
/
EZ_Common.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_common.js
/*
Acknowledgements
Andres del Pozo for his PreviewControl.js
*/
#include <pjsr/StarDetector.jsh>
#include <pjsr/UndoFlag.jsh>
#include <pjsr/Sizer.jsh>
#include <pjsr/FrameStyle.jsh>
#include <pjsr/TextAlign.jsh>
#include <pjsr/StdButton.jsh>
#include <pjsr/StdIcon.jsh>
#include <pjsr/UndoFlag.jsh>
#include <pjsr/ColorSpace.jsh>
#include <pjsr/NumericControl.jsh>
#include <pjsr/SectionBar.jsh>
#include <pjsr/StdCursor.jsh>
#include <pjsr/PropertyType.jsh>
#include <pjsr/PropertyAttribute.jsh>
#include <pjsr/PenStyle.jsh>
#include <pjsr/Color.jsh>
//STF settings:
// Shadows clipping point in (normalized) MAD units from the median.
#define DEFAULT_AUTOSTRETCH_SCLIP -2.8
// Target mean background in the [0,1] range.
#define DEFAULT_AUTOSTRETCH_TGBND 0.25
#define CONSOLE_WIDTH 72
#define PADDING 4
#define DEFAULT_STF [[0.5,0,1,0,1],[0.5,0,1,0,1],[0.5,0,1,0,1],[0.5,0,1,0,1]]
#define StorePropertyAttribute (PropertyAttribute_Permanent | PropertyAttribute_Storable)
// #region Globals
var COMMONVERSION = "2.7";
var CurrentProcessingInfo = null;
var dialog = null;
var commonMessageLevel = 0;
var FULLNAME = NAME + " v" + VERSION;
var WARNING = "WARNING: THE EZ PROCESSING SUITE IS STILL UNDER HEAVY DEVELOPMENT. PLEASE SAVE YOUR WORK BEFORE DOING ANYTHING IN THE \"" + FULLNAME.toUpperCase() + "\" SCRIPT INCLUDING SELECTING AN IMAGE. PIXINSIGHT COULD CRASH AND YOU COULD LOSE ALL YOUR UNSAVED WORK.";
var showWarning = false;
var PROCESSING = [];
myDialog.prototype = new Dialog;
ProcessingInfo.prototype = new Object;
PreviewControl.prototype = new Control;
SpacedVerticalSizer.prototype = new VerticalSizer;
SpacedHorizontalSizer.prototype = new HorizontalSizer;
SpacedRichLabel.prototype = new Label;
function ProcessingInfo() {
this.mainViewId = null;
this.workingViewId = null;
}
// #endregion Globals
// #region Utility
ProcessingInfo.prototype.toString = function() {
for (let propName in this) {
propValue = this[propName]
console.writeln(this.constructor.name + "." +propName + " = " + propValue);
}
}
Object.prototype.printPropertiesDebug = function() {
for (let propName in this) {
propValue = this[propName]
console.writeln(this.constructor.name + "." +propName + " = " + propValue);
}
}
function waitForS(seconds) {
let sleepT = 0;
while (sleepT < seconds) {
let sleepS = 0.1;
sleep(sleepS);
processEvents();
sleepT += sleepS;
}
}
function getValueOrDefault(value, defaultValue) {
if(value == null || value === undefined) return defaultValue;
return value;
}
Array.prototype.removeItem = function(item) {
let idx = this.indexOf(item);
if(idx > -1) {
this.splice(idx, 1);
}
}
function startProcessing() {
PROCESSING.push(true);
dialog.recalculateAll();
}
function stopProcessing() {
PROCESSING.pop();
}
function isProcessing() {
return PROCESSING.length != 0;
}
String.prototype.format = function () {
var a = this;
for (var k in arguments) {
a = a.replace(new RegExp("\\{" + k + "\\}", 'g'), arguments[k]);
}
return a
}
function writeMessage(text, useSeparatorBefore = true, useSeparatorAfter = true, level = 0, warning = false) {
let textLine = levelPadLeft("║", level);
let orgPadding = textLine.length;
for (let i = 0; i < PADDING; i++) {
textLine += " ";
}
let preamble = textLine.length;
if (useSeparatorBefore) {
if (!warning) {
console.noteln(getSeparator(level, true));
} else {
console.warningln(getSeparator(level, true));
}
}
if(text != null) {
if (text.length + textLine.length + PADDING > CONSOLE_WIDTH) {
let split = text.split(" ");
let paddedLength = preamble + PADDING;
for (let i = 0; i < split.length; i++) {
if (paddedLength + split[i].length + PADDING > CONSOLE_WIDTH) {
split[i] = split[i].substring(0, CONSOLE_WIDTH - (paddedLength + 4)) + "...";
}
}
while (split.length > 0) {
do {
processEvents();
if (split.length == 0) break;
if (textLine.length + split[0].length + " ".length + PADDING > CONSOLE_WIDTH) {
break;
}
textLine += split[0] + " ";
paddedLength = textLine.length + PADDING;
split.shift();
} while (true);
textLine = padTextRight(textLine);
if (!warning) {
console.noteln(textLine);
} else {
console.warningln(textLine);
}
textLine = levelPadLeft("║", level);
for (let i = 0; i < preamble - orgPadding; i++) {
textLine += " ";
}
}
} else {
if (!warning) {
console.noteln(padTextRight(textLine + text));
} else {
console.warningln(padTextRight(textLine + text));
}
}
}
if (useSeparatorAfter) {
if (!warning) {
console.noteln(getSeparator(level, false));
} else {
console.warningln(getSeparator(level, false));
}
}
}
function getSeparator(level, top) {
let leftChar = "╔";
if (!top) leftChar = "╚";
let rightChar = "╗";
if (!top) rightChar = "╝";
let separator = levelPadLeft(leftChar, level)
for (let i = separator.length; i < CONSOLE_WIDTH - 1; i++) {
separator += "═";
}
separator += rightChar;
return separator;
}
function levelPadLeft(text, level) {
let padText = "";
for (let i = 0; i < level * PADDING; i++) {
if (i % PADDING == 0) padText += "║";
else padText += " ";
}
return padText + text;
}
function padTextRight(text) {
while (text.length < CONSOLE_WIDTH - 1) {
text += " ";
}
text += "║";
return text;
}
function writeMessageBlock(text, useborders = true, decreaseLevel = false) {
if (decreaseLevel) commonMessageLevel--;
writeMessage(text, useborders, useborders, commonMessageLevel);
if (decreaseLevel) commonMessageLevel++;
}
function writeWarningBlock(text, useborders, decreaseLevel = false) {
if (decreaseLevel) commonMessageLevel--;
writeMessage(text, useborders, useborders, commonMessageLevel, true);
if (decreaseLevel) commonMessageLevel++;
}
function writeMessageStart(text) {
writeMessage(text, true, false, commonMessageLevel);
commonMessageLevel++;
}
function writeMessageEnd(text) {
commonMessageLevel--;
commonMessageLevel < 0 ? commonMessageLevel = 0 : commonMessageLevel;
writeMessage(text, false, true, commonMessageLevel);
}
function getStarNet() {
try {
return new StarNet;
} catch (e) {
return null;
}
}
function readFromSettingsOrDefault(key, type, defaultVal) {
let value = Settings.read(key, type);
if (Settings.lastReadOK) {
return value;
}
return defaultVal;
}
function readImage(filePath, ignoreKeywords = false) {
startProcessing();
let ext = File.extractExtension(filePath);
let fileFormat = new FileFormat(ext, true/*toRead*/, false/*toWrite*/);
let fileFormatInstance = new FileFormatInstance(fileFormat);
let image = null;
try {
image = fileFormatInstance.open(filePath, "fits-keywords normalize raw cfa");
} catch(e) {
writeWarningBlock("Could not read file");
stopProcessing();
return null;
}
let fileName = sanitizeViewId(File.extractName(filePath));
if (!View.viewById(fileName).isNull) {
fileName += "1";
}
let window = new ImageWindow(1, 1, 1,/*numberOfChannels*/ 32,/*bitsPerSample*/
true/*floatSample*/, false, fileName);
let view = window.mainView;
view.beginProcess(UndoFlag_NoSwapFile);
if (!fileFormatInstance.readImage(view.image)) {
stopProcessing();
view.endProcess();
throw new Error("Unable to read file: " + filePath);
}
if (fileFormat.canStoreImageProperties && !ignoreKeywords)
if (fileFormat.supportsViewProperties) {
let info = view.importProperties(fileFormatInstance);
if (info.isEmpty)
console.criticalln("<end><cbr>*** Error reading image properties:\n", info);
}
if (fileFormat.canStoreKeywords && !ignoreKeywords)
window.keywords = fileFormatInstance.keywords;
view.endProcess();
fileFormatInstance.close();
stopProcessing();
return window;
};
function sanitizeViewId(id) {
var fId = "";
if (id.length == 0) {
return "_";
}
var c = id.charAt(0);
if ("0" <= c && c <= "9") {
fId = fId + "_";
}
for (var i = 0; i != id.length; ++i) {
c = id.charAt(i);
fId = fId + (
(("0" <= c && c <= "9") || ("a" <= c && c <= "z") || ("A" <= c && c <= "Z")) ? c : "_"
);
if (fId.length > 3 && fId.substring(fId.length - 4, fId.length) == "____") {
fId = fId.substring(0, fId.length - 1);
}
}
return fId;
}
function printProperties(view) {
writeMessageStart("Properties of " + view.id);
for (let i = 0; i < view.properties.length; i++) {
writeMessageBlock(view.properties[i] + " = " + view.propertyValue(view.properties[i]), false, true);
}
writeMessageEnd()
}
// #endregion Utilities
// #region Image Modification
function cloneProperties(oldView, newView, func = null) {
//console.warningln("Cloning properties from " + oldView.id + " to " + newView.id);
let oldProperties = [];
for (let i = 0; i < oldView.properties.length; i++) {
oldProperties.push([oldView.properties[i], oldView.propertyValue(oldView.properties[i]), oldView.propertyAttributes((oldView.properties[i]))]);
}
let oldKeywords = oldView.keywords;
if (func != null) func();
for (let i = 0; i < oldProperties.length; i++) {
try {
newView.setPropertyValue(oldProperties[i][0], oldProperties[i][1]);
newView.setPropertyAttributes(oldProperties[i][0], oldProperties[i][2]);
//console.warningln("prop " + oldProperties[i][0] + ":" + oldProperties[i][1]);
} catch (e) { /* probably some reserved property */ }
}
newView.beginProcess(UndoFlag_NoSwapFile);
newView.keywords = oldKeywords;
newView.endProcess();
}
View.prototype.storeProperty = function(property, value) {
this.setPropertyValue(property, value, PropertyType_Auto, StorePropertyAttribute);
}
function convertFromViewStf(stf) {
let newStf = [];
for (let i = 0; i < stf.length; i++) {
newStf.push([stf[i][1], stf[i][2], stf[i][0], stf[i][3], stf[i][4]]);
}
return newStf;
}
function convertToViewStf(stf) {
let newStf = [];
for (let i = 0; i < stf.length; i++) {
newStf.push([stf[i][2], stf[i][0], stf[i][1], stf[i][3], stf[i][4]]);
}
return newStf;
}
function doSTF(view, stf = null, unlinked = false) {
var transformation = [
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1]];
if (stf == null) {
//get values from the image to calculate STF
var median = view.computeOrFetchProperty("Median");
var mad = view.computeOrFetchProperty("MAD");
//set variables
let targetBackground = DEFAULT_AUTOSTRETCH_TGBND;
let shadowsClipping = DEFAULT_AUTOSTRETCH_SCLIP;
if ((!unlinked && !view.image.isGrayscale) || view.image.isGrayscale) {
// calculate STF settings based on DeLinear Script
var clipping = (1 + mad.at(0) != 1) ?
Math.range(median.at(0) + shadowsClipping * mad.at(0), 0.0, 1.0) : 0.0;
var targetMedian = Math.mtf(targetBackground, median.at(0) - clipping);
transformation[0] = [clipping, 1, targetMedian, 0, 1];
if(!view.image.isGrayscale) {
transformation[1] = [clipping, 1, targetMedian, 0, 1];
transformation[2] = [clipping, 1, targetMedian, 0, 1];
}
} else {
for (let i = 0; i < 3; i++) {
// calculate STF settings based on DeLinear Script
var clipping = (1 + mad.at(i) != 1) ?
Math.range(median.at(i) + shadowsClipping * mad.at(i), 0.0, 1.0) : 0.0;
var targetMedian = Math.mtf(targetBackground, median.at(i) - clipping);
transformation[i] = [clipping, 1, targetMedian, 0, 1];
}
}
} else {
transformation = stf;
}
var STFunction = new ScreenTransferFunction();
STFunction.STF = transformation;
STFunction.executeOn(view);
return transformation;
}
// applies ht transformation on current image
function doHistogramTransformation(view) {
var HT = new HistogramTransformation;
if (view.image.isGrayscale) {
//get values from STF
var clipping = view.stf[0][1];
var median = view.stf[0][0];
HT.H = [[0, 0.5, 1.0, 0, 1.0],
[0, 0.5, 1.0, 0, 1.0],
[0, 0.5, 1.0, 0, 1.0],
[clipping, median, 1.0, 0, 1.0],
[0, 0.5, 1.0, 0, 1.0]];
} else {
HT.H = [[view.stf[0][1], view.stf[0][0], 1.0, 0, 1.0],
[view.stf[1][1], view.stf[1][0], 1.0, 0, 1.0],
[view.stf[2][1], view.stf[2][0], 1.0, 0, 1.0],
[0, 0.5, 1.0, 0, 1.0],
[0, 0.5, 1.0, 0, 1.0]];
}
view.beginProcess();
HT.executeOn(view.image);
view.endProcess();
}
function doResetSTF(view) {
let transformation = [
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1],
[0, 1, 0.5, 0, 1]];
let STFunction = new ScreenTransferFunction();
STFunction.STF = transformation;
STFunction.executeOn(view);
return transformation;
}
// stretches view to target value
function stretchToValue(view, target) {
var AH = new AutoHistogram;
AH.clip = false;
AH.stretch = true;
AH.stretchTogether = true;
AH.stretchMethod = AutoHistogram.prototype.MTF;
AH.targetMedianR = target;
AH.targetMedianG = target;
AH.targetMedianB = target;
AH.executeOn(view);
}
//uses NoiseEvaluation script to get an estimation of the background noise. Returns stdev
function noiseEvaluation(window) {
var img = window.mainView.image;
var a, n = 4, m = 0.01 * img.selectedRect.area;
for (; ;) {
a = img.noiseMRS(n);
if (a[1] >= m)
break;
if (--n == 1) {
console.writeln("Issue with MRS noise evaluation (did not converge). Using k-sigma noise evaluation. Try using manually selected preview for noise estimation.");
break;
}
}
return a[0];
}
function EZ_ScaledNoiseEvaluation(image)
{
let scale = image.Sn();
if ( 1 + scale == 1 )
throw Error( "Zero or insignificant data." );
let a, n = 4, m = 0.01*image.selectedRect.area;
for ( ;; )
{
a = image.noiseMRS( n );
if ( a[1] >= m )
break;
if ( --n == 1 )
{
console.writeln( "<end><cbr>** Warning: No convergence in MRS noise evaluation routine - using k-sigma noise estimate." );
a = image.noiseKSigma();
break;
}
}
this.sigma = a[0]/scale; // estimated scaled stddev of Gaussian noise
this.count = a[1]; // number of pixels in the noisy pixels set
this.layers = n; // number of layers used for noise evaluation
}
// copies an existing view to a new name
function cloneView(view, newName, hide = false, convertToColor = false) {
var newWindow = new ImageWindow(view.image.width, view.image.height, convertToColor ? 3 : view.image.numberOfChannels,
view.window.bitsPerSample, view.window.isFloatSample, view.image.colorSpace != ColorSpace_Gray || convertToColor,
newName);
newWindow.mainView.beginProcess(UndoFlag_NoSwapFile);
newWindow.mainView.image.assign(view.image);
if(convertToColor && view.image.colorSpace == 0)
{
newWindow.mainView.image.colorSpace = 1;
}
newWindow.mainView.endProcess();
// clone keywords and properties
cloneProperties(view, newWindow.mainView);
newWindow.mainView.stf = view.stf;
if (!hide) {
newWindow.show();
}
return newWindow.mainView;
}
function extractLightness(view) {
let clonedView = null;
if (view.image.isColor) {
writeMessageBlock("Original image is color, extracting luminance");
var lumExtraction = new ChannelExtraction;
lumExtraction.colorSpace = ChannelExtraction.prototype.CIELab;
lumExtraction.channels = [
[true, ""],
[false, ""],
[false, ""]
];
lumExtraction.sampleFormat = ChannelExtraction.prototype.SameAsSource;
lumExtraction.executeOn(view);
clonedView = ImageWindow.activeWindow.currentView;
clonedView.id = "_ez_lightness_temp";
} else {
clonedView = cloneView(view, "_ez_lightness_temp");
}
return clonedView;
}
function createBackgroundMask(view, maskName, stretch = true) {
startProcessing();
writeMessageStart("Creating background mask based on " + view.id);
let lightnessClone = extractLightness(view);
if(stretch)
doStretch(lightnessClone);
let backgroundMaskView = doBackgroundRangeSelection(lightnessClone);
lightnessClone.window.forceClose();
backgroundMaskView.id = maskName;
backgroundMaskView.window.iconize();
writeMessageEnd("Mask creation done");
stopProcessing();
return backgroundMaskView.id;
}
function doBackgroundRangeSelection(view) {
let median = view.computeOrFetchProperty("Median").at(0);
let rangeSelection = new RangeSelection();
rangeSelection.fuzziness = 0.1;
rangeSelection.smoothness = 5;
rangeSelection.highRange = median;
rangeSelection.executeOn(view);
return ImageWindow.activeWindow.mainView;
}
View.prototype.readPropertyOrKeyword = function(property, keyword) {
let value = this.propertyValue(property);
if(value != null) return value;
try {
let keywords = this.window.keywords;
for(let i = 0;i<keywords.length;i++) {
let fitskeyword = new FITSKeyword(keywords[i]);
if(fitskeyword.name == keyword) {
return fitskeyword.strippedValue;
}
}
} catch(e) {
}
return null;
}
function doStretch(view) {
writeMessageBlock("Stretching image");
doSTF(view);
doHistogramTransformation(view);
}
function doPixelMath(view, expression, useSingleExpression = true) {
cloneProperties(view, view, function () {
var pixelMath = new PixelMath;
if (useSingleExpression) {
pixelMath.expression = expression;
pixelMath.expression1 = "";
pixelMath.expression2 = "";
pixelMath.expression3 = "";
pixelMath.useSingleExpression = true;
} else {
pixelMath.expression = expression;
pixelMath.expression1 = expression;
pixelMath.expression2 = expression;
pixelMath.expression3 = "";
pixelMath.useSingleExpression = false;
}
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;
pixelMath.executeOn(view);
});
}
// #endregion Image Modification
// #region Histogram Stuff
function detectPeaks(arr, windowWidth, threshold) {
const peaks = [];
let prev = 0;
for (let i = 0; i < arr.length; i++) {
const start = Math.max(0, i - windowWidth);
const end = Math.min(arr.length, i + windowWidth);
let deltaAcc = 0;
for (let a = start; a < end; a++) {
let cur = arr[a];
deltaAcc += Math.abs(prev - cur);
prev = cur;
}
if (deltaAcc > threshold) {
peaks.push([i, deltaAcc]);
}
i += end - start - 1;
}
return peaks;
}
function findMidtonesBalance(v0, v1, eps) {
if (!eps)
eps = 1.0e-5;
else
eps = Math.max(1.0e-10, eps);
var m0, m1;
if (v1 < v0) {
m0 = 0;
m1 = 0.5;
}
else {
m0 = 0.5;
m1 = 1;
}
for (; ;) {
var m = 0.5 * (m0 + m1);
var v = Math.mtf(m, v1);
processEvents();
if (Math.abs(v - v0) < eps)
return m;
if (v < v0)
m1 = m;
else
m0 = m;
}
}
function generateNoiseEvalImage(noiseEvalValues) {
let vals = [];
let noiseEvalValuesString = null;
if(noiseEvalValues != null) {
noiseEvalValuesString = noiseEvalValues.toString();
}
if(noiseEvalValuesString != null && noiseEvalValuesString.indexOf(";") >= 0) {
vals = noiseEvalValuesString.split(";");
}
let xScale = 400;
let yScale = 400;
let bitmap = new Bitmap(xScale, yScale);
let graphics = new VectorGraphics(bitmap);
// do some drawing magic
graphics.antialiasing = true;
graphics.fillRect(0, 0, xScale, yScale, new Brush(0xFF202020));
if(noiseEvalValuesString == null || vals.length == 0) {
graphics.end();
return bitmap;
}
writeMessageBlock("Generating Noise Evaluation Image");
// find minVal
let minVal = vals[0];
for(let i = 0;i<vals.length;i++) {
if(vals[i] < minVal) {
minVal = vals[i];
}
}
// find maxVAl
let maxVal = vals[0];
for(let i = 0;i<vals.length;i++) {
if(vals[i] > maxVal) {
maxVal = vals[i];
}
}
let radius = 2.5;
let xValScale = ((xScale-radius*2)/(vals.length-1));
var px = 0xFFAAAAAA;
var points = [];
for(let i = 0;i<vals.length;i++) {
let val = vals[i];
let yPos = (yScale-radius*2)*((val-minVal)/(maxVal-minVal));
let point = new Point(i*xValScale+radius, yScale-radius-yPos);
points.push(point);
}
for(let i = 0;i<points.length;i++) {
let nextPoint = i+1 > points.length ? null : points[i+1];
graphics.fillCircle(points[i], radius, new Brush(px));
if(nextPoint != null) {
graphics.pen = new Pen(px);
graphics.drawLine(points[i], nextPoint);
}
}
graphics.end();
processEvents();
return bitmap;
}
function generateHistogramImage(view) {
let xScale = 450;
let yScale = 250;
writeMessageBlock("Generating Histogram Image");
let histogramMatrix = view.computeOrFetchProperty("Histogram16");
let htStep = parseInt(histogramMatrix.cols / xScale);
let htMax = 0;
let matrixarray = histogramMatrix.toArray();
let rgb = [];
if (histogramMatrix.rows == 1) {
rgb.push(matrixarray);
}
else {
rgb.push(matrixarray.slice(0, 65536));
rgb.push(matrixarray.slice(65537, 65536 * 2));
rgb.push(matrixarray.slice(65536 * 2 + 1, 65536 * 3));
}
let peaks = [];
for (let rgbc = 0; rgbc < histogramMatrix.rows; rgbc++) {
peaks = detectPeaks(rgb[rgbc], 10000, 50000);
processEvents();
let selectedPeak = 0;
let selectedPeakVal = 0;
for (let i = 0; i < peaks.length; i++) {
let value = peaks[i][1];
if (value > selectedPeakVal) {
selectedPeakVal = value;
selectedPeak = peaks[i][0];
}
}
for (let i = selectedPeak; i < rgb[rgbc].length; i++) {
let value = rgb[rgbc][i];
if (value > htMax) {
htMax = value;
}
}
}
let scaleMult = (yScale / htMax);
let newChannelMatrix = [];
let summedValue = [];
for (let rgbc = 0; rgbc < histogramMatrix.rows; rgbc++) {
newChannelMatrix.push([]);
for (let i = 0; i < histogramMatrix.cols; i++) {
summedValue.push(histogramMatrix.at(rgbc, i));
if (i % htStep == 0) {
newChannelMatrix[rgbc].push(Math.maxElem(summedValue) * scaleMult);
summedValue = [];
}
}
}
let bitmap = new Bitmap(xScale, yScale);
let graphics = new VectorGraphics(bitmap);
graphics.antialiasing = true;
graphics.fillRect(0, 0, xScale, yScale, new Brush(0xFF202020));
graphics.fillRect(0, 0, 1, yScale, new Brush(0x33FFFFFF));
graphics.fillRect(xScale, 0, xScale - 1, yScale, new Brush(0x33FFFFFF));
graphics.fillRect(0, 0, xScale, 1, new Brush(0x33FFFFFF));
graphics.fillRect(0, yScale, xScale, yScale - 1, new Brush(0x33FFFFFF));
for (let i = 1; i < 4; i++) {
graphics.fillRect(parseInt((xScale * 0.25)) * i, 0, parseInt((xScale * 0.25)) * i, yScale, new Brush(0x33FFFFFF));
}
for (let i = 0; i < newChannelMatrix[0].length; i++) {
if (newChannelMatrix.length == 1) {
for (let j = 0; j < yScale; j++) {
var px = 0xAA000000;
if (newChannelMatrix[0][i] > j) px |= 0x00CCCCCC;
if (px != 0xAA000000) {
graphics.fillRect(i, yScale - j, i, yScale - j, new Brush(px));
}
}
} else {
for (let j = 0; j < yScale; j++) {
var px = 0xAA000000;
if (newChannelMatrix[0][i] > j) px |= 0x00FF0000;
if (newChannelMatrix[1][i] > j) px |= 0x0000FF00;
if (newChannelMatrix[2][i] > j) px |= 0x000000FF;
if (px != 0xAA000000) {
graphics.fillRect(i, yScale - j, i, yScale - j, new Brush(px));
}
}
}
}
graphics.end();
processEvents();
return bitmap;
}
// #endregion Histogram Stuff
// #region "Dialog"
Control.prototype.bindings = null;
Control.prototype.evaluateBindings = function() {
//console.warningln("Evaluating bindings for " + this.constructor.name + ", parent: " + (this.parent == null ? "-" : this.parent.constructor.name));
if(this.bindings != null) {
//console.warningln("Evaluating bindings for " + this.constructor.name + ", parent: " + (this.parent == null ? "-" : this.parent.constructor.name));
if(this.hasFocus != null && !this.hasFocus)
this.bindings();
}
}
Sizer.prototype.evaluateBindings = function() {
if(this.bindings != null) {
if(this.hasFocus != null && !this.hasFocus)
this.bindings();
}
}
TabBox.prototype.recalculateAll = function(previous) {
for(let i = 0;i<this.numberOfPages;i++) {
let item = this.pageControlByIndex(i);
let alreadyProcessed = false;
for(let j = 0;j<previous.length;j++) {
if(previous[j] === item) {
alreadyProcessed = true;
break;
}
}
if(alreadyProcessed) continue;
previous.push(item);
if(item.evaluateBindings != null) item.evaluateBindings();
if(item.recalculateAll != null) item.recalculateAll(previous);
}
}
GroupBox.prototype.recalculateAll = function(previous) {
this.sizer.recalculateAll(previous);
}
Sizer.prototype.recalculateAll = function(previous) {
previous.push(this);
if(this.evaluateBindings != null) {
this.evaluateBindings();
}
//console.warningln("Previous " + previous);
for(let i = 0;i<this.items.length;i++) {
let item = this.items[i];
let alreadyProcessed = false;
for(let j = 0;j<previous.length;j++) {
if(previous[j] === item) {
alreadyProcessed = true;
break;
}
}
if(alreadyProcessed) continue;
previous.push(item);
if(item.evaluateBindings != null) item.evaluateBindings();
if(item.recalculateAll != null) item.recalculateAll(previous);
}
}
Dialog.prototype.evaluatedBindings = [];
Dialog.prototype.recalculateAll = function() {
//const start = Date.now();
this.evaluatedBindings = [this.sizer];
this.evaluateBindings();
this.sizer.recalculateAll(this.evaluatedBindings);
processEvents();
//const end = Date.now() - start;
//console.writeln("BindingCalc took " + end + "ms");
}
Sizer.prototype.items = [];
Sizer.prototype.clearMargin = function(previous) {
previous.push(this);
this.scaledMargin = 0;
for(let i = 0;i<this.items.length;i++) {
let item = this.items[i];
let alreadyProcessed = false;
for(let j = 0;j<previous.length;j++) {
if(previous[j] === item) {
alreadyProcessed = true;
break;
}
}
if(alreadyProcessed) continue;
previous.push(item);
if(item.constructor.name == "Sizer" && this.parentControl != null && typeof this.parentControl != "Dialog") {
item.scaledMargin = 0;
item.clearMargin(previous);
}
}
}
Sizer.prototype.addItem = function(item, stretchFactor = 0) {
//console.warningln("Adding " + item.constructor.name + " to " + this.constructor.name);
if(item.constructor.name == "Sizer" && this.parentControl != null && this.parentControl.constructor.name != "Dialog") {
item.clearMargin([]);