ImageUtil.cs
41.3 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
using AccImage;
using OpenCvSharp;
using OpenCvSharp.Blob;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
namespace Acc.Img
{
public class ImageUtil
{
/// <summary>
/// 读取图片,,支持格式*.raw,*.bmp;*.gif;*.jpg;*.png
/// </summary>
/// <param name="imagePath"></param>
/// <returns>读取到的图片对像,读取失败时返回null</returns>
public static Image ReadImage(string imagePath)
{
Image image = null;
try
{
if (imagePath.ToLower().EndsWith(".raw"))
{
byte[] src = System.IO.File.ReadAllBytes(imagePath);
int width = 3072;
int height = 3072;
int n = 0;
byte[] buff = new byte[src.Length * 3];
for (int i = 0; i < src.Length; i += 2)
{
short ss = BitConverter.ToInt16(src, i);
ss *= 10;
byte[] bb = BitConverter.GetBytes(ss);
buff[n++] = bb[0];
buff[n++] = bb[1];
buff[n++] = bb[0];
buff[n++] = bb[1];
buff[n++] = bb[0];
buff[n++] = bb[1];
}
Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
System.Runtime.InteropServices.Marshal.Copy(buff, 0, bmpData.Scan0, bmpData.Stride * height);
bmp.UnlockBits(bmpData);
//bmp.Save(@"C:\Users\ASA\Desktop\222.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
image = bmp;
}
else
{
image = Image.FromFile(imagePath);
}
}
catch (Exception)
{
}
return image;
}
/// <summary>
/// 二值化图像
/// </summary>
/// <param name="image">图像数据</param>
/// <param name="thresh">阈值</param>
/// <param name="inv">true表示元器件为白色,false表示元器件为黑色</param>
/// <returns>二值化后的图像</returns>
public static Image Threshhold(Image image, int thresh)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
Mat threshMat = Threshhold(imageMat, thresh);
return BitmapConverter.ToBitmap(threshMat);
}
/// <summary>
/// 获取鼠标位置的元器件特征值
/// </summary>
/// <param name="image">输入的图像</param>
/// <param name="markX">鼠标的X点坐标</param>
/// <param name="markY">鼠标的Y点坐标</param>
/// <param name="thresh">二值化阈值</param>
/// <param name="inv">true表示元器件为白色,false表示元器件为黑色</param>
/// <returns>鼠标指向的元器件特征值</returns>
public static int GetItemFeature(Image image, int markX = -1, int markY = -1, int thresh = -1)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
List<CvBlob> blobList = GetBlobs(imageMat, thresh);
int blobCount = blobList.Count;
int selectIndex = blobCount / 2;
if (markX != -1 && markY != -1)
{
//查找标记的Blob
int markIndex = -1;
for (int i = 0; i < blobCount; i++)
{
CvBlob blob = blobList[i];
if (blob.Rect.Contains(new OpenCvSharp.Point(markX, markY)))
{
if (markIndex == -1 || blobList[i].Area < blobList[markIndex].Area)
{
markIndex = i;
}
}
}
if (markIndex != -1)
{
int area = blobList[markIndex].Area;
area = area * 5 / 3 - 23;
return area;
}
}
return 0;
}
public static int GetItemFeatureAuto(Image image, int markX = -1, int markY = -1, int thresh = -1, bool inv = true)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
List<CvBlob> blobList = GetBlobs(imageMat, thresh);
List<int> sampleList = new List<int>();
CvBlob srcBlob = new CvBlob();
srcBlob.Area = -1;
int blobCount = blobList.Count;
int selectIndex = blobCount / 2 + blobCount / 16;
for (int i = 0; i < blobList.Count; i++)
{
if (srcBlob.Area == -1)
{
srcBlob = blobList[i];
if (srcBlob.Area < 40)
{
srcBlob.Area = -1;
}
}
else
{
if (blobList[i].Area < srcBlob.Area && blobList[i].Area > 40)
{
srcBlob = blobList[i];
}
}
}
for (int i = 0; i < blobList.Count; i++)
{
if (srcBlob.Area < blobList[i].Area)
{
double num = (double)blobList[i].Area / srcBlob.Area;
if (num < 2)
{
sampleList.Add(blobList[i].Area);
}
}
if (sampleList.Count == blobList.Count - 1 || i == blobList.Count - 1)
{
int nums = 0;
for (int j = 0; j < sampleList.Count; j++)
{
nums += sampleList[j];
}
double area = (double)nums / sampleList.Count;
double ss = area * 0.35;
int areaI = (int)Math.Round(area + ss);
//int sss = (int)Math.Round(areaI);
return areaI;
}
}
//if (markX != -1 && markY != -1)
//{
// //查找标记的Blob
// int markIndex = -1;
// for (int i = 0; i < blobCount; i++)
// {
// CvBlob blob = blobList[i];
// if (blob.Rect.Contains(new OpenCvSharp.Point(markX, markY)))
// {
// if (markIndex == -1 || blobList[i].Area < blobList[markIndex].Area)
// {
// markIndex = i;
// }
// }
// }
// if (markIndex != -1)
// {
// int area = blobList[markIndex].Area;
// area = area * 5 / 3 - 23;
// return area;
// }
//}
return srcBlob.Area;
}
/// <summary>
/// 根据元器件特征统计图片中的元器件数量
/// </summary>
/// <param name="image"></param>
/// <param name="itemFeature"></param>
/// <param name="thresh"></param>
/// <param name="inv"></param>
/// <returns></returns>
public static int CountItems(ref Image image, int itemArea)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.RGBA2BGR);
Mat grayMat = BitmapConverter.ToMat(new Bitmap(image));
Cv2.CvtColor(grayMat, grayMat, ColorConversionCodes.RGB2GRAY);
CvBlobs blobs = AutoThreshBlobs(ref grayMat, itemArea);
int totalCount = findCircles(ref imageMat, grayMat, blobs, itemArea);
//int totalCount = CountBlobs(blobs, itemArea, ref imageMat);
image = BitmapConverter.ToBitmap(imageMat);
return totalCount;
}
private static void FindCours(Mat srcMat, Mat threshMat)
{
Mat[] contours = null;
Mat hierarchy = new Mat();
Cv2.FindContours(threshMat, out contours, hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
Mat linePic = Mat.Zeros(threshMat.Rows, threshMat.Cols, MatType.CV_8UC3);
int contoursSize = contours.Length;
for (int index = 0; index < contoursSize; index++)
{
//Cv2.DrawContours(linePic, contours, index, Scalar.RandomColor());
//找出完整包含轮廓的最小矩形
//Rect rect = Cv2.BoundingRect(contours[index]);
RotatedRect rect = Cv2.MinAreaRect(contours[index]);
double area = Cv2.ContourArea(contours[index]);
if (rect.Size.Height < 100 || rect.Size.Width < 100)
{
continue;
}
//Cv2.Rectangle(originalImg, rect, Scalar.Red);
Point2f[] pf = rect.Points();
OpenCvSharp.Point[] ps = new OpenCvSharp.Point[pf.Length];
for (int i = 0; i < pf.Length; i++)
{
ps[i] = new OpenCvSharp.Point(pf[i].X, pf[i].Y);
}
Cv2.Line(srcMat, ps[0], ps[1], Scalar.Red);
Cv2.Line(srcMat, ps[1], ps[2], Scalar.Red);
Cv2.Line(srcMat, ps[2], ps[3], Scalar.Red);
Cv2.Line(srcMat, ps[0], ps[3], Scalar.Red);
}
}
private static void LabelBlobsInCircle(ref string[] labels, List<CvBlob> blobList, double centerX, double centerY, double radius)
{
int labelCount = 0;
double minX = 0;
double maxX = 0;
double minY = 0;
double maxY = 0;
for (int i = 0; i < labels.Length; i++)
{
if (labels[i] == null)
{
CvBlob anotherBlob = blobList[i];
//左上,右上,左下,右下
bool isNeighbour = false;
if (Math.Abs(anotherBlob.MinX - centerX) < radius && Math.Abs(anotherBlob.MinY - centerY) < radius)
{
isNeighbour = true;
}
else if (Math.Abs(anotherBlob.MaxX - centerX) < radius && Math.Abs(anotherBlob.MinY - centerY) < radius)
{
isNeighbour = true;
}
else if (Math.Abs(anotherBlob.MinX - centerX) < radius && Math.Abs(anotherBlob.MaxY - centerY) < radius)
{
isNeighbour = true;
}
else if (Math.Abs(anotherBlob.MaxX - centerX) < radius && Math.Abs(anotherBlob.MaxY - centerY) < radius)
{
isNeighbour = true;
}
if (isNeighbour)
{
labels[i] = "1";
labelCount = labelCount + 1;
if (anotherBlob.MinX < minX || minX == 0)
{
minX = anotherBlob.MinX;
}
if (anotherBlob.MinY < minY || minY == 0)
{
minY = anotherBlob.MinY;
}
if (anotherBlob.MaxX > maxX)
{
maxX = anotherBlob.MaxX;
}
if (anotherBlob.MaxY > maxY)
{
maxY = anotherBlob.MaxY;
}
}
}
}
if (labelCount > 0)
{
double rightX = centerX;
do
{
rightX = rightX + radius;
LabelBlobsInCircle(ref labels, blobList, rightX, centerY, radius);
} while (rightX < maxX);
double leftX = centerX;
do
{
leftX = leftX - radius;
LabelBlobsInCircle(ref labels, blobList, leftX, centerY, radius);
} while (leftX > minX);
double downY = centerY;
do
{
downY = downY + radius;
LabelBlobsInCircle(ref labels, blobList, centerX, downY, radius);
} while (downY < maxY);
double upY = centerY;
do
{
upY = upY - radius;
LabelBlobsInCircle(ref labels, blobList, centerX, upY, radius);
} while (upY > minY);
}
}
private static double GetLabelStep(List<CvBlob> blobList, int avgArea, out CvBlob markBlob)
{
int leastNeighbourBlobCount = 15;
int selectIndex = blobList.Count / 2;
markBlob = blobList[selectIndex];
for (int i = selectIndex; i < blobList.Count; i++)
{
CvBlob blob = blobList[i];
int blobArea = markBlob.Area;
if (BlobHasItem(avgArea, blob) == 1)
// if(blobArea > 0.9 * avgArea && blobArea < 1.1 * avgArea)
{
//面积与给定的面积差不多,以其为中心,周围至少要有15个Blob
int neighbourCount = 0;
int blobRectSize = (blob.MaxX - blob.MinX) < (blob.MaxY - blob.MinY) ? (blob.MaxX - blob.MinX) : (blob.MaxY - blob.MinY);
double radius = blobRectSize;
while (neighbourCount != blobList.Count)
{
neighbourCount = blobList.Count(b =>
{
if (BlobHasItem(avgArea, b) >= 1)
{
double distance = blob.Centroid.DistanceTo(b.Centroid);
return distance < radius;
}
return false;
});
if (neighbourCount > leastNeighbourBlobCount)
{
markBlob = blob;
return radius;
}
radius = radius + blobRectSize;
if (radius > leastNeighbourBlobCount * blobRectSize)
{
break;
}
}
}
}
return Math.Sqrt(avgArea);
}
private static CvBlobs AutoThreshBlobs(ref Mat imageMat, int blobArea = -1)
{
if (blobArea == -1)
{
//获取元器件特征时,假定的blob面积
blobArea = 3;
}
Mat[] mats = new Mat[] { imageMat };//一张图片,初始化为panda
Mat hist = new Mat();//用来接收直方图
int[] channels = new int[] { 0 };//一个通道,初始化为通道0
int[] histsize = new int[] { 256 };//一个通道,初始化为256箱子
Rangef[] range = new Rangef[1];//一个通道,值范围
range[0].Start = 0.0F;//从0开始(含)
range[0].End = 256.0F;//到256结束(不含)
Mat mask = new Mat();//不做掩码
Cv2.CalcHist(mats, channels, mask, hist, 1, histsize, range);//计算灰度图,dim为1 1维
double total = 0;
for (int i = 0; i < 256; i++)//灰度值总数量
{
total = total + hist.Get<double>(i);
}
double percent = 0;
int startIndex = -1;
int endIndex = -1;
for (int i = 0; i < 256; i++)//直方图
{
double len = hist.Get<double>(i);
if (len > 100)
{//灰度值的像素数小于100的忽略
percent = percent + len / total;
if (startIndex == -1)
{
startIndex = i;
}
//近似的认为元器件的灰度值 数量占总数的百分比小于10%
if (percent > 0.1)
{
endIndex = i - 1;
break;
}
}
}
//int avgIndex = (startIndex + endIndex) / 2;
//Mat threshMat = new Mat();
//Cv2.Threshold(imageMat, threshMat, avgIndex, 255, ThresholdTypes.BinaryInv);
//CvBlobs resultBlobs = new CvBlobs();
//resultBlobs.Label(threshMat);
//List<CvBlob> autoBlobList = resultBlobs.Values.Where(b => b.Area > blobArea).ToList();
//int blobCount = resultBlobs.Count();
Mat threshMat = new Mat();
int blobCount = 0;
CvBlobs resultBlobs = new CvBlobs();
int threshIndex = (startIndex + endIndex) / 2;
Console.WriteLine("Avg Thresh: " + threshIndex + " blobArea =" + blobArea);
double theArea = blobArea * 0.8;
if (theArea < 1) theArea = 1;
for (int index = startIndex; index < endIndex; index++)
{
Mat tempThreshMat = new Mat();
Cv2.Threshold(imageMat, tempThreshMat, threshIndex, 255, ThresholdTypes.BinaryInv);
CvBlobs blobs = new CvBlobs();
blobs.Label(tempThreshMat);
List<CvBlob> blobList = blobs.Values.Where(b => b.Area > theArea).ToList();
if (blobList.Count > blobCount)
{
threshMat = tempThreshMat;
threshIndex = index;
resultBlobs = blobs;
blobCount = blobList.Count;
}
}
imageMat = threshMat;
Console.WriteLine("result thresh: " + threshIndex + "==== Blob: " + blobCount + " Area:" + theArea);
return resultBlobs;
}
/// <summary>
/// 二值化图像
/// </summary>
/// <param name="imageMat"></param>
/// <param name="thresh"></param>
/// <param name="inv"></param>
/// <returns></returns>
private static Mat Threshhold(Mat imageMat, int thresh = -1)
{
Mat dst = new Mat();
Cv2.CvtColor(imageMat, dst, ColorConversionCodes.RGB2GRAY);
if (thresh == -1)
{
//全局自动二值 化
Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.BinaryInv);
//自动局部二值化
//Binarizer.Sauvola(dst, dst, 221, 0.02, 232);
//Cv2.AdaptiveThreshold(dst, dst, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 5, 0);
}
else
{
//二值化
Cv2.Threshold(dst, dst, thresh, 255, ThresholdTypes.BinaryInv);
}
return dst;
}
/// <summary>
/// 获取所有Blobs
/// </summary>
/// <param name="imageMat"></param>
/// <param name="thresh"></param>
/// <param name="inv"></param>
/// <returns></returns>
private static List<CvBlob> GetBlobs(Mat imageMat, int thresh = -1)
{
Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.RGBA2BGR);
Mat dst = Threshhold(imageMat, thresh);
CvBlobs blobs = new CvBlobs();
blobs.Label(dst);
List<CvBlob> blobList = blobs.Values.Where(b => b.Area > 0).ToList();
return blobList;
}
/// <summary>
/// 给定Blob包含几个元器件
/// </summary>
/// <param name="averageArea"></param>
/// <param name="blob"></param>
/// <returns></returns>
public static int BlobHasItem(int averageArea, CvBlob blob)
{
int blobArea = blob.Area;
double minArea = 0.5 * averageArea;
if (averageArea < 50)
{
minArea = 0.2 * averageArea;
}
if (blobArea < minArea)
{
return 0;
}
//if (blobArea >= 0.5 * averageArea && blobArea <= 1.5 * averageArea)
//{
// return 1;
//}
//else if (blobArea > 1.5 * averageArea && blobArea <= 3 * averageArea)
//{
// return 2;
//}
//else if (blobArea > 3.5 * averageArea && blobArea < 5.5 * averageArea)
//{
// return 3;
//}
int count = (int)((blobArea + 1.5 * averageArea) / (1.5 * averageArea));
if (count == 0)
{
count = 1;
}
if (count <= 5000)
{
return count;
}
return 1;
}
/// <summary>
/// 读取Raw格式图片
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
private static Bitmap[] ReadRaw(string imagePath)
{
byte[] buff = System.IO.File.ReadAllBytes(imagePath);
if (buff == null || buff.Length == 0)
{
return null;
}
bool needRevertLayer = false;
for (int i = 0; i < buff.Length; i++)
{
if (buff[i] != 0)
{
if (i > 65535)
{
byte[] b = new byte[buff.Length - 65535];
Array.Copy(buff, 65535, b, 0, b.Length);
buff = b;
needRevertLayer = true;
}
break;
}
}
byte[] buffer_src = new byte[buff.Length / 2];
byte[] buffer_filter = new byte[buff.Length / 2];
for (int i = 0; i < buffer_src.Length; i++)
{
byte currentByte = buff[i * 2];
byte filterByte = buff[i * 2 + 1];
if (needRevertLayer)
{
currentByte = (byte)(currentByte * 3);
filterByte = (byte)(filterByte * 3);
}
buffer_src[i] = currentByte;
if (filterByte == 1)
buffer_filter[i] = currentByte;
else
{
//buffer_filter[i] = 255;
buffer_filter[i] = filterByte;
}
}
Bitmap filter_bitmap = ToImage32(buffer_filter);
Bitmap src_bitmap = ToImage32(buffer_src);
//翻转图层
if (needRevertLayer)
{
return new Bitmap[] { filter_bitmap, src_bitmap };
}
else
{
return new Bitmap[] { src_bitmap, filter_bitmap };
}
}
/// <summary>
/// 8位灰度转32位图像
/// </summary>
/// <returns></returns>
private static Bitmap ToImage32(byte[] buff)
{
int w = Convert.ToInt32(Math.Sqrt(buff.Length));
int a = buff.Length % w;
if (a != 0)
{
w = w - 1;
}
int n = 0;
byte[] bb = new byte[buff.Length * 4];
for (int i = 0; i < buff.Length; i++)
{
byte currentByte = buff[i];
//currentByte = (byte)(Math.Log(1 + currentByte) * 255);
bb[n++] = currentByte;
bb[n++] = currentByte;
bb[n++] = currentByte;
bb[n++] = 255;
}
Bitmap bmp = new Bitmap(w, w, PixelFormat.Format32bppArgb);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, w, w), ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr ptrBmp = bmpData.Scan0;
System.Runtime.InteropServices.Marshal.Copy(bb, 0, ptrBmp, bmpData.Stride * w);
bmp.UnlockBits(bmpData);
return bmp;
}
private static List<OpenCvSharp.Point> toContourPoints(CvContourChainCode contour)
{
List<OpenCvSharp.Point> contourPoints = new List<OpenCvSharp.Point>();
contourPoints.Add(contour.StartingPoint);
int x = contour.StartingPoint.X;
int y = contour.StartingPoint.Y;
foreach (CvChainCode cc in contour.ChainCode)
{
x += CvBlobConst.ChainCodeMoves[(int)cc][0];
y += CvBlobConst.ChainCodeMoves[(int)cc][1];
contourPoints.Add(new OpenCvSharp.Point(x, y));
}
return contourPoints;
}
private static CvBlob findMarkBlob(List<CvBlob> blobList, int markX = -1, int markY = -1, int thresh = -1, bool inv = true)
{
int blobCount = blobList.Count;
int selectIndex = blobCount / 2;
if (markX != -1 && markY != -1)
{
//查找标记的Blob
int markIndex = -1;
for (int i = 0; i < blobCount; i++)
{
CvBlob blob = blobList[i];
if (blob.Rect.Contains(new OpenCvSharp.Point(markX, markY)))
{
if (markIndex == -1 || blobList[i].Area < blobList[markIndex].Area)
{
markIndex = i;
}
}
}
if (markIndex != -1)
{
CvBlob markBlob = blobList[markIndex];
return markBlob;
}
}
return null;
}
/// <summary>
/// 查找Blob中包含的所有与给定半径差不多的内接圆
/// </summary>
/// <param name="matDistanceArr"></param>
/// <param name="blobs"></param>
/// <param name="blob"></param>
/// <param name="reelCenter"></param>
/// <param name="oneBlobWidth"></param>
/// <param name="oneBlobRadius"></param>
/// <returns></returns>
public static SplitItem findCircleInBlob(double[,] matDistanceArr, CvBlobs blobs, CvBlob blob, Point2d reelCenter, double oneBlobWidth= -1, double oneBlobRadius = -1)
{
SplitItem item = new SplitItem();
while (true)
{
bool hasFind = false;
bool hasPixToHandle = false;
for (int x = blob.MinX; x< blob.MaxX; x++)
{
for (int y = blob.MinY; y < blob.MaxY; y++)
{
double distance = matDistanceArr[x, y];
if (distance > 0)
{
int label = blobs.GetLabel(x, y);
if (label != blob.Label)
{
//不是当前Blob的像素
//matDistanceArr[x, y] = 0;
continue;
}
hasPixToHandle = true;
if (!item.isEnd)
{
double distanceToCircle = item.minDistanceToCircles(x, y, reelCenter);
if (distanceToCircle == 0)
{
matDistanceArr[x, y] = 0;
continue;
}
if (distanceToCircle> 0 && distanceToCircle < distance)
{
distance = distanceToCircle;
matDistanceArr[x, y] = distance;
}
if (distance > item.currentMaxRadius)
{
item.currentMaxRadius = distance;
item.centerX = x;
item.centerY = y;
if (oneBlobRadius != -1 && distance >= oneBlobRadius)
{
item.calOneItem(oneBlobRadius);
hasFind = true;
break;
}
}
}
}
}
if (hasFind)
{
break;
}
}
if (!hasFind)
{
item.calOneItem(oneBlobRadius);
}
if (item.isEnd || !hasPixToHandle)
{
break;
}
}
return item;
}
/// <summary>
/// 查找Blobs包含的元器件数量
/// </summary>
/// <param name="srcMat"></param>
/// <param name="threshMat"></param>
/// <param name="blobs"></param>
/// <param name="avgArea"></param>
/// <returns></returns>
public static int findCircles(ref Mat srcMat, Mat threshMat, CvBlobs blobs, int avgArea)
{
Mat distanceMat = new Mat();
Cv2.DistanceTransform(threshMat, distanceMat, DistanceTypes.L2, DistanceMaskSize.Mask3);
double[,] distanceArr = new double[threshMat.Cols, threshMat.Rows];
IntPtr dddd = distanceMat.Data;
Console.WriteLine("Start to distance array");
unsafe
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int y = 0; y < threshMat.Rows; y++)
{
for (int x = 0; x < threshMat.Cols; x++)
{
float* dd = (float*)distanceMat.Ptr(y, x);
distanceArr[x, y] = dd[0];
//float atValue = distanceMat.At<float>(y, x);
//distanceArr[x, y] = atValue;
//if (atValue != dd[0])
//{
// Console.WriteLine("rho=" + dd[0].ToString() + " atValue=" + atValue);
//}
}
}
sw.Stop();
Console.WriteLine("=" + sw.ElapsedMilliseconds + " ms");
}
Dictionary<int, SplitItem> blobCircles = new Dictionary<int, SplitItem>();
Console.WriteLine("Start find reel center");
Point2d reelCenter = new Point2d(0,0) ;
//查找中心
foreach (CvBlob blob in blobs.Values)
{
int count = BlobHasItem(avgArea, blob);
if (count > 10 && reelCenter.X == 0)
{
Point2d center = blob.Centroid;
//中间的圆,查找圆心
if (center.DistanceTo(new Point2d(srcMat.Cols / 2, srcMat.Rows / 2)) < 200)
{
reelCenter = center;
srcMat.Line(new OpenCvSharp.Point(center.X-10, center.Y), new OpenCvSharp.Point(center.X+10, center.Y), Scalar.Blue);
srcMat.Line(new OpenCvSharp.Point(center.X, center.Y-10), new OpenCvSharp.Point(center.X, center.Y+10), Scalar.Blue);
break;
}
}
}
Console.WriteLine("Start find reel Max Radius, max Width");
//最大
double maxRadius = 0;
double maxWidth = 0;
foreach (CvBlob blob in blobs.Values)
{
int count = BlobHasItem(avgArea, blob);
if (count == 1)
{
if (blob.Rect.Width > maxWidth)
{
maxWidth = blob.Rect.Width;
}
if (blob.Rect.Height > maxWidth)
{
maxWidth = blob.Rect.Height;
}
SplitItem item = findCircleInBlob(distanceArr, blobs, blob, reelCenter);
foreach (Circle c in item.circles)
{
if (c.radius > maxRadius || maxRadius == 0)
{
maxRadius = c.radius;
}
//srcMat.Circle(c.x, c.y, (int)c.radius, Scalar.Green);
}
}
}
//放大宽度,防止误判断
maxWidth = maxWidth * 1.1;
Console.WriteLine("Start count");
int totalCount = 0;
foreach (CvBlob blob in blobs.Values)
{
int count = BlobHasItem(avgArea, blob);
if(count == 1)
{
//单个元器件
totalCount = totalCount +1;
srcMat.Circle((int)blob.Centroid.X, (int)blob.Centroid.Y, (int)maxRadius/2, Scalar.LightGreen);
}
else if (count > 1)
{
if (count > 20)
{
//中间的圆,去除
if(blob.Centroid.DistanceTo(new Point2d(srcMat.Cols / 2, srcMat.Rows / 2)) < 200)
{
continue;
}
}
//多个元器件,查找 所有圆
SplitItem item = findCircleInBlob(distanceArr, blobs, blob, reelCenter, maxWidth, maxRadius);
//对所有圆进行分组
List<List<Circle>> groupCircles = item.groupCircles(maxWidth, maxRadius, reelCenter);
Scalar color = Scalar.RandomColor();
blob.Contour.Render(srcMat, color);
foreach (List<Circle> groupCircle in groupCircles)
{
Circle c = groupCircle[0];
srcMat.Circle(c.x, c.y, (int)c.radius/2, Scalar.Yellow);
totalCount = totalCount + 1;
//foreach (Circle cg in groupCircle)
//{
// srcMat.Circle(cg.x, cg.y, (int)c.radius, color);
//}
}
}
}
Cv2.PutText(srcMat, totalCount + "", new OpenCvSharp.Point(reelCenter.X-40, reelCenter.Y+30), HersheyFonts.HersheySimplex, 1.0, Scalar.LightGreen);
Console.WriteLine("===========" + totalCount);
return totalCount;
}
//TODO: 测试距离变换,用后删除
public static Image DistanceTransform(Image image)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
Mat gray = new Mat();
Cv2.CvtColor(imageMat, gray, ColorConversionCodes.RGB2GRAY);
////开运算
Mat k1 = Mat.Ones(new OpenCvSharp.Size(1, 1), MatType.CV_8UC1);
Cv2.MorphologyEx(gray, gray, MorphTypes.Open, k1, new OpenCvSharp.Point(0, 0), 3);
Mat distanceMat = new Mat();
Mat labels = new Mat() ;
Cv2.DistanceTransform(gray, distanceMat, DistanceTypes.L2, DistanceMaskSize.Mask3) ;
Cv2.Normalize(distanceMat, gray, 0, 255, NormTypes.MinMax);
gray.ConvertTo(gray, MatType.CV_8UC1);
Cv2.Threshold(gray, gray, 0, 255, ThresholdTypes.Otsu);
Mat colorImg = Mat.Zeros(gray.Size(), MatType.CV_8UC3);
Cv2.ConnectedComponents(gray, labels, PixelConnectivity.Connectivity8);
Dictionary<int, SplitItem> blobCircles = new Dictionary<int, SplitItem>();
for(int y=0;y<labels.Rows; y++)
{
for (int x = 0; x < labels.Cols; x++)
{
int label = labels.At<int>(y, x);
float distance = distanceMat.At<float>(y, x);
SplitItem item = new SplitItem();
if (blobCircles.ContainsKey(label))
{
item = blobCircles[label];
}
if (distance > item.currentMaxRadius)
{
item.currentMaxRadius = distance;
item.centerX = x;
item.centerY = y;
}
blobCircles[label] = item;
byte b = (byte)(label % 255);
byte g = 0;
if (b < 128 && b>0)
{
g = (byte)(255 - b);
}
Vec3b color = new Vec3b(b,g,0);
colorImg.Set<Vec3b>(y, x, color);
}
}
foreach (SplitItem circle in blobCircles.Values)
{
circle.calOneItem(-1);
}
while (true)
{
for (int y = 0; y < labels.Rows; y++)
{
for (int x = 0; x < labels.Cols; x++)
{
int label = labels.At<int>(y, x);
if (label == 0) continue;
SplitItem item = new SplitItem();
if (blobCircles.ContainsKey(label))
{
item = blobCircles[label];
}
if (!item.isEnd)
{
double distance = distanceMat.At<float>(y, x);
//此Blob未结束
// bool validPoint = item.isValidPoint(x, y);
bool validPoint = false;
if (validPoint)
{
if (distance > item.currentMaxRadius)
{
item.currentMaxRadius = distance;
item.centerX = x;
item.centerY = y;
blobCircles[label] = item;
}
}
}
}
}
bool needContinue = false;
foreach (SplitItem circle in blobCircles.Values)
{
circle.calOneItem();
if (!circle.isEnd)
{
needContinue = true;
}
}
if (!needContinue)
{
break;
}
}
int totalCount = 0;
foreach (SplitItem item in blobCircles.Values)
{
foreach(Circle circle in item.circles)
{
Cv2.Circle(colorImg, circle.x, circle.y, (int)circle.radius,Scalar.White);
totalCount++;
}
}
Console.WriteLine("Total: " + totalCount);
return BitmapConverter.ToBitmap(colorImg);
//dist.SaveImage("d:\\image\\dsitdist1.jpg");
//Cv2.Threshold(dist, dist, 79, 255, ThresholdTypes.Binary);
//Cv2.CvtColor(dist,dist,ColorConversionCodes.BGRA2BGR);
//dist.ConvertTo(dist, MatType.CV_8UC1);
//image = BitmapConverter.ToBitmap(dist);
//return image;
}
/// <summary>
/// 获取单个元器件的特征
/// </summary>
/// <param name="image"></param>
/// <param name="markX"></param>
/// <param name="markY"></param>
/// <returns></returns>
public static int GetFeature(ref Image image, int markX, int markY)
{
Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
Mat dst = new Mat();
Cv2.CvtColor(imageMat, dst, ColorConversionCodes.RGB2GRAY);
//全局二值化
//Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.BinaryInv);
//image = BitmapConverter.ToBitmap(dst);
//CvBlobs blobs = new CvBlobs();
//blobs.Label(dst);
CvBlobs blobs = AutoThreshBlobs(ref dst);
image = BitmapConverter.ToBitmap(dst);
int blobArea = -1;
foreach (CvBlob blob in blobs.Values) {
if (blob.Rect.Contains(new OpenCvSharp.Point(markX, markY)))
{
if (blob.Area < blobArea || blobArea == -1)
{
blobArea = blob.Area;
}
}
}
return blobArea;
}
}
}