Repository navigation
Expand file tree
/
Copy pathForm1.cs
More file actions
1216 lines (1034 loc) · 57.7 KB
/
Copy pathForm1.cs
File metadata and controls
1216 lines (1034 loc) · 57.7 KB
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
// Made by Stephan Akkerman (6397514) and Tim Koornstra (6435777) - Assignment pair 2
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace INFOIBV
{
public partial class INFOIBV : Form
{
private Bitmap InputImage;
private Bitmap OutputImage;
private byte[,] workingImage;
public INFOIBV()
{
InitializeComponent();
}
/*
* loadButton_Click: process when user clicks "Load" button
*/
private void loadImageButton_Click(object sender, EventArgs e)
{
if (openImageDialog.ShowDialog() == DialogResult.OK) // open file dialog
{
string file = openImageDialog.FileName; // get the file name
imageFileName.Text = file; // show file name
if (InputImage != null) InputImage.Dispose(); // reset image
InputImage = new Bitmap(file); // create new Bitmap from file
workingImage = new byte[InputImage.Size.Width, InputImage.Size.Height];
if (InputImage.Size.Height <= 0 || InputImage.Size.Width <= 0 ||
InputImage.Size.Height > 512 || InputImage.Size.Width > 512) // dimension check (may be removed or altered)
MessageBox.Show("Error in image dimensions (have to be > 0 and <= 512)");
else
pictureBox1.Image = (Image)InputImage; // display input image
}
}
/*
* applyButton_Click: process when user clicks "Apply" button
*/
private void applyButton_Click(object sender, EventArgs e)
{
if (InputImage == null) return; // get out if no input image
if (OutputImage != null) OutputImage.Dispose(); // reset output image
OutputImage = new Bitmap(InputImage.Size.Width, InputImage.Size.Height); // create new output image
Color[,] Image = new Color[InputImage.Size.Width, InputImage.Size.Height]; // create array to speed-up operations (Bitmap functions are very slow)
// copy input Bitmap to array
for (int x = 0; x < InputImage.Size.Width; x++) // loop over columns
for (int y = 0; y < InputImage.Size.Height; y++) // loop over rows
{
Image[x, y] = InputImage.GetPixel(x, y); // set pixel color in array at (x,y)
}
// ====================================================================
// =================== YOUR FUNCTION CALLS GO HERE ====================
// Alternatively you can create buttons to invoke certain functionality
// ====================================================================
// Beware that although multiple checkboxes can be checked at the same time, operations will happen from top to bottom.
// By checking wantGrayscale, the image will be reloaded. If you want to apply operations in a different order than
// top to bottom, uncheck wantGrayscale and you can apply whatever operator is desired.
// Also, keep in mind that textboxes are parsed from local language settings. If your system's language is Dutch,
// a float value of 1.4 would not result in a normal application of a function. If your language is not in English, please
// use ',' for floats and doubles. If it is, please use '.' to indicate decimals.
if (wantGrayscale.Checked) // convert image to grayscale
workingImage = convertToGrayscale(Image);
if (filterBox.Checked) // use a filter over an image
{
if (filterCombo.SelectedItem.ToString() == "Median")
workingImage = medianFilter(workingImage, Byte.Parse(sizeBox.Text));
}
if (sharpenBox.Checked) // sharpen edges
workingImage = sharpenEdges(workingImage, float.Parse(sharpBox.Text), Byte.Parse(smoothSizeBox.Text), float.Parse(smoothBox.Text));
if (closeBox.Checked)
workingImage = closeImage(workingImage, createStructuringElement(strucShapeCombo.Text.ToLower(), int.Parse(strucSizeBox.Text)));
if (edgeBox.Checked) // calculate edges
{
sbyte[,] hX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
sbyte[,] hY = { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };
workingImage = cannyEdge(workingImage, hX, hY);
}
if (thresholdBox.Checked) // threshold an image over a certain value
workingImage = thresholdImage(workingImage, Byte.Parse(thresholdField.Text));
if (circleDetect.Checked)
workingImage = circleDetection(workingImage, int.Parse(rMin.Text), int.Parse(rMax.Text), 30, 0.25);
// ==================== END OF YOUR FUNCTION CALLS ====================
// ====================================================================
// copy array to output Bitmap
for (int x = 0; x < workingImage.GetLength(0); x++) // loop over columns
for (int y = 0; y < workingImage.GetLength(1); y++) // loop over rows
{
Color newColor = Color.FromArgb(workingImage[x, y], workingImage[x, y], workingImage[x, y]);
OutputImage.SetPixel(x, y, newColor); // set the pixel color at coordinate (x,y)
}
pictureBox2.Image = (Image)OutputImage; // display output image
}
// A button to do all the Pre-Processing using the input boxes.
private void preButton_Click(object sender, EventArgs e)
{
if (InputImage == null) return; // get out if no input image
if (OutputImage != null) OutputImage.Dispose(); // reset output image
OutputImage = new Bitmap(InputImage.Size.Width, InputImage.Size.Height); // create new output image
Color[,] Image = new Color[InputImage.Size.Width, InputImage.Size.Height]; // create array to speed-up operations (Bitmap functions are very slow)
// copy input Bitmap to array
for (int x = 0; x < InputImage.Size.Width; x++) // loop over columns
for (int y = 0; y < InputImage.Size.Height; y++) // loop over rows
{
Image[x, y] = InputImage.GetPixel(x, y); // set pixel color in array at (x,y)
}
sbyte[,] hX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
sbyte[,] hY = { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };
workingImage = convertToGrayscale(Image);
workingImage = medianFilter(workingImage, Byte.Parse(sizeBox.Text));
workingImage = sharpenEdges(workingImage, float.Parse(sharpBox.Text), Byte.Parse(smoothSizeBox.Text), float.Parse(smoothBox.Text));
workingImage = closeImage(workingImage, createStructuringElement(strucShapeCombo.Text.ToLower(), int.Parse(strucSizeBox.Text)));
workingImage = cannyEdge(workingImage, hX, hY);
workingImage = thresholdImage(workingImage, Byte.Parse(thresholdField.Text));
for (int x = 0; x < workingImage.GetLength(0); x++) // loop over columns
for (int y = 0; y < workingImage.GetLength(1); y++) // loop over rows
{
Color newColor = Color.FromArgb(workingImage[x, y], workingImage[x, y], workingImage[x, y]);
OutputImage.SetPixel(x, y, newColor); // set the pixel color at coordinate (x,y)
}
pictureBox2.Image = (Image)OutputImage; // display output image
}
// A button function to classify the image and return an image with a bounding box around each coin, along with a count of how much of what has been
// classified.
private void classifyButton_Click(object sender, EventArgs e)
{
if (InputImage == null) return; // get out if no input image
if (OutputImage != null) OutputImage.Dispose(); // reset output image
OutputImage = new Bitmap(InputImage.Size.Width, InputImage.Size.Height); // create new output image
Color[,] Image = new Color[InputImage.Size.Width, InputImage.Size.Height]; // create array to speed-up operations (Bitmap functions are very slow)
// copy input Bitmap to array
for (int x = 0; x < InputImage.Size.Width; x++) // loop over columns
for (int y = 0; y < InputImage.Size.Height; y++) // loop over rows
{
Image[x, y] = InputImage.GetPixel(x, y); // set pixel color in array at (x,y)
}
// ColorNoise is based on the slider, if there is a lot of noise the threshold in getColors will be a bigger value
float colorNoise = (float)(noiseTrack.Value / 1.5);
List<Tuple<int, int, int>> circles = circleLocations(workingImage, int.Parse(rMin.Text), int.Parse(rMax.Text), 30, 0.25);
List<Color> colors = getColors(Image, circles, colorNoise);
List<List<Tuple<Point, Point>>> boundingBoxes = new List<List<Tuple<Point, Point>>>();
byte[,] flipImage = convertToGrayscale(Image);
List<bool> front = new List<bool>();
int countRed = 0;
int countBlue = 0;
int countGreen = 0;
int countYellow = 0;
int countBlack = 0;
foreach (Tuple<int, int, int> t in circles)
{
boundingBoxes.Add(createBoundingBox(t));
front.Add(isFront(flipImage, t));
}
foreach (List<Tuple<Point, Point>> l in boundingBoxes)
{
int index = boundingBoxes.IndexOf(l);
Color color = colors[index];
bool notBack = front[index];
if (color == Color.Red)
countRed++;
if (color == Color.Blue)
countBlue++;
if (color == Color.YellowGreen)
countYellow++;
if (color == Color.Green)
countGreen++;
if (color == Color.Black)
countBlack++;
foreach (Tuple<Point, Point> t in l)
{
int x1 = t.Item1.X;
int y1 = t.Item1.Y;
int x2 = t.Item2.X;
int y2 = t.Item2.Y;
if (x1 != x2)
for (int x = x1; x < x2; x++)
{
try
{
// To create a dashed bounding box to describe the back.
if (!notBack)
{
if (x % 10 > 3 && x % 10 < 9)
for (int y = y1 - 1; y < y1 + 1; y++)
Image[x, y] = color;
}
else
for (int y = y1 - 1; y < y1 + 1; y++)
Image[x, y] = color;
}
catch { }
}
else if (x1 == x2)
for (int y = y1; y < y2; y++)
{
try
{
if (!notBack)
{
if (y % 10 > 3 && y % 10 < 9)
for (int x = x1 - 1; x < x1 + 1; x++)
Image[x, y] = color;
}
else
for (int x = x1 - 1; x < x1 + 1; x++)
Image[x, y] = color;
}
catch { }
}
}
}
copperCount.Text = $"Found {countRed} 1 or 2 or 5 cent coin(s)";
goldCount.Text = $"Found {countYellow} 10 or 20 or 50 cent coin(s)";
countOneEu.Text = $"Found {countBlue} 1 euro coin(s)";
countTwoEu.Text = $"Found {countGreen} 2 euro coin(s)";
countUnclassified.Text = $"Found {countBlack} unidentified circle(s)";
for (int x = 0; x < workingImage.GetLength(0); x++) // loop over columns
for (int y = 0; y < workingImage.GetLength(1); y++) // loop over rows
{
OutputImage.SetPixel(x, y, Image[x, y]); // set the pixel color at coordinate (x,y)
}
pictureBox2.Image = (Image)OutputImage; // display output image
}
// A button to do both the pre-processing and the classification in one go.
private void preClassifyButtonClick(object sender, EventArgs e)
{
if (InputImage == null) return; // get out if no input image
if (OutputImage != null) OutputImage.Dispose(); // reset output image
OutputImage = new Bitmap(InputImage.Size.Width, InputImage.Size.Height); // create new output image
Color[,] Image = new Color[InputImage.Size.Width, InputImage.Size.Height]; // create array to speed-up operations (Bitmap functions are very slow)
// copy input Bitmap to array
for (int x = 0; x < InputImage.Size.Width; x++) // loop over columns
for (int y = 0; y < InputImage.Size.Height; y++) // loop over rows
{
Image[x, y] = InputImage.GetPixel(x, y); // set pixel color in array at (x,y)
}
sbyte[,] hX = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
sbyte[,] hY = { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };
workingImage = convertToGrayscale(Image);
workingImage = medianFilter(workingImage, Byte.Parse(sizeBox.Text));
workingImage = sharpenEdges(workingImage, float.Parse(sharpBox.Text), Byte.Parse(smoothSizeBox.Text), float.Parse(smoothBox.Text));
workingImage = closeImage(workingImage, createStructuringElement(strucShapeCombo.Text.ToLower(), int.Parse(strucSizeBox.Text)));
workingImage = cannyEdge(workingImage, hX, hY);
workingImage = thresholdImage(workingImage, Byte.Parse(thresholdField.Text));
// ColorNoise is based on the slider, if there is a lot of noise the threshold in getColors will be a bigger value
float colorNoise = (float)(noiseTrack.Value / 1.5);
List<Tuple<int, int, int>> circles = circleLocations(workingImage, int.Parse(rMin.Text), int.Parse(rMax.Text), 30, 0.25);
List<Color> colors = getColors(Image, circles, colorNoise);
List<List<Tuple<Point, Point>>> boundingBoxes = new List<List<Tuple<Point, Point>>>();
byte[,] flipImage = convertToGrayscale(Image);
List<bool> front = new List<bool>();
int countRed = 0;
int countBlue = 0;
int countGreen = 0;
int countYellow = 0;
int countBlack = 0;
foreach (Tuple<int, int, int> t in circles)
{
boundingBoxes.Add(createBoundingBox(t));
front.Add(isFront(flipImage, t));
}
foreach (List<Tuple<Point, Point>> l in boundingBoxes)
{
int index = boundingBoxes.IndexOf(l);
Color color = colors[index];
bool notBack = front[index];
if (color == Color.Red)
countRed++;
if (color == Color.Blue)
countBlue++;
if (color == Color.YellowGreen)
countYellow++;
if (color == Color.Green)
countGreen++;
if (color == Color.Black)
countBlack++;
foreach (Tuple<Point, Point> t in l)
{
int x1 = t.Item1.X;
int y1 = t.Item1.Y;
int x2 = t.Item2.X;
int y2 = t.Item2.Y;
if (x1 != x2)
for (int x = x1; x < x2; x++)
{
try
{
if (!notBack)
{
if (x % 10 > 4 && x % 10 < 9)
for (int y = y1 - 1; y < y1 + 1; y++)
Image[x, y] = color;
}
else
for (int y = y1 - 1; y < y1 + 1; y++)
Image[x, y] = color;
}
catch { }
}
else if (x1 == x2)
for (int y = y1; y < y2; y++)
{
try
{
if (!notBack)
{
if (y % 10 > 4 && y % 10 < 9)
for (int x = x1 - 1; x < x1 + 1; x++)
Image[x, y] = color;
}
else
for (int x = x1 - 1; x < x1 + 1; x++)
Image[x, y] = color;
}
catch { }
}
}
}
copperCount.Text = $"Found {countRed} 1 or 2 or 5 cent coin(s)";
goldCount.Text = $"Found {countYellow} 10 or 20 or 50 cent coin(s)";
countOneEu.Text = $"Found {countBlue} 1 euro coin(s)";
countTwoEu.Text = $"Found {countGreen} 2 euro coin(s)";
countUnclassified.Text = $"Found {countBlack} unidentified circle(s)";
for (int x = 0; x < workingImage.GetLength(0); x++) // loop over columns
for (int y = 0; y < workingImage.GetLength(1); y++) // loop over rows
{
OutputImage.SetPixel(x, y, Image[x, y]); // set the pixel color at coordinate (x,y)
}
pictureBox2.Image = (Image)OutputImage; // display output image
}
private void noiseTrack_Scroll(object sender, EventArgs e)
{
noiseCount.Text = noiseTrack.Value.ToString();
}
/*
* saveButton_Click: process when user clicks "Save" button
*/
private void saveButton_Click(object sender, EventArgs e)
{
if (OutputImage == null) return; // get out if no output image
if (saveImageDialog.ShowDialog() == DialogResult.OK)
OutputImage.Save(saveImageDialog.FileName); // save the output image
}
/*
* convertToGrayScale: convert a three-channel color image to a single channel grayscale image
* input: inputImage three-channel (Color) image
* output: single-channel (byte) image
*/
private byte[,] convertToGrayscale(Color[,] inputImage)
{
// create temporary grayscale image of the same size as input, with a single channel
byte[,] tempImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
// setup progress bar
progressBar.Visible = true;
progressBar.Minimum = 1;
progressBar.Maximum = InputImage.Size.Width * InputImage.Size.Height;
progressBar.Value = 1;
progressBar.Step = 1;
// process all pixels in the image
for (int x = 0; x < InputImage.Size.Width; x++) // loop over columns
for (int y = 0; y < InputImage.Size.Height; y++) // loop over rows
{
Color pixelColor = inputImage[x, y]; // get pixel color
byte average = (byte)((pixelColor.R + pixelColor.B + pixelColor.G) / 3); // calculate average over the three channels
tempImage[x, y] = average; // set the new pixel color at coordinate (x,y)
progressBar.PerformStep(); // increment progress bar
}
progressBar.Visible = false; // hide progress bar
return tempImage;
}
// ====================================================================
// ============= YOUR FUNCTIONS FOR ASSIGNMENT 1 GO HERE ==============
// ====================================================================
/*
* invertImage: invert a single channel (grayscale) image
* input: inputImage single-channel (byte) image
* output: tempImage single-channel (byte) image
*/
private byte[,] invertImage(byte[,] inputImage)
{
// create temporary grayscale image
byte[,] tempImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
for (int x = 0; x < inputImage.GetLength(0); x++) // loop over columns
for (int y = 0; y < inputImage.GetLength(1); y++) // loop over rows
{
byte invertedPixel = (byte)(255 - inputImage[x, y]);
tempImage[x, y] = invertedPixel;
}
return tempImage;
}
/*
* createGaussianFilter: create a Gaussian filter of specific square size and with a specified sigma
* input: size length and width of the Gaussian filter (only odd sizes)
* sigma standard deviation of the Gaussian distribution
* output: filter Gaussian filter
*/
private float[,] createGaussianFilter(byte size, float sigma)
{
float[,] filter = new float[size, size];
if (size % 2 == 1)
{
float gaussianSum = 0;
int filterCenter = (filter.GetLength(0) - 1) / 2;
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
{
// calculate the Gaussian value for each of the filter points and store them in our filter
float distx = filterCenter - x;
float disty = filterCenter - y;
float gaussianNumber = (float)Math.Pow(Math.E, -(distx * distx + disty * disty) / (2 * (sigma * sigma)));
gaussianSum += gaussianNumber;
filter[x, y] = gaussianNumber;
}
// normalize values to sum to 1
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
filter[x, y] = filter[x, y] / gaussianSum;
}
return filter;
}
/*
* convolveImage: apply linear filtering of an input image
* input: inputImage single-channel (byte) image
* filter linear kernel
* output: retImage single-channel (byte) image
*/
private byte[,] convolveImage(byte[,] inputImage, float[,] filter)
{
int paddingSize = (int)Math.Floor((double)filter.GetLength(0) / 2);
byte[,] tempImage = createPaddedImage(inputImage, (byte)filter.GetLength(0));
byte[,] retImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
// Apply filter
for (int x = paddingSize; x < tempImage.GetLength(0) - paddingSize; x++)
for (int y = paddingSize; y < tempImage.GetLength(1) - paddingSize; y++)
{
short newValue = 0;
for (int i = 0; i < filter.GetLength(0); i++)
for (int j = 0; j < filter.GetLength(1); j++)
newValue += (short)(filter[i, j] * tempImage[x - paddingSize + i, y - paddingSize + j]);
retImage[x - paddingSize, y - paddingSize] = (byte)newValue;
}
return retImage;
}
/*
* medianFilter: apply median filtering on an input image with a kernel of specified size
* input: inputImage single-channel (byte) image
* size length/width of the median filter kernel
* output: retImage single-channel (byte) image
*/
private byte[,] medianFilter(byte[,] inputImage, byte size)
{
int paddingSize = (int)Math.Floor((double)size / 2);
byte[,] tempImage = createPaddedImage(inputImage, size);
byte[,] retImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
byte[,] filter;
byte[] filter1d;
// Apply filter
for (int x = paddingSize; x < tempImage.GetLength(0) - paddingSize; x++)
for (int y = paddingSize; y < tempImage.GetLength(1) - paddingSize; y++)
{
filter = new byte[size, size];
filter1d = new byte[size * size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
filter[i, j] = tempImage[x - paddingSize + i, y - paddingSize + j];
// turn filter into 1d array so we can sort
int k = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
filter1d[k++] = filter[i, j];
Array.Sort(filter1d);
byte center = (byte)Math.Floor((double)filter1d.Length / 2);
if (filter1d.Length % 2 != 0)
retImage[x - paddingSize, y - paddingSize] = filter1d[center];
else
retImage[x - paddingSize, y - paddingSize] = (byte)((filter1d[center] + filter1d[center - 1]) * 0.5);
}
return retImage;
}
// A function for canny edge detection. This is partly the same as our old edge detection, but with the extra functionality
// that canny edge detection brings.
private byte[,] cannyEdge(byte[,] inputImage, sbyte[,] horizontalKernel, sbyte[,] verticalKernel)
{
int paddingSize = (int)Math.Floor((double)horizontalKernel.GetLength(0) / 2);
byte[,] tempImage = createPaddedImage(inputImage, (byte)horizontalKernel.GetLength(0));
byte[,] retImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
short[,] tempImageX = new short[tempImage.GetLength(0), tempImage.GetLength(1)];
short[,] tempImageY = new short[tempImage.GetLength(0), tempImage.GetLength(1)];
// Calculate Dx(u,v) and Dy(u,v)
for (int x = paddingSize; x < tempImage.GetLength(0) - paddingSize; x++)
for (int y = paddingSize; y < tempImage.GetLength(1) - paddingSize; y++)
{
short newValueX = 0;
short newValueY = 0;
for (int i = 0; i < horizontalKernel.GetLength(0); i++)
for (int j = 0; j < verticalKernel.GetLength(0); j++)
{
newValueX += (short)(horizontalKernel[i, j] * tempImage[x - paddingSize + i, y - paddingSize + j]);
newValueY += (short)(verticalKernel[i, j] * tempImage[x - paddingSize + i, y - paddingSize + j]);
}
tempImageX[x, y] = newValueX;
tempImageY[x, y] = newValueY;
}
// Calculate the gradient magnitude and the angle
short maxG = 0;
short minG = Int16.MaxValue;
short[,] gradient = new short[inputImage.GetLength(0), inputImage.GetLength(1)];
double[,] angle = new double[inputImage.GetLength(0), inputImage.GetLength(1)];
for (int x = 0; x < retImage.GetLength(0); x++)
for (int y = 0; y < retImage.GetLength(1); y++)
{
angle[x, y] = Math.Atan2(tempImageY[x, y], tempImageX[x, y]);
gradient[x, y] = (short)Math.Sqrt((tempImageX[x, y] * tempImageX[x, y]) + (tempImageY[x, y] * tempImageY[x, y]));
if (gradient[x, y] > maxG)
maxG = gradient[x, y];
if (gradient[x, y] < minG)
minG = gradient[x, y];
}
// Non-maximum suppression.
for (int x = 1; x < gradient.GetLength(0) - 1; x++)
{
for (int y = 1; y < gradient.GetLength(1) - 1; y++)
{
short q = maxG;
short r = maxG;
if ((angle[x, y] < 22.5 && angle[x, y] >= 0) || (angle[x, y] < 180 && angle[x, y] >= 157.5))
{
q = gradient[x, y + 1];
r = gradient[x, y - 1];
}
else if (angle[x, y] < 67.5 && angle[x, y] >= 22.5)
{
q = gradient[x + 1, y - 1];
r = gradient[x - 1, y - 1];
}
else if (angle[x, y] < 112.5 && angle[x, y] >= 67.5)
{
q = gradient[x + 1, y];
r = gradient[x - 1, y];
}
else if (angle[x, y] < 157.5 && angle[x, y] >= 112.5)
{
q = gradient[x - 1, y - 1];
r = gradient[x + 1, y + 1];
}
if (gradient[x, y] < q || gradient[x, y] < r)
{
gradient[x, y] = minG;
}
}
}
// Double thresholding
double highThreshold = maxG * 0.09;
double lowThreshold = highThreshold * 0.05;
short[,] doubleThreshold = new short[gradient.GetLength(0), gradient.GetLength(1)];
for (int x = 0; x < gradient.GetLength(0); x++)
{
for (int y = 0; y < gradient.GetLength(1); y++)
{
if (gradient[x, y] >= lowThreshold && gradient[x, y] <= highThreshold)
doubleThreshold[x, y] = -1;
else if (gradient[x, y] >= highThreshold)
doubleThreshold[x, y] = 1;
else if (gradient[x, y] < lowThreshold)
doubleThreshold[x, y] = 0;
}
}
// Actually drawing the double thresholded values.
for (int x = 1; x < gradient.GetLength(0) - 1; x++)
{
for (int y = 1; y < gradient.GetLength(1) - 1; y++)
{
if (doubleThreshold[x, y] == -1)
{
if ((doubleThreshold[x - 1, y] == 1 || doubleThreshold[x + 1, y] == 1 || doubleThreshold[x - 1, y - 1] == 1 || doubleThreshold[x - 1, y + 1] == 1
|| doubleThreshold[x + 1, y - 1] == 1 || doubleThreshold[x + 1, y + 1] == 1 || doubleThreshold[x, y - 1] == 1 || doubleThreshold[x, y + 1] == 1))
gradient[x, y] = gradient[x, y];
else
gradient[x, y] = minG;
}
}
}
// Scale those values back to 0-255 so we can store them in a byte array
for (int x = 0; x < retImage.GetLength(0); x++)
for (int y = 0; y < retImage.GetLength(1); y++)
{
gradient[x, y] = (short)(((gradient[x, y] - minG) * 255) / (double)(maxG - minG));
retImage[x, y] = (byte)gradient[x, y];
}
return retImage;
}
/*
* thresholdImage: threshold a grayscale image
* input: inputImage single-channel (byte) image
* output: tempImage single-channel (byte) image with on/off values
*/
private byte[,] thresholdImage(byte[,] inputImage, byte threshold)
{
// Threshold image
byte[,] tempImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
{
if (inputImage[x, y] > threshold)
tempImage[x, y] = 255;
else
tempImage[x, y] = 0;
}
return tempImage;
}
/*
* sharpenEdges: sharpen the edges of an image
* input: inputImage single-channel (byte) image
* output: retImage single-channel (byte) image with sharpened edges
*/
private byte[,] sharpenEdges(byte[,] inputImage, float factor, byte filterSize, float filterSigma) //Unsharp masking
{
short[,] tempImage = new short[inputImage.GetLength(0), inputImage.GetLength(1)];
byte[,] retImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
byte[,] smoothImage = convolveImage(inputImage, createGaussianFilter(filterSize, filterSigma));
short[,] mask = new short[inputImage.GetLength(0), inputImage.GetLength(1)];
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
mask[x, y] = (short)(inputImage[x, y] - smoothImage[x, y]);
// Create the new image by subtracting the mask from the original image
short maxValue = 0;
short minValue = Int16.MaxValue;
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
{
tempImage[x, y] = (short)(inputImage[x, y] + factor * mask[x, y]);
if (tempImage[x, y] > maxValue)
maxValue = tempImage[x, y];
if (tempImage[x, y] < minValue)
minValue = tempImage[x, y];
}
// Scale the values back to the range 0-255
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
retImage[x, y] = (byte)((tempImage[x, y] - minValue) * 255.0 / (maxValue - minValue));
return retImage;
}
// function to add padding to image to apply kernels
private byte[,] createPaddedImage(byte[,] inputImage, byte size)
{
int paddingSize = (int)Math.Floor((double)size / 2);
byte[,] tempImage = new byte[inputImage.GetLength(0) + 2 * paddingSize, inputImage.GetLength(1) + 2 * paddingSize];
// Add padding
for (int x = 0; x < tempImage.GetLength(0); x++)
for (int y = 0; y < tempImage.GetLength(1); y++)
{
if (x < paddingSize || y < paddingSize || x > paddingSize + inputImage.GetLength(0) - 1 || y > paddingSize + inputImage.GetLength(1) - 1)
{
// Corners
if (x < paddingSize && y < paddingSize)
tempImage[x, y] = inputImage[0, 0];
else if (x < paddingSize && y >= paddingSize + inputImage.GetLength(1))
tempImage[x, y] = inputImage[0, inputImage.GetLength(1) - 1];
else if (x >= paddingSize + inputImage.GetLength(0) && y < paddingSize)
tempImage[x, y] = inputImage[inputImage.GetLength(0) - 1, 0];
else if (x >= paddingSize + inputImage.GetLength(0) && y >= paddingSize + inputImage.GetLength(1))
tempImage[x, y] = inputImage[inputImage.GetLength(0) - 1, inputImage.GetLength(1) - 1];
// Other edges
else if (x >= paddingSize && y < paddingSize && x <= inputImage.GetLength(0) + paddingSize)
tempImage[x, y] = inputImage[x - paddingSize, 0];
else if (x < paddingSize && y >= paddingSize && y < inputImage.GetLength(1) + paddingSize)
tempImage[x, y] = inputImage[0, y - paddingSize];
else if (x >= inputImage.GetLength(0) + paddingSize && y >= paddingSize && y < inputImage.GetLength(1) + paddingSize)
tempImage[x, y] = inputImage[inputImage.GetLength(0) - 1, y - paddingSize];
else if (x >= paddingSize && y >= inputImage.GetLength(1) + paddingSize && x <= inputImage.GetLength(0) + paddingSize)
tempImage[x, y] = inputImage[x - paddingSize, inputImage.GetLength(1) - 1];
}
else
tempImage[x, y] = inputImage[x - paddingSize, y - paddingSize];
}
return tempImage;
}
// ====================================================================
// ============= YOUR FUNCTIONS FOR ASSIGNMENT 2 GO HERE ==============
// ====================================================================
// Function to create a structuring element
private sbyte[,] createStructuringElement(string shape, int size)
{
// If the desired shape is a square, simply fill an array of a set size with 1s.
if (shape == "square")
{
sbyte[,] square = new sbyte[size, size];
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
square[x, y] = 1;
return square;
}
// If the desired shape is a plus, only place 1s on the horizontal and vertical center.
else if (shape == "plus")
{
sbyte[,] plus = new sbyte[size, size];
int center = (int)Math.Floor((double)size / 2);
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
if (x == center || y == center)
plus[x, y] = 1;
return plus;
}
else if (shape == "circle")
{
sbyte[,] circle = new sbyte[size, size];
int center = (int)Math.Floor((double)size / 2);
int r = 2;
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
if (((x - center) * (x - center) + (y - center) * (y - center)) <= (r * r))
circle[x, y] = 1;
return circle;
}
else
return null;
}
// Function to dilate an image.
private byte[,] dilateImage(byte[,] inputImage, sbyte[,] inputShape)
{
// Because we are working with a kernel, we need to add padding to the image.
byte[,] paddedImage = createPaddedImage(inputImage, (byte)inputShape.GetLength(0));
short[,] tempImage = new short[inputImage.GetLength(0), inputImage.GetLength(1)];
byte[,] retImage = new byte[inputImage.GetLength(0), inputImage.GetLength(1)];
int paddingSize = (int)Math.Floor((double)inputShape.GetLength(0) / 2);
short maxValue = 0;
short minValue = short.MaxValue;
// For every pixel in the padded image (excluding the borders).
for (int x = paddingSize; x < paddedImage.GetLength(0) - paddingSize; x++)
for (int y = paddingSize; y < paddedImage.GetLength(1) - paddingSize; y++)
{
// Calculate the diluted values within the kernel shape.
short[,] kernelDilated = new short[inputShape.GetLength(0), inputShape.GetLength(1)];
for (int i = 0; i < inputShape.GetLength(0); i++)
for (int j = 0; j < inputShape.GetLength(1); j++)
if (inputShape[i, j] != 0)
kernelDilated[i, j] = (short)(inputShape[i, j] + paddedImage[x - paddingSize + i, y - paddingSize + j]);
// Find the max value of the values within the kernel shape.
short max = 0;
for (int i = 0; i < kernelDilated.GetLength(0); i++)
for (int j = 0; j < kernelDilated.GetLength(1); j++)
if (kernelDilated[i, j] > max)
max = kernelDilated[i, j];
// Replace our tempImage value with the max value we found in the kernel and calculate the max
// value in our image at the same time.
tempImage[x - paddingSize, y - paddingSize] = max;
if (tempImage[x - paddingSize, y - paddingSize] > maxValue)
maxValue = tempImage[x - paddingSize, y - paddingSize];
if (tempImage[x - paddingSize, y - paddingSize] < minValue)
minValue = tempImage[x - paddingSize, y - paddingSize];
}
// Scale our image values back to the range 0-255
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
retImage[x, y] = (byte)((tempImage[x, y] - minValue) * 255.0 / (maxValue - minValue));
return retImage;
}
// A function to erode an image.
private byte[,] erodeImage(byte[,] inputImage, sbyte[,] inputShape)
{
// Eroding an image is the same as taking the mirrored inputShape and applying it to the inverted
// input image. Since our input shapes are symmetrical, however, we do not need to mirror it (since
// we can assume that our structuring elements are of (arbitrary) odd size.
byte[,] tempImage = invertImage(inputImage);
tempImage = dilateImage(tempImage, inputShape);
byte[,] retImage = invertImage(tempImage);
return retImage;
}
// Simply dilate and image and erode it by the same input shape.
private byte[,] closeImage(byte[,] inputImage, sbyte[,] inputShape)
{
return erodeImage(dilateImage(inputImage, inputShape), inputShape);
}
// =======================================================
// ============= Circle Detection Functions ==============
// =======================================================
// General function to detect circles using the Hough Circle Transform.
private byte[,] circleDetection(byte[,] inputImage, int rmin, int rmax, double steps, double threshold)
{
// We create a list of possible points, where the first and second items in the tuple describe the center point and the third the radius.
List<Tuple<int, int, int>> points = new List<Tuple<int, int, int>>();
for (int r = rmin; r < rmax; r++)
for (int t = 0; t < steps; t++)
points.Add(new Tuple<int, int, int>(r, (int)(r * Math.Cos(2 * Math.PI * t / steps)), (int)(r * Math.Sin(2 * Math.PI * t / steps))));
// Create a dictionary to save each point along with a value (the voting).
Dictionary<Tuple<int, int, int>, int> dict = new Dictionary<Tuple<int, int, int>, int>();
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
if (inputImage[x, y] > 0)
{
foreach (Tuple<int, int, int> t in points)
{
int a = x - t.Item2;
int b = y - t.Item3;
if (dict.ContainsKey(new Tuple<int, int, int>(a, b, t.Item1)))
{
int score = dict[new Tuple<int, int, int>(a, b, t.Item1)];
dict[new Tuple<int, int, int>(a, b, t.Item1)] = score + 1;
}
else
{
dict.Add(new Tuple<int, int, int>(a, b, t.Item1), 1);
}
}
}
// Create a list of circles that we have found. Again, the first and second items in the tuple describe the center point and the third the radius.
List<Tuple<int, int, int>> circles = new List<Tuple<int, int, int>>();
foreach (KeyValuePair<Tuple<int, int, int>, int> item in dict)
{
int x = item.Key.Item1;
int y = item.Key.Item2;
int r = item.Key.Item3;
double v = item.Value;
if (v / steps >= threshold)
{
bool forAll = true;
foreach (Tuple<int, int, int> waardes in circles)
if (!(((x - waardes.Item1) * (x - waardes.Item1) + (y - waardes.Item2) * (y - waardes.Item2)) > (waardes.Item3 * waardes.Item3)))
{
forAll = false;
break;
}
if (forAll)
circles.Add(new Tuple<int, int, int>(x, y, r));
}
}
// This function allows us to draw a gray circle over each of the found circles. We return an altered inputImage, with these overlayed circles.
foreach (Tuple<int, int, int> coordinates in circles)
{
int xo = coordinates.Item1;
int yo = coordinates.Item2;
int r = coordinates.Item3;
int rr = (int)(Math.Pow(r, 2));
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
if (((x - xo) * (x - xo) + (y - yo) * (y - yo)) <= rr)
inputImage[x, y] = 122;
}
return inputImage;
}
// The same function as before, with the exception that we do not draw the circle, but instead return a list of the circles we have found.
private List<Tuple<int, int, int>> circleLocations(byte[,] inputImage, int rmin, int rmax, double steps, double threshold)
{
List<Tuple<int, int, int>> points = new List<Tuple<int, int, int>>();
for (int r = rmin; r < rmax; r++)
for (int t = 0; t < steps; t++)
points.Add(new Tuple<int, int, int>(r, (int)(r * Math.Cos(2 * Math.PI * t / steps)), (int)(r * Math.Sin(2 * Math.PI * t / steps))));
Dictionary<Tuple<int, int, int>, int> dict = new Dictionary<Tuple<int, int, int>, int>();
for (int x = 0; x < inputImage.GetLength(0); x++)
for (int y = 0; y < inputImage.GetLength(1); y++)
if (inputImage[x, y] > 0)
{
foreach (Tuple<int, int, int> t in points)
{
int a = x - t.Item2;
int b = y - t.Item3;
if (dict.ContainsKey(new Tuple<int, int, int>(a, b, t.Item1)))
{
int score = dict[new Tuple<int, int, int>(a, b, t.Item1)];