-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
807 lines (687 loc) · 37 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using win = System.Windows;
using System.Drawing;
using controls = System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using media = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Threading;
using Be.IO;
using System.Diagnostics;
namespace ChannelMixMatcher
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : win.Window
{
bool initialized = false;
public MainWindow()
{
InitializeComponent();
initialized = true;
updateIter();
Experiments();
}
private void Experiments()
{
Stopwatch sw = new Stopwatch();
sw.Start();
int pixelCount = 50000;
for(int i = 0; i < pixelCount; i++)
{
for (int ii = 0; ii < pixelCount; ii++)
{
}
}
sw.Stop();
win.MessageBox.Show((sw.ElapsedMilliseconds/1000).ToString());
/*double[] Rout = new double[3] { 1,1,1};
double[] Rin = new double[3] {1,0.5,0.5 };
double[] Gin = new double[3] {0.5,1,0.5 };
double[] Bin = new double[3] {0.5,0.5,1 };
//double[] Rin = new double[3] {1,0,0 };
//double[] Gin = new double[3] {0,1,0 };
//double[] Bin = new double[3] {0,0,1 };
double[] coeffs = Helpers.findCoefficients(Rout, Rin, Gin, Bin);
double[] check = new double[3];
for(int i = 0; i < 3; i++)
{
check[i] = coeffs[0] * Rin[i] + coeffs[1] * Gin[i] + coeffs[2] * Bin[i];
}
win.MessageBox.Show(coeffs.ToString());*/
}
const int R = 0;
const int G = 1;
const int B = 2;
private Bitmap testImage = null;
private Bitmap regradedImage = 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 Task ColorMatchTask;
// 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;
}
float rangeMin, rangeMax, sliderRangeMin, sliderRangeMax, precision, workGamma, testGamma, refGamma;
int subdiv, resX, resY;
DOWNSCALE downscaleMethod = DOWNSCALE.DEFAULT;
NormalizationMethods.Method normalizationMethod;
try
{
rangeMin = float.Parse(MatchFrom_txt.Text);
rangeMax = float.Parse(MatchTo_txt.Text);
sliderRangeMin = float.Parse(ChannelMixSliderFrom_txt.Text);
sliderRangeMax = float.Parse(ChannelMixSliderTo_txt.Text);
precision = float.Parse(Precision_txt.Text);
workGamma = float.Parse(WorkGamma_txt.Text);
testGamma = float.Parse(TestImageGamma_txt.Text);
refGamma = float.Parse(ReferenceImageGamma_txt.Text);
subdiv = int.Parse(Subdiv_txt.Text);
resX = int.Parse(MatchResX_txt.Text);
resY = int.Parse(MatchResY_txt.Text);
if (useLabColorVarietyDownscale_radio.IsChecked == true)
{
downscaleMethod = DOWNSCALE.LABCOLORVARIETY;
}
else if (useNNDownscale_radio.IsChecked == true)
{
downscaleMethod = DOWNSCALE.NN;
}
else if(useDefaultDownscale_radio.IsChecked == true)
{
downscaleMethod = DOWNSCALE.DEFAULT;
} else
{
downscaleMethod = DOWNSCALE.DEFAULT;
}
if (useRelativeNormalization_radio.IsChecked == true)
{
normalizationMethod = NormalizationMethods.Method.RELATIVE;
}
else if (useAbsoluteNormalization_radio.IsChecked == true)
{
normalizationMethod = NormalizationMethods.Method.ABSOLUTE;
}
else if (useSuperRelativeNormalization_radio.IsChecked == true)
{
normalizationMethod = NormalizationMethods.Method.SUPERRELATIVE;
}
else
{
normalizationMethod = NormalizationMethods.Method.RELATIVE;
}
}
catch (Exception blah)
{
setStatus("Make sure you only entered valid numbers.",true);
return;
}
var progress = new Progress<MatchReport>(update =>
{
setStatus(update.message,update.error);
// Update matrix
if (update.matching_range != null)
{
SetSliderRanges(update.matching_range);
}
if (update.best_matrix != null)
{
SetSlidersToMatrix(update.best_matrix);
RegradeImage(update.best_matrix);
}
});
ColorMatchTask = Task.Run(() => DoColorMatch_Worker(progress,rangeMin,rangeMax,sliderRangeMin,sliderRangeMax,precision,workGamma,testGamma,refGamma,subdiv,resX,resY,testImage,referenceImage,downscaleMethod,normalizationMethod));
setStatus("Started...");
}
private void SetSliderRanges(float[,] ranges)
{
slide_RtoR.IsSelectionRangeEnabled = true;
slide_GtoR.IsSelectionRangeEnabled = true;
slide_BtoR.IsSelectionRangeEnabled = true;
slide_RtoG.IsSelectionRangeEnabled = true;
slide_GtoG.IsSelectionRangeEnabled = true;
slide_BtoG.IsSelectionRangeEnabled = true;
slide_RtoB.IsSelectionRangeEnabled = true;
slide_GtoB.IsSelectionRangeEnabled = true;
slide_BtoB.IsSelectionRangeEnabled = true;
slide_RtoR.SelectionStart = ranges[0, 0];
slide_RtoR.SelectionEnd = ranges[0, 1];
slide_GtoR.SelectionStart = ranges[1, 0];
slide_GtoR.SelectionEnd = ranges[1, 1];
slide_BtoR.SelectionStart = ranges[2, 0];
slide_BtoR.SelectionEnd = ranges[2, 1];
slide_RtoG.SelectionStart = ranges[3, 0];
slide_RtoG.SelectionEnd = ranges[3, 1];
slide_GtoG.SelectionStart = ranges[4, 0];
slide_GtoG.SelectionEnd = ranges[4, 1];
slide_BtoG.SelectionStart = ranges[5, 0];
slide_BtoG.SelectionEnd = ranges[5, 1];
slide_RtoB.SelectionStart = ranges[6, 0];
slide_RtoB.SelectionEnd = ranges[6, 1];
slide_GtoB.SelectionStart = ranges[7, 0];
slide_GtoB.SelectionEnd = ranges[7, 1];
slide_BtoB.SelectionStart = ranges[8, 0];
slide_BtoB.SelectionEnd = ranges[8, 1];
}
private void SetSlidersToMatrix(float[,] matrix)
{
slide_RtoR.Value = matrix[0, 0];
slide_GtoR.Value = matrix[0, 1];
slide_BtoR.Value = matrix[0, 2];
slide_RtoG.Value = matrix[1, 0];
slide_GtoG.Value = matrix[1, 1];
slide_BtoG.Value = matrix[1, 2];
slide_RtoB.Value = matrix[2, 0];
slide_GtoB.Value = matrix[2, 1];
slide_BtoB.Value = matrix[2, 2];
}
private CancellationTokenSource _cancelRegrade = new CancellationTokenSource();
private async void RegradeImage(float[,] matrix)
{
_cancelRegrade.Cancel();
_cancelRegrade = new CancellationTokenSource();
CancellationToken token = _cancelRegrade.Token;
float workGamma, testGamma;
try
{
workGamma = float.Parse(WorkGamma_txt.Text);
testGamma = float.Parse(TestImageGamma_txt.Text);
}
catch (Exception blah)
{
setStatus("Make sure you only entered valid numbers.", true);
return;
}
if(testImage == null)
{
// Can't regrade an image that isn't loaded!
return;
}
try
{
Bitmap tmp = new Bitmap(testImage);
BitmapSource result = await Task.Run(() => DoRegrade_Worker(matrix, testGamma, workGamma, tmp, token));
ImageTop.Source = result;
}
catch (OperationCanceledException)
{
//Nothing
}
}
private BitmapSource DoRegrade_Worker(float[,] matrix, float testGamma, float workGamma, Bitmap testImage,CancellationToken token)
{
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,LABCOLORVARIETY}
// The actual colormatching.
private void DoColorMatch_Worker(IProgress<MatchReport> progress, float rangeMin, float rangeMax, float sliderRangeMin, float sliderRangeMax, float precision, float workGamma, float testGamma, float refGamma, int subdiv, int resX, int resY, Bitmap testImage, Bitmap referenceImage, DOWNSCALE downscaleMethod, NormalizationMethods.Method normalizationMethod)
{
//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 resizedTestImage, resizedReferenceImage;
switch(downscaleMethod)
{
case DOWNSCALE.LABCOLORVARIETY:
resizedTestImage = Helpers.ResizeBitmapNN(testImage, resX, resY);
resizedReferenceImage = Helpers.ResizeBitmapNN(referenceImage, resX, resY);
break;
case DOWNSCALE.NN:
resizedTestImage = Helpers.ResizeBitmapNN(testImage, resX, resY);
resizedReferenceImage = Helpers.ResizeBitmapNN(referenceImage, resX, resY);
break;
case DOWNSCALE.DEFAULT:
default:
resizedTestImage = new Bitmap(testImage, new Size(resX, resY));
resizedReferenceImage = new Bitmap(referenceImage, new Size(resX, resY));
break;
}
float[,,] testImgData = new float[resX, resY, 3];
float[,,] refImgData = new float[resX, resY, 3];
// Convert images into arrays for faster access (hopefully)
for(var x = 0; x < resX; x++)
{
for (var y = 0; y < resY; y++)
{
Color testPixel = resizedTestImage.GetPixel(x, y);
testImgData[x, y, R] = (float)(255*Math.Pow(((double)testPixel.R / 255d), testGamma/workGamma));
testImgData[x, y, G] = (float)(255*Math.Pow(((double)testPixel.G / 255d), testGamma/workGamma));
testImgData[x, y, B] = (float)(255*Math.Pow(((double)testPixel.B / 255d), testGamma/workGamma));
Color referencePixel = resizedReferenceImage.GetPixel(x, y);
refImgData[x, y, R] = (float)(255*Math.Pow(((double)referencePixel.R / 255d), refGamma/workGamma));
refImgData[x, y, G] = (float)(255*Math.Pow(((double)referencePixel.G / 255d), refGamma/workGamma));
refImgData[x, y, B] = (float)(255*Math.Pow(((double)referencePixel.B / 255d), refGamma/workGamma));
}
}
// Step Size for individual sliders
// Need subdiv-1 because : | segment 1 | segment 2 | segment 3 | , where the "|" represents the testing points and the segments the stepsize
float stepSize = (rangeMax - rangeMin)/(subdiv-1);
float stepSizeNext = stepSize;
// Nest all sliders (this is where it gets computationally intensive very quick.
double count = 0;
double skipped = 0;
float[] testColor = new float[3];
float[] refColor = new float[3];
float[] testMatrixed = new float[3];
//float multiplier,multiplierRef;
double average_diff;
double best_average_diff = double.PositiveInfinity;
double? tmp_diff;
float[,] current_matrix = new float[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };
float[,] best_matrix = new float[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };
float[,] matchRanges = new float[9, 2] {
{ rangeMin, rangeMax},
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax },
{ rangeMin, rangeMax } };
int iteration = 0;
while (stepSize > precision)
{
stepSize = stepSizeNext;
progress.Report(new MatchReport(
"Colormatching... iteration "+(iteration+1).ToString()+", stepSize "+stepSize.ToString()+", desired precision "+precision.ToString(),
false,
null,
matchRanges
));
bool update_matrix = false;
for (int iRtoR = 0; iRtoR < subdiv; iRtoR++)
{
for (int iGtoR = 0; iGtoR < subdiv; iGtoR++)
{
for (int iBtoR = 0; iBtoR < subdiv; iBtoR++)
{
for (int iRtoG = 0; iRtoG < subdiv; iRtoG++)
{
for (int iGtoG = 0; iGtoG < subdiv; iGtoG++)
{
for (int iBtoG = 0; iBtoG < subdiv; iBtoG++)
{
for (int iRtoB = 0; iRtoB < subdiv; iRtoB++)
{
for (int iGtoB = 0; iGtoB < subdiv; iGtoB++)
{
for (int iBtoB = 0; iBtoB < subdiv; iBtoB++)
{
double total_diff = 0;
Int64 count_diff = 0; //How many diff-values were added to total_diff, so that an average can be calculated
// Calculate matrix
current_matrix = new float[3, 3] {
{ iRtoR*stepSize+matchRanges[0,0], iGtoR*stepSize+matchRanges[1,0], iBtoR*stepSize+matchRanges[2,0] },
{ iRtoG*stepSize+matchRanges[3,0], iGtoG*stepSize+matchRanges[4,0], iBtoG*stepSize+matchRanges[5,0] },
{ iRtoB*stepSize+matchRanges[6,0], iGtoB*stepSize+matchRanges[7,0], iBtoB*stepSize+matchRanges[8,0] } };
for (var x = 0; x < resX; x++)
{
for (var y = 0; y < resX; y++)
{
// TODO Alternate difference algorithm that doesn't calculate average difference, but peak difference instead. might help with a few things.
count++;
// Apply matrix
testMatrixed[R] = testImgData[x, y, R] * current_matrix[0, 0] + testImgData[x, y, G] * current_matrix[0, 1] + testImgData[x, y, B] * current_matrix[0, 2];
testMatrixed[G] = testImgData[x, y, R] * current_matrix[1, 0] + testImgData[x, y, G] * current_matrix[1, 1] + testImgData[x, y, B] * current_matrix[1, 2];
testMatrixed[B] = testImgData[x, y, R] * current_matrix[2, 0] + testImgData[x, y, G] * current_matrix[2, 1] + testImgData[x, y, B] * current_matrix[2, 2];
// Diff Methods.
switch (normalizationMethod)
{
case NormalizationMethods.Method.ABSOLUTE:
tmp_diff = NormalizationMethods.DiffRelative(testMatrixed, refImgData, x, y);
break;
case NormalizationMethods.Method.SUPERRELATIVE:
tmp_diff = NormalizationMethods.DiffSuperRelative(testMatrixed, refImgData, x, y);
break;
default:
case NormalizationMethods.Method.RELATIVE:
tmp_diff = NormalizationMethods.DiffAbsolute(testMatrixed, refImgData, x, y);
break;
}
if (!tmp_diff.HasValue)
{
skipped++;
continue;
}
else
{
total_diff += tmp_diff.Value;
count_diff++;
}
}
}
// Calculate average diff for this particular matrix
// If it's better than the one saved as best_average_diff,
// it overwrites it and this matrix takes the place of best_matrix
// TODO PSNR (?) instead of average as option
average_diff = total_diff / count_diff;
if (average_diff < best_average_diff)
{
best_average_diff = average_diff;
best_matrix = current_matrix;
update_matrix = true;
//progress.Report(new MatchReport(count.ToString("#,##0") + ", best average diff: " + best_average_diff.ToString(), false, current_matrix));
}
}
}
}
}
}
progress.Report(new MatchReport(count.ToString("#,##0") + ", best average diff: " + best_average_diff.ToString(),false,update_matrix ? best_matrix : null)); // Can't put it further in or it won't update at all. Dunno why. It gets called, but doesn't update UI. PC freezes tho, maybe performance/priority problem?
update_matrix = false;
}
}
}
}
iteration++;
// For each new iteration, the current best_matrix +- current stepsize will be used, and that range again divided by subdiv.
// TODO: Idea: Make individual stepsize for each of the 9 matrix elements. Why? Because that way whenever the best determined setting is on the outermost of the 4 parts,
// we can keep a higher border/buffer for the next iteration. In other words, whenever the best value settles on one of the outer values, more buffer will be kept around that border,
// or the stepsize will remain constant for that one, so that it can settle towards something more reasonable.
matchRanges = new float[9, 2] {
{ best_matrix[0,0]-stepSize, best_matrix[0,0]+stepSize},
{ best_matrix[0,1]-stepSize, best_matrix[0,1]+stepSize},
{ best_matrix[0,2]-stepSize, best_matrix[0,2]+stepSize},
{ best_matrix[1,0]-stepSize, best_matrix[1,0]+stepSize},
{ best_matrix[1,1]-stepSize, best_matrix[1,1]+stepSize},
{ best_matrix[1,2]-stepSize, best_matrix[1,2]+stepSize},
{ best_matrix[2,0]-stepSize, best_matrix[2,0]+stepSize},
{ best_matrix[2,1]-stepSize, best_matrix[2,1]+stepSize},
{ best_matrix[2,2]-stepSize, best_matrix[2,2]+stepSize}};
// Need subdiv-1 because : | segment 1 | segment 2 | segment 3 | , where the "|" represents the testing points and the segments the stepsize
stepSizeNext = stepSize * 2 / (subdiv -1);
}
progress.Report(new MatchReport(count.ToString("#,##0") + ", best average diff: " + best_average_diff.ToString()));
}
private media.Brush redBackground = new media.SolidColorBrush(media.Color.FromRgb(255,0,0));
private media.Brush transparentBackground = new media.SolidColorBrush(media.Color.FromArgb(0,0,0,0));
private media.Brush whiteText = new media.SolidColorBrush(media.Color.FromRgb(255,255,255));
private media.Brush blackText = new media.SolidColorBrush(media.Color.FromRgb(0,0,0));
private void setStatus(string status, bool error=false)
{
Status_txt.Text = status;
if (error)
{
Status_txt.Background = redBackground;
Status_txt.Foreground = whiteText;
} else
{
Status_txt.Background = transparentBackground;
Status_txt.Foreground = blackText;
}
}
private void updateIter_Change(object sender, win.RoutedEventArgs e)
{
updateIter();
}
private void updateIter()
{
if (!initialized)
{
return;
}
try
{
int resX = int.Parse(MatchResX_txt.Text);
int resY = int.Parse(MatchResY_txt.Text);
int subdiv = int.Parse(Subdiv_txt.Text);
double iterSteps = (double)Math.Pow(subdiv, 9) * resX * resY;
IterSteps_txt.Text = iterSteps.ToString("#,##0");
}
catch (Exception blah)
{
try
{
IterSteps_txt.Text = "N/A";
}
catch (Exception blah2)
{
// nothing
}
}
}
private void BtnLoadCHA_Click(object sender, win.RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Photoshop RGB Channel Mixer Preset (.cha)|*.cha";
float[,] PSmatrix = new float[3,3];
int[] useless = new int[3]; // I think these are for CMYK
int[] constant = new int[3];
if (ofd.ShowDialog() == true)
{
string filename = ofd.FileName;
using(FileStream fs = File.Open(filename, FileMode.Open))
{
using (BeBinaryReader binReader = new BeBinaryReader(fs))
{
uint version = binReader.ReadUInt16();
uint monochrome = binReader.ReadUInt16();
PSmatrix[0, 0] = binReader.ReadInt16() / 100f;
PSmatrix[0, 1] = binReader.ReadInt16() / 100f;
PSmatrix[0, 2] = binReader.ReadInt16() / 100f;
useless[0] = binReader.ReadInt16();
constant[0] = binReader.ReadInt16();
PSmatrix[1, 0] = binReader.ReadInt16() / 100f;
PSmatrix[1, 1] = binReader.ReadInt16() / 100f;
PSmatrix[1, 2] = binReader.ReadInt16() / 100f;
useless[1] = binReader.ReadInt16();
constant[1] = binReader.ReadInt16();
PSmatrix[2, 0] = binReader.ReadInt16() / 100f;
PSmatrix[2, 1] = binReader.ReadInt16() / 100f;
PSmatrix[2, 2] = binReader.ReadInt16() / 100f;
useless[2] = binReader.ReadInt16();
constant[2] = binReader.ReadInt16();
}
}
setStatus(Helpers.matrixToString<float>(PSmatrix));
SetSlidersToMatrix(PSmatrix);
RegradeImage(PSmatrix);
}
}
private float[,] slidersToMatrix()
{
return new float[3, 3]
{
{(float)slide_RtoR.Value,(float)slide_GtoR.Value,(float)slide_BtoR.Value},
{(float)slide_RtoG.Value,(float)slide_GtoG.Value,(float)slide_BtoG.Value },
{(float)slide_RtoB.Value,(float)slide_GtoB.Value,(float)slide_BtoB.Value }
};
}
private float[,] matrixInvert(float[,] matrix) {
double[] result = matrixInvert(new double[9] { matrix[0,0], matrix[0, 1], matrix[0, 2], matrix[1, 0], matrix[1, 1], matrix[1, 2], matrix[2, 0], matrix[2, 1], matrix[2, 2] });
float[,] retVal = new float[3, 3] { { (float)result[0], (float)result[1], (float)result[2] },{ (float)result[3] , (float)result[4] , (float)result[5] },{ (float)result[6] , (float)result[7] , (float)result[8] } };
return retVal;
}
private double[] matrixInvert(double[] matrix)
{
double[][] twoDimMatrix = new double[3][];
twoDimMatrix[0] = new double[3] { matrix[0], matrix[1], matrix[2] };
twoDimMatrix[1] = new double[3] { matrix[3], matrix[4], matrix[5] };
twoDimMatrix[2] = new double[3] { matrix[6], matrix[7], matrix[8] };
double[][] invertedMatrix;
try
{
invertedMatrix = MatrixOps.MatrixInverse(twoDimMatrix);
}
catch (Exception e)
{
// Inversion not possible (not all values filled correctly yet?)
invertedMatrix = MatrixOps.MatrixCreate(3, 3);
}
return new double[9] {
invertedMatrix[0][0],invertedMatrix[0][1],invertedMatrix[0][2],
invertedMatrix[1][0],invertedMatrix[1][1],invertedMatrix[1][2],
invertedMatrix[2][0],invertedMatrix[2][1],invertedMatrix[2][2]
};
}
// TODO Add automatic scaling if the user wants it.
private void BtnSaveCHA_Click(object sender, win.RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Photoshop RGB Channel Mixer Preset (.cha)|*.cha";
string proposedFileName = "matrix";
float[,] sliderMatrix = slidersToMatrix();
bool normalizationNeeded = false;
double normalizationMaxValue = 2;
// Check if any values are outside Photoshops -2 to 2 scope. (PS won't read a file if it's outside the scope)
for (int i = 0; i<3; i++)
{
for(int ii = 0; ii < 3; ii++)
{
if (sliderMatrix[i,ii] < -2 || sliderMatrix[i, ii] > 2)
{
normalizationNeeded = true;
if (Math.Abs(sliderMatrix[i, ii]) > normalizationMaxValue)
{
normalizationMaxValue = Math.Abs(sliderMatrix[i, ii]);
}
/*if (win.MessageBox.Show("Photoshop's Channel Mixer only supports values between -2 and 2 (-200% to 200%). Your current settings exceed those values. If you continue, those values will be clipped. Continue?","Attention!", win.MessageBoxButton.YesNo) != win.MessageBoxResult.Yes)
{
return;
} else
{
// Do clip the values, go!
goto FuckBeingElegant; // I didn't want to do this, C#, but you leave me no other choice. In PHP I could have written break 2;
}*/
}
}
}
//FuckBeingElegant:
double multiplier = 100;
if (normalizationNeeded)
{
win.MessageBoxResult wish = win.MessageBox.Show("The values of this matrix unfortunately exceed the -200% to 200% limit of the CHA file format. Do you wish to normalize the values? If you hit 'No', values will be clipped instead (not recommended), which will throw off color balance. Normalizing will only affect brightness.", "Decision needed", win.MessageBoxButton.YesNoCancel);
if (wish == win.MessageBoxResult.Yes)
{
multiplier = 100.0 * 2.0 / normalizationMaxValue;
proposedFileName += "_normalized";
}
else if (wish == win.MessageBoxResult.No)
{
proposedFileName += "_clipped";
}
else
{
return; // Cancel.
}
}
sfd.FileName = proposedFileName + ".cha";
//sfd.FileName = ;
if (sfd.ShowDialog() == true)
{
string filename = sfd.FileName;
using (FileStream fs = File.Open(filename, FileMode.Create))
{
using (BeBinaryWriter binWriter = new BeBinaryWriter(fs))
{
binWriter.Write((short)1);//Version
binWriter.Write((short)0);//Monochrome
binWriter.Write((short)Math.Max(-200, Math.Min(200,sliderMatrix[0,0]* multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[0,1]* multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[0,2]* multiplier)));
binWriter.Write((short)0); //Useless (CMYK?)
binWriter.Write((short)0); //Constant
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[1, 0] * multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[1, 1] * multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[1, 2] * multiplier)));
binWriter.Write((short)0); //Useless (CMYK?)
binWriter.Write((short)0); //Constant
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[2, 0] * multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[2, 1] * multiplier)));
binWriter.Write((short)Math.Max(-200, Math.Min(200, sliderMatrix[2, 2] * multiplier)));
binWriter.Write((short)0); //Useless (CMYK?)
binWriter.Write((short)0); //Constant
// No idea what the next values mean, but they are necessary apparently:
binWriter.Write((short)0);
binWriter.Write((short)0);
binWriter.Write((short)0);
binWriter.Write((short)100);
binWriter.Write((short)0);
}
}
setStatus("Slider values were written into " + filename + ": " + Helpers.matrixToString<float>(sliderMatrix));
}
}
private void btnMatrixInvert_Click(object sender, win.RoutedEventArgs e)
{
float[,] sliderMatrix = slidersToMatrix();
sliderMatrix = matrixInvert(sliderMatrix);
SetSlidersToMatrix(sliderMatrix);
}
}
}