-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
1601 lines (1279 loc) · 73.3 KB
/
MainWindow.xaml.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using win = System.Windows;
using System.Drawing;
using media = System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using System.Threading;
using System.Numerics;
using Win = System.Windows;
using System.Windows.Controls;
using System.Globalization;
using System.Text;
namespace ColorMatch3D
{
struct FloatColor
{
public Vector3 color;
//public float R, G, B;
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : win.Window
{
public MainWindow()
{
InitializeComponent();
//win.Forms.MessageBox.Show(Helpers.CIELChabTosRGB((Helpers.sRGBToCIELChab(new Vector3 { X=128, Y=128, Z=128 }))).ToString());
//Status_txt.Text = "SIMD: " + Vector.IsHardwareAccelerated.ToString();
}
private void readGUISettings(string nameOfElement = "")
{
try {
switch (nameOfElement)
{
case "batchTestSuffix_text":
batchTestSuffix = batchTestSuffix_text.Text.Trim();
break;
case "batchReferenceSuffix_text":
batchReferenceSuffix = batchReferenceSuffix_text.Text.Trim();
break;
case "lowpassEqualizeBlurRadius_Text":
lowPassEqualizeBlurRadius = float.Parse(lowpassEqualizeBlurRadius_Text.Text);
break;
case "lowPassPercentileSubdivisions_Text":
lowPass1DRegradePercentileSubdivisions = int.Parse(lowPassPercentileSubdivisions_Text.Text);
break;
case "lowPassSmoothingIntensity_Text":
lowPass1DRegradeSmoothingIntensity = float.Parse(lowPassSmoothingIntensity_Text.Text);
break;
case "lowPassHistoMatchSmoothRadius_Text":
lowPass1DRegradeSmoothingRadius = int.Parse(lowPassHistoMatchSmoothRadius_Text.Text);
break;
case "boxBlur3dRadius_text":
postMatchSmoothing3DBoxBlurRadius = int.Parse(boxBlur3dRadius_text.Text);
break;
case "boxBlur3dProtectLuminance_text":
postMatchSmoothing3DBoxBlurLuminanceProtection = float.Parse(boxBlur3dProtectLuminance_text.Text);
break;
case "boxBlur3dStrength_text":
postMatchSmoothing3DBoxBlurStrength = float.Parse(boxBlur3dStrength_text.Text);
break;
case "boxBlur3dDisabled_radio":
postMatchSmoothing = PostMatchSmoothing.NONE;
break;
case "boxBlur3dActive_radio":
postMatchSmoothing = PostMatchSmoothing.BOXBLUR3D;
break;
case "lowPassHistoMatchYes_radio":
lowPass1DRegrade = LowPass1DRegrade.HISTOGRAM;
break;
case "lowPassHistoMatchNo_radio":
lowPass1DRegrade = LowPass1DRegrade.NONE;
break;
case "lowPassMatchNone_radio":
lowPassMatching = LowPassMatching.NONE;
break;
case "lowPassMatchReferenceToSource_radio":
lowPassMatching = LowPassMatching.REFERENCETOTEST;
break;
case "useSRGBAggrSpace_radio":
aggregateColorSpace = AggregateColorSpace.SRGB;
break;
case "useSRGBLinearAggrSpace_radio":
aggregateColorSpace = AggregateColorSpace.SRGBLINEAR;
break;
case "useXYZAggrSpace_radio":
aggregateColorSpace = AggregateColorSpace.XYZ;
break;
case "useCIELabAggrSpace_radio":
aggregateColorSpace = AggregateColorSpace.CIELAB;
break;
case "useCIELChabAggrSpace_radio":
aggregateColorSpace = AggregateColorSpace.CIELCHAB;
break;
case "aggrAbsolute_radio":
aggregateWhat = AggregateVariable.ABSOLUTE;
break;
case "aggrVector_radio":
aggregateWhat = AggregateVariable.VECTOR;
break;
case "interpNone_radio":
interpolationType = InterpolationType.NONE;
break;
case "interpSingleLinear_radio":
interpolationType = InterpolationType.SINGLELINEAR;
break;
case "interpDualLinear_radio":
interpolationType = InterpolationType.DUALLINEAR;
break;
default:
break;
}
}
catch (Exception e) { //fuck, it's just called too early and the objects dont exist. whatever.
win.MessageBox.Show("Caution. Invalid values entered. Will prevent proper setting of data. "+e.Message+" "+e.StackTrace);
}
//Win.MessageBox.Show(aggregateWhat.ToString());
}
string batchTestSuffix = "-test";
string batchReferenceSuffix = "-ref";
string batchTestFolder = ".";
string batchReferenceFolder = ".";
string batchOutputFolder = ".";
bool batchTestFolderIsset = false, batchReferenceFolderIsset = false, batchOutputFolderIsset = false;
bool batchTestFolderSoftIsset = false, batchReferenceFolderSoftIsset = false, batchOutputFolderSoftIsset = false;
enum AggregateVariable { ABSOLUTE, VECTOR};
AggregateVariable aggregateWhat = AggregateVariable.VECTOR;
enum InterpolationType { NONE, SINGLELINEAR, DUALLINEAR};
InterpolationType interpolationType = InterpolationType.SINGLELINEAR;
enum AggregateColorSpace { SRGB, SRGBLINEAR, XYZ, CIELAB, CIELCHAB };
AggregateColorSpace aggregateColorSpace = AggregateColorSpace.CIELAB;
enum LowPassMatching { NONE, REFERENCETOTEST, TESTTOREFERENCE};
LowPassMatching lowPassMatching = LowPassMatching.NONE;
float lowPassEqualizeBlurRadius = 10f;
enum LowPass1DRegrade { NONE, HISTOGRAM }
LowPass1DRegrade lowPass1DRegrade = LowPass1DRegrade.HISTOGRAM;
float lowPass1DRegradeSmoothingIntensity = 1f;
int lowPass1DRegradeSmoothingRadius = 20;
int lowPass1DRegradePercentileSubdivisions = 100;
enum PostMatchSmoothing { NONE, BOXBLUR3D};
PostMatchSmoothing postMatchSmoothing = PostMatchSmoothing.NONE;
int postMatchSmoothing3DBoxBlurRadius = 2;
float postMatchSmoothing3DBoxBlurStrength = 1.0f;
float postMatchSmoothing3DBoxBlurLuminanceProtection = 1.0f;
const int R = 0;
const int G = 1;
const int B = 2;
private Bitmap testImage = null;
private Bitmap referenceImage = null;
float displayGamma = 2.2f;
// Select test image
private void SelectTest_Click(object sender, win.RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files (.png,.jpg,.jpeg,.tif,.tiff,.tga)|*.png;*.jpg;*.jpeg;*.tif;*.tiff;*.tga";
if(ofd.ShowDialog() == true)
{
string filename = ofd.FileName;
testImage = (Bitmap) Bitmap.FromFile(filename);
ImageTop.Source = Helpers.BitmapToImageSource(testImage);
}
}
// Select reference image
private void SelectReference_Click(object sender, win.RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files (.png,.jpg,.jpeg,.tif,.tiff,.tga)|*.png;*.jpg;*.jpeg;*.tif;*.tiff;*.tga";
if (ofd.ShowDialog() == true)
{
string filename = ofd.FileName;
referenceImage = (Bitmap)Bitmap.FromFile(filename);
ImageBottom.Source = Helpers.BitmapToImageSource(referenceImage);
}
}
private void DoColorMatch_Click(object sender, win.RoutedEventArgs e)
{
DoColorMatch();
}
private void DoColorMatchBatch_Click(object sender, win.RoutedEventArgs e)
{
DoColorMatchBatch();
}
private Task ColorMatchTask;
private FloatColor[,,] globalCube = null;
// ColorMatch caller
private async void DoColorMatch()
{
if (testImage == null || referenceImage == null)
{
setStatus("Need both a test image and a reference image to match colors.",true);
return;
}
try
{
// Get variables/config
}
catch (Exception blah)
{
setStatus("Make sure you only entered valid numbers.",true);
return;
}
var progress = new Progress<MatchReport>(update =>
{
setStatus(update.message, update.error);
if(update.cube != null)
{
globalCube = update.cube;
}
});
ColorMatchTask = Task.Run(() => DoColorMatch_Worker(progress,testImage,referenceImage,aggregateWhat));
setStatus("Started...");
}
struct BatchTriple
{
public string testFile;
public string refFile;
public string LUTFile;
}
private async void DoColorMatchBatch()
{
string[] testfiles_unfiltered = Directory.GetFiles(batchTestFolder);
string[] reffiles_unfiltered = Directory.GetFiles(batchReferenceFolder);
List<BatchTriple> batchTriples = new List<BatchTriple>();
int set_index = 0;
BatchTriple tmpBatchTriple = new BatchTriple();
// Find image pairs
for(int k = 0; k < testfiles_unfiltered.Length; k++)
{
string baseFileName = Path.GetFileName(testfiles_unfiltered[k]);
string fullFileName = Path.GetFullPath(testfiles_unfiltered[k]);
string folder = Path.GetDirectoryName(fullFileName);
string baseFileNameNoExt = Path.GetFileNameWithoutExtension(fullFileName);
string extension = Path.GetExtension(fullFileName);
bool is_testfile = baseFileNameNoExt.EndsWith(batchTestSuffix);
if (is_testfile)
{
string corresponding_basename = baseFileNameNoExt.Substring(0,baseFileNameNoExt.Length-batchTestSuffix.Length) + batchReferenceSuffix;
// Give meaningful name to cube file
string target_cubename = baseFileNameNoExt.Substring(0, baseFileNameNoExt.Length - batchTestSuffix.Length) +
(lowPassMatching == LowPassMatching.REFERENCETOTEST ?"-lowpassreftotest("+lowPassEqualizeBlurRadius+"px"+
(lowPass1DRegrade == LowPass1DRegrade.HISTOGRAM ? ",histogram1Dregrade("+lowPass1DRegradePercentileSubdivisions+"subdiv,"+lowPass1DRegradeSmoothingRadius+"smthrad,"+lowPass1DRegradeSmoothingIntensity+"smth)" : "") +
")" : "")+
"-"+aggregateColorSpace.ToString()+
"-" + aggregateWhat.ToString()+
"-" + interpolationType.ToString()+
(postMatchSmoothing == PostMatchSmoothing.BOXBLUR3D ? "-postsmoothboxblur3d("+postMatchSmoothing3DBoxBlurRadius+"u,"+postMatchSmoothing3DBoxBlurStrength+"str,"+postMatchSmoothing3DBoxBlurLuminanceProtection+"lumprt)" : "") +
".cube";
target_cubename = batchOutputFolder.Trim(new char[] { "/"[0] }) + Path.DirectorySeparatorChar + target_cubename;
for (int l = 0; l < reffiles_unfiltered.Length; l++)
{
string baseFileName_ref = Path.GetFileName(reffiles_unfiltered[l]);
string fullFileName_ref = Path.GetFullPath(reffiles_unfiltered[l]);
string folder_ref = Path.GetDirectoryName(fullFileName_ref);
string baseFileNameNoExt_ref = Path.GetFileNameWithoutExtension(fullFileName_ref);
string extension_ref = Path.GetExtension(fullFileName_ref);
bool is_corresponding_file = baseFileNameNoExt_ref == corresponding_basename;
if (is_corresponding_file)
{
tmpBatchTriple.testFile = fullFileName;
tmpBatchTriple.refFile = fullFileName_ref;
tmpBatchTriple.LUTFile = target_cubename;
batchTriples.Add(tmpBatchTriple);
}
}
}
}
BatchProgress progressBox = new BatchProgress();
progressBox.Show();
for(int i = 0; i < batchTriples.Count; i++)
{
progressBox.AddOrUpdateProgressItem(i); // This isn't necessary but it makes sure that the order of the items in the batch progress is correct
}
Parallel.ForEach(batchTriples, (currentTriple,state,index) => {
Task ColorMatchTask;
Bitmap testImage = (Bitmap)Bitmap.FromFile(currentTriple.testFile);
Bitmap referenceImage = (Bitmap)Bitmap.FromFile(currentTriple.refFile);
var progress = new Progress<MatchReport>(update =>
{
progressBox.AddOrUpdateProgressItem((int)index,update.message);
//setStatus(update.message, update.error);
if (update.cube != null)
{
MakeLUT(update.cube, currentTriple.LUTFile);
//globalCube = update.cube;
}
});
ColorMatchTask = Task.Run(() => DoColorMatch_Worker(progress, testImage, referenceImage, aggregateWhat));
});
setStatus("Started...");
}
private CancellationTokenSource _cancelRegrade = new CancellationTokenSource();
//defunct
/*
private async void RegradeImage(float[,] matrix)
{
return;
/*
_cancelRegrade.Cancel();
_cancelRegrade = new CancellationTokenSource();
CancellationToken token = _cancelRegrade.Token;
float workGamma, testGamma;
try
{
// Get some config data or whatever
}
catch (Exception blah)
{
setStatus("Make sure you only entered valid numbers.", true);
return;
}
try
{
Bitmap tmp = new Bitmap(testImage);
BitmapSource result = await Task.Run(() => DoRegrade_Worker( tmp, token));
ImageTop.Source = result;
}
catch (OperationCanceledException)
{
//Nothing
}
*/
//}*/
// defunct
/*
private BitmapSource DoRegrade_Worker(float[,] matrix, float testGamma, float workGamma, Bitmap testImage,CancellationToken token)
{
return Helpers.BitmapToImageSource(testImage);
Bitmap regradedImage = new Bitmap(testImage);
int width = regradedImage.Width;
int height = regradedImage.Height;
float[] regradedImgData = new float[3];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
token.ThrowIfCancellationRequested();
Color pixelColor = regradedImage.GetPixel(x, y);
float[] workGammaPixel = new float[3]{
(float)(255 * Math.Pow((pixelColor.R / 255d), testGamma / workGamma)),
(float)(255 * Math.Pow((pixelColor.G / 255d), testGamma / workGamma)),
(float)(255 * Math.Pow((pixelColor.B / 255d), testGamma / workGamma))
};
regradedImgData[R] = Math.Max(0, Math.Min(255, workGammaPixel[R] * matrix[0, 0] + workGammaPixel[G] * matrix[0, 1] + workGammaPixel[B] * matrix[0, 2]));
regradedImgData[G] = Math.Max(0, Math.Min(255, workGammaPixel[R] * matrix[1, 0] + workGammaPixel[G] * matrix[1, 1] + workGammaPixel[B] * matrix[1, 2]));
regradedImgData[B] = Math.Max(0, Math.Min(255, workGammaPixel[R] * matrix[2, 0] + workGammaPixel[G] * matrix[2, 1] + workGammaPixel[B] * matrix[2, 2]));
regradedImage.SetPixel(x, y, Color.FromArgb(255,
(int)(Math.Pow(regradedImgData[R] / 255d, workGamma / displayGamma) * 255),
(int)(Math.Pow(regradedImgData[G] / 255d, workGamma / displayGamma) * 255),
(int)(Math.Pow(regradedImgData[B] / 255d, workGamma / displayGamma) * 255)));
}
}
token.ThrowIfCancellationRequested();
BitmapSource result = Helpers.BitmapToImageSource(regradedImage);
token.ThrowIfCancellationRequested();
result.Freeze();
return result;
}*/
private enum DOWNSCALE { DEFAULT,NN}
int outputValueCount = 32;
const int RCORD = 3;
const int GCORD = 4;
const int BCORD = 5;
struct AverageData
{
//public double totalR,totalG,totalB;
public Vector3 color;
public float divisor;
};
struct ColorPairData
{
//public byte R, G, B, RCORD, GCORD, BCORD;
public Vector3 color, cord, cordConverted;
public byte nearestQuadrantR, nearestQuadrantG, nearestQuadrantB;
};
/*internal unsafe struct Int32Buffer
{
private int _e00, _e02, _e03, _e04, _e05;
public ref int this[int index]
{
get
{
fixed (int* p = &_e00) return ref p[index];
}
}
}*/
// The actual colormatching.
private void DoColorMatch_Worker(IProgress<MatchReport> progress,Bitmap testImage, Bitmap referenceImage, AggregateVariable aggregateWhat)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
List<long> durations = new List<long>();
//TODO Sanity checks: rangeMax msut be > rangemin etc.
//Resize both images to resX,resY
//TODO: Do proper algorithm that ignores blown highlights
// TODO: Add "default linear" downscaler that corrects gamma before downscaling
// TODO: add special downscaler that picks only useful pixels
// TODO Add second special downscaler that isn't really a downscaler but one that picks most important colors including a slight average.
Bitmap resizedReferenceImage;
int resX = testImage.Width, resY = testImage.Height;
float[,,] testImgData = new float[resX, resY, 3];
float[,,] refImgData = new float[resX, resY, 3];
// 3D Histogram.
// Each possible color in a 256x256x256 RGB colorspace has one entry.
// Each entry is a list of int[] arrays, each containing an RGB color
// The [256,256,256] array represents the colors of the test image
// The int[] arrays represent corresponding colors in the reference image that were found in an identical position.
//List<int[]>[,,] histogram3D = new List<int[]>[256, 256, 256];
// Got tip:
/*
* ```cs
public struct Color
{
public byte R;
public byte G;
public byte B;
// rest of logic
}```
* */
resizedReferenceImage = new Bitmap(referenceImage, new Size(resX, resY));
//Bitmap debugBitmap = new Bitmap(referenceImage, new Size(resX, resY));
// Need to do new Bitmap() because it converts to ARGB, and we have consistency for the following loop, otherwise shit results.
// No need to do for reference image because it was already resized and thus regenerated.
ByteImage testBitmap = Helpers.BitmapToByteArray(new Bitmap(testImage));
ByteImage referenceBitmap = Helpers.BitmapToByteArray(resizedReferenceImage);
durations.Add(watch.ElapsedMilliseconds);
// Convert images into arrays for faster access (hopefully)
// If lowpass matching is enabled, do that in the same go.
if (lowPassMatching == LowPassMatching.REFERENCETOTEST)
{
float blurRadius = lowPassEqualizeBlurRadius;
int blurSizeX = (int)(resX / blurRadius);
int blurSizeY = (int)(resY / blurRadius);
ByteImage testBitmapBlurred = Helpers.ToGreyscale(Helpers.BitmapToByteArray(Helpers.ResizeBitmapHQ(Helpers.ResizeBitmapHQ(testImage, blurSizeX, blurSizeY),resX, resY)));
ByteImage referenceBitmapBlurred = Helpers.ToGreyscale(Helpers.BitmapToByteArray(Helpers.ResizeBitmapHQ(Helpers.ResizeBitmapHQ(referenceImage, blurSizeX, blurSizeY),resX, resY)));
FloatImage testBitmapBlurred1DRegradeToreferenceBitmap = new FloatImage(new float[0], 0, 0, 0, System.Drawing.Imaging.PixelFormat.DontCare); // just initializing so VS doesn't moan and bitch
if (lowPass1DRegrade == LowPass1DRegrade.HISTOGRAM)
{
testBitmapBlurred1DRegradeToreferenceBitmap = Helpers.Regrade1DHistogram(testBitmapBlurred, referenceBitmapBlurred, lowPass1DRegradePercentileSubdivisions,lowPass1DRegradeSmoothingRadius,lowPass1DRegradeSmoothingIntensity);
} else if (lowPass1DRegrade == LowPass1DRegrade.NONE)
{
testBitmapBlurred1DRegradeToreferenceBitmap = FloatImage.FromByteImage(testBitmapBlurred);
}
/*progress.Report(new MatchReport("Blurring test image...."));
ByteImage testBitmapBlurred = Helpers.BlurImage(testBitmap,50);
progress.Report(new MatchReport("Blurring reference image...."));
ByteImage referenceBitmapBlurred = Helpers.BlurImage(referenceBitmap, 50);*/
Helpers.ByteArrayToBitmap(testBitmapBlurred).Save("test1-test.png");
Helpers.ByteArrayToBitmap(referenceBitmapBlurred).Save("test2-ref.png");
Helpers.ByteArrayToBitmap(testBitmapBlurred1DRegradeToreferenceBitmap.ToByteImage()).Save("test3-1dregrade.png");
progress.Report(new MatchReport("Lowpass matching...."));
for (var x = 0; x < resX; x++)
{
for (var y = 0; y < resY; y++)
{
testImgData[x, y, B] = testBitmap[testBitmap.stride * y + x * 4];
testImgData[x, y, G] = testBitmap[testBitmap.stride * y + x * 4 + 1];
testImgData[x, y, R] = testBitmap[testBitmap.stride * y + x * 4 + 2];
// The -0.1 stuff is to avoid division by zero.
refImgData[x, y, B] = -0.1f+ (((float)referenceBitmap[referenceBitmap.stride * y + x * 4]+0.1f) / ((float)referenceBitmapBlurred[referenceBitmapBlurred.stride * y + x * 4] + 0.1f) * (testBitmapBlurred1DRegradeToreferenceBitmap[testBitmapBlurred1DRegradeToreferenceBitmap.stride * y + x * 4] + 0.1f));
refImgData[x, y, G] = -0.1f + (((float)referenceBitmap[referenceBitmap.stride * y + x * 4 + 1] + 0.1f) / ((float)referenceBitmapBlurred[referenceBitmapBlurred.stride * y + x * 4 + 1] + 0.1f) * (testBitmapBlurred1DRegradeToreferenceBitmap[testBitmapBlurred1DRegradeToreferenceBitmap.stride * y + x * 4 + 1] + 0.1f));
refImgData[x, y, R] = -0.1f + (((float)referenceBitmap[referenceBitmap.stride * y + x * 4 + 2] + 0.1f) / ((float)referenceBitmapBlurred[referenceBitmapBlurred.stride * y + x * 4 + 2] + 0.1f) * (testBitmapBlurred1DRegradeToreferenceBitmap[testBitmapBlurred1DRegradeToreferenceBitmap.stride * y + x * 4 + 2] + 0.1f));
/*debugBitmap.SetPixel(x, y, Color.FromArgb(testBitmap[testBitmap.stride * y + x * 3],
refImgData[x, y, G] = testBitmap[testBitmap.stride * y + x * 3 + 1],
refImgData[x, y, R] = testBitmap[testBitmap.stride * y + x * 3 + 2]));*/
}
}
}
else if (lowPassMatching == LowPassMatching.NONE)
{
for (var x = 0; x < resX; x++)
{
for (var y = 0; y < resY; y++)
{
testImgData[x, y, B] = testBitmap[testBitmap.stride * y + x * 4];
testImgData[x, y, G] = testBitmap[testBitmap.stride * y + x * 4 + 1];
testImgData[x, y, R] = testBitmap[testBitmap.stride * y + x * 4 + 2];
refImgData[x, y, B] = referenceBitmap[referenceBitmap.stride * y + x * 4];
refImgData[x, y, G] = referenceBitmap[referenceBitmap.stride * y + x * 4 + 1];
refImgData[x, y, R] = referenceBitmap[referenceBitmap.stride * y + x * 4 + 2];
/*debugBitmap.SetPixel(x, y, Color.FromArgb(testBitmap[testBitmap.stride * y + x * 3],
refImgData[x, y, G] = testBitmap[testBitmap.stride * y + x * 3 + 1],
refImgData[x, y, R] = testBitmap[testBitmap.stride * y + x * 3 + 2]));*/
}
}
}
//debugBitmap.Save("test2.png");
durations.Add(watch.ElapsedMilliseconds);
// this will save which cube parts the algo should even bother to loop through. will set bool to true for that segment if anything was found in there.
// Most of the final cube will always be empty anyway, we can use this to our advantage.
bool[,,] preCube = new bool[outputValueCount, outputValueCount, outputValueCount];
int steps = outputValueCount - 1;
float stepSize = 255 / (float)steps;
byte stepR, stepG, stepB;
int trueStepR, trueStepG, trueStepB;
ColorPairData thisPointLinear = new ColorPairData();
int rAround, gAround, bAround;
int pixelCount = resX * resY;
ColorPairData[] collectCubeLinear = new ColorPairData[pixelCount];
int collectCubeLinearIndex = 0;
// Build full histogram
for (var y = 0; y < resY; y++)
{
for (var x = 0; x < resX; x++)
{
// set preCube (massive speedup later)
stepR = (byte)Math.Round(testImgData[x, y, R] / stepSize);
stepG = (byte)Math.Round(testImgData[x, y, G] / stepSize);
stepB = (byte)Math.Round(testImgData[x, y, B] / stepSize);
thisPointLinear.cord.X = testImgData[x, y, R];
thisPointLinear.cord.Y = testImgData[x, y, G];
thisPointLinear.cord.Z = testImgData[x, y, B];
if (aggregateColorSpace == AggregateColorSpace.CIELAB)
{
/*
tmpRGB.R = refImgData[x, y, R];
tmpRGB.G = refImgData[x, y, G];
tmpRGB.B = refImgData[x, y, B];
tmpLab = tmpRGB.To<Lab>();
thisPointLinear.color.X = (float)tmpLab.L;
thisPointLinear.color.Y = (float)tmpLab.A;
thisPointLinear.color.Z = (float)tmpLab.B;
tmpRGB.R = thisPointLinear.cord.X;
tmpRGB.G = thisPointLinear.cord.Y;
tmpRGB.B = thisPointLinear.cord.Z;
tmpLab = tmpRGB.To<Lab>();
thisPointLinear.cordConverted.X = (float)tmpLab.L;
thisPointLinear.cordConverted.Y = (float)tmpLab.A;
thisPointLinear.cordConverted.Z = (float)tmpLab.B;
*/
thisPointLinear.color.X = refImgData[x, y, R];
thisPointLinear.color.Y = refImgData[x, y, G];
thisPointLinear.color.Z = refImgData[x, y, B];
thisPointLinear.cordConverted = Helpers.sRGBToCIELab(thisPointLinear.cord);
thisPointLinear.color = Helpers.sRGBToCIELab(thisPointLinear.color);
} else if (aggregateColorSpace == AggregateColorSpace.CIELCHAB)
{
/*
tmpRGB.R = refImgData[x, y, R];
tmpRGB.G = refImgData[x, y, G];
tmpRGB.B = refImgData[x, y, B];
tmpLab = tmpRGB.To<Lab>();
thisPointLinear.color.X = (float)tmpLab.L;
thisPointLinear.color.Y = (float)tmpLab.A;
thisPointLinear.color.Z = (float)tmpLab.B;
tmpRGB.R = thisPointLinear.cord.X;
tmpRGB.G = thisPointLinear.cord.Y;
tmpRGB.B = thisPointLinear.cord.Z;
tmpLab = tmpRGB.To<Lab>();
thisPointLinear.cordConverted.X = (float)tmpLab.L;
thisPointLinear.cordConverted.Y = (float)tmpLab.A;
thisPointLinear.cordConverted.Z = (float)tmpLab.B;
*/
thisPointLinear.color.X = refImgData[x, y, R];
thisPointLinear.color.Y = refImgData[x, y, G];
thisPointLinear.color.Z = refImgData[x, y, B];
thisPointLinear.cordConverted = Helpers.sRGBToCIELChab(thisPointLinear.cord);
thisPointLinear.color = Helpers.sRGBToCIELChab(thisPointLinear.color);
} else if(aggregateColorSpace == AggregateColorSpace.SRGB)
{
thisPointLinear.cordConverted = thisPointLinear.cord;
thisPointLinear.color.X = refImgData[x, y, R];
thisPointLinear.color.Y = refImgData[x, y, G];
thisPointLinear.color.Z = refImgData[x, y, B];
}
if(aggregateWhat == AggregateVariable.VECTOR)
{
thisPointLinear.color = thisPointLinear.color - thisPointLinear.cordConverted;
}
/*thisPointLinear.R = refImgData[x, y, R];
thisPointLinear.G = refImgData[x, y, G];
thisPointLinear.B = refImgData[x, y, B];
thisPointLinear.RCORD = testImgData[x, y, R];
thisPointLinear.GCORD = testImgData[x, y, G];
thisPointLinear.BCORD = testImgData[x, y, B];*/
thisPointLinear.nearestQuadrantR = stepR;
thisPointLinear.nearestQuadrantG = stepG;
thisPointLinear.nearestQuadrantB = stepB;
collectCubeLinear[collectCubeLinearIndex++] = thisPointLinear;
}
progress.Report(new MatchReport("Building histogram [" + ((float)y*resX/pixelCount*100).ToString("#.##") + "%] "));
}
durations.Add(watch.ElapsedMilliseconds);
// Build 32x32x32 cube data ( TODO later make the precision flexible)
AverageData[,,] tmpCube = new AverageData[outputValueCount, outputValueCount, outputValueCount];
UInt64 count = 0;
float weight;
float tmp1, tmp2, tmp3,
tmp1sq,tmp2sq,tmp3sq;
int redOctant, greenOctant, blueOctant;
float sqrtOf3 = (float)Math.Sqrt(3);
AverageData tmpAverageData = new AverageData();
bool simpleWeight = false;
float simpleWeightValue = sqrtOf3 - 1;
Vector3 cordNormalized;
// compiler explorer. check
// This loop is currently the bottleneck. Edit: Is it still?
foreach (ColorPairData collectCubeLinearHere in collectCubeLinear)
{
redOctant = collectCubeLinearHere.nearestQuadrantR;
greenOctant = collectCubeLinearHere.nearestQuadrantG;
blueOctant = collectCubeLinearHere.nearestQuadrantB;
/*multiplyHelper.X = collectCubeLinearHere.RCORD;
multiplyHelper.Y = collectCubeLinearHere.GCORD;
multiplyHelper.Z = collectCubeLinearHere.BCORD;*/
cordNormalized = collectCubeLinearHere.cord / stepSize;
/*rCordNormalized = collectCubeLinearHere.RCORD / stepSize;
gCordNormalized = collectCubeLinearHere.GCORD / stepSize;
bCordNormalized = collectCubeLinearHere.BCORD / stepSize;*/
count++;
for (rAround = -1; rAround <= 1; rAround++)
{
if (cordNormalized.X > redOctant && rAround == -1) continue; //major speed improvement but slight quality degradation
if (cordNormalized.X < redOctant && rAround == 1) continue; //major speed improvement but slight quality degradation
trueStepR = Math.Max(0, Math.Min(steps, redOctant + rAround));
tmp1 = (trueStepR - cordNormalized.X);
tmp1sq = tmp1 * tmp1;
for (gAround = -1; gAround <= 1; gAround++)
{
if (cordNormalized.Y > greenOctant && gAround == -1) continue; //major speed improvement but slight quality degradation
if (cordNormalized.Y < greenOctant && gAround == 1) continue; //major speed improvement but slight quality degradation
trueStepG = Math.Max(0, Math.Min(steps, greenOctant + gAround));
tmp2 = (trueStepG - cordNormalized.Y);
tmp2sq = tmp2 * tmp2;
for (bAround = -1; bAround <= 1; bAround++)
{
if (cordNormalized.Z > blueOctant && bAround == -1) continue; //major speed improvement but slight quality degradation
if (cordNormalized.Z < blueOctant && bAround == 1) continue; //major speed improvement but slight quality degradation
trueStepB = Math.Max(0, Math.Min(steps, blueOctant + bAround));
tmp3 = (trueStepB - cordNormalized.Z);
tmp3sq = tmp3 * tmp3;
if (simpleWeight)
{
weight = simpleWeightValue;
simpleWeight = false;
} else
{
// 5- Euklidian distance self-multiply
// can pretty safely skip the SQRT part actually, my experiments have shown that it makes pretty much zero visual difference
/*weight = Math.Max(0, sqrtOf3 - (float)Math.Sqrt(
(tmp1 * tmp1
+ tmp2 * tmp2
+ tmp3 * tmp3)
));*/
weight = Math.Max(0, 3 - (
(tmp1sq
+ tmp2sq
+ tmp3sq)
));
}
// TODO MEDIAN METHOD + option to only accept places that have 3+ result colors + interpolation to prettify
tmpCube[trueStepR, trueStepG, trueStepB].color += collectCubeLinearHere.color * weight;
tmpCube[trueStepR, trueStepG, trueStepB].divisor += weight;
//tmpAverageData.valueR = (float)tmpAverageData.data.X / tmpAverageData.divisor;
//tmpAverageData.valueG = (float)tmpAverageData.data.Y / tmpAverageData.divisor;
//tmpAverageData.valueB = (float)tmpAverageData.data.Z / tmpAverageData.divisor;
}
}
}
if(count%200000 == 0)
{
progress.Report(new MatchReport("Building cube [" + (((double)count/(pixelCount))*100).ToString("#.##") + "%] "));
}
}
durations.Add(watch.ElapsedMilliseconds);
FloatColor[,,] cube = new FloatColor[outputValueCount, outputValueCount, outputValueCount];
FloatColor tmpFloatColor;
tmpFloatColor.color = new Vector3(0, 0, 0);
Vector3 NaNColor = new Vector3 {X=float.NaN,Y=float.NaN,Z=float.NaN };
// transfer tmpCube to normal cube
// May seem slow from the code but actually only takes about 1 ms, it's ridiculously fast.
AverageData averageHelper;
Vector3 absCoord = new Vector3(0, 0, 0);
for (redOctant = 0; redOctant<outputValueCount; redOctant++)
{
absCoord.X = redOctant * stepSize;
for (greenOctant = 0; greenOctant < outputValueCount; greenOctant++)
{
absCoord.Y = greenOctant * stepSize;
for (blueOctant = 0; blueOctant < outputValueCount; blueOctant++)
{
absCoord.Z = blueOctant * stepSize;
tmpAverageData = tmpCube[redOctant, greenOctant, blueOctant];
if (tmpAverageData.divisor == 0)
{
// Do this only if you skipped the arounds earlier. Maybe make this a "fast algo" option.
// This part is pretty quick though, but it still doesn't eliminate artifacts completely.
// Also don't do this if interpolation is activated, as it will (hopefully) provide more reasonable values than this.
if(interpolationType == InterpolationType.NONE) {
averageHelper = new AverageData();
for (rAround = -1; rAround <= 1; rAround++)
{
trueStepR = Math.Max(0, Math.Min(steps, redOctant + rAround));
for (gAround = -1; gAround <= 1; gAround++)
{
trueStepG = Math.Max(0, Math.Min(steps, greenOctant + gAround));
for (bAround = -1; bAround <= 1; bAround++)
{
trueStepB = Math.Max(0, Math.Min(steps, blueOctant + bAround));
averageHelper.color += tmpCube[trueStepR, trueStepG, trueStepB].color;
averageHelper.divisor += tmpCube[trueStepR, trueStepG, trueStepB].divisor;
}
}
}
if(aggregateWhat == AggregateVariable.ABSOLUTE)
{
tmpFloatColor.color = averageHelper.color / averageHelper.divisor;
} else if(aggregateWhat == AggregateVariable.VECTOR)
{
//tmpFloatColor.color = absCoord + (averageHelper.color / averageHelper.divisor); I had it like this and I guess it worked but the "back to absolute" seems wrong bc this is done later...
tmpFloatColor.color = averageHelper.color / averageHelper.divisor;
}
cube[redOctant, greenOctant, blueOctant] = tmpFloatColor;
} else
{
cube[redOctant, greenOctant, blueOctant].color = NaNColor;
}
}
else
{
/*tmpFloatColor.color.X = (float)tmpAverageData.color.X / tmpAverageData.divisor;
tmpFloatColor.color.Y = (float)tmpAverageData.color.Y / tmpAverageData.divisor;
tmpFloatColor.color.Z = (float)tmpAverageData.color.Z / tmpAverageData.divisor;*/
/*
if (aggregateWhat == AggregateVariable.ABSOLUTE)
{
cube[redQuadrant, greenQuadrant, blueQuadrant].color = tmpAverageData.color / tmpAverageData.divisor;
}
else if (aggregateWhat == AggregateVariable.VECTOR)
{
cube[redQuadrant, greenQuadrant, blueQuadrant].color = absCoord + tmpAverageData.color / tmpAverageData.divisor;
}*/ // This whole thing comes later now (transfer to absolute)
cube[redOctant, greenOctant, blueOctant].color = tmpAverageData.color / tmpAverageData.divisor;
}
}
}
}
durations.Add(watch.ElapsedMilliseconds);
// Interpolation
if (interpolationType == InterpolationType.DUALLINEAR || interpolationType == InterpolationType.SINGLELINEAR)
{
int unsolvedNaNs = 0;
bool thisIsNaN = false;
/* Possible directions for a hint: (2 dimensional example)
* X - X - X
*
* - X X X -
*
* X X O X X
*
* - X X X -
*
* X - X - X
*
* Abstract explanation attempt:
* A hint is if either of these is true:
* - Use any combination of -1 0 and 1 in the 3 dimensions.
* - Take a second value that is the same vector, but times 2. 0 with stay 0, -1 will become -2 etc.
*/
// Prepare directions
List<Vector3> directionsList = new List<Vector3>();
Vector3 currentDirection = new Vector3();
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
currentDirection.X = x;
currentDirection.Y = y;
currentDirection.Z = z;
directionsList.Add(currentDirection);
}
}
}
Vector3[] directions = directionsList.ToArray();
Vector3[] directionsX2 = new Vector3[directions.Length];
for(int i=0;i<directions.Length;i++)
{
directionsX2[i] = directions[i] * 2; // Add second item in same direction
}