ImageUtil.cs 62.4 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 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
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)
        {
            Bitmap bitmap = new Bitmap(image);
            Mat imageMat = BitmapConverter.ToMat(bitmap);
            RadiusPt radiusPt, radiusPtOut;
            GetCenter(imageMat, out radiusPt);
            GetOutContour(imageMat, out radiusPtOut);
            Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.RGBA2BGR);
            Mat grayMat = BitmapConverter.ToMat(bitmap);
            Cv2.CvtColor(grayMat, grayMat, ColorConversionCodes.RGB2GRAY);
            CvBlobs blobs = AutoThreshBlobs(ref grayMat, itemArea,out itemArea,radiusPt,radiusPtOut);
            int totalCount = findCircles(ref imageMat, grayMat, blobs, itemArea,radiusPt,radiusPtOut);
            //imageMat = grayMat;
            //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);
        }
        //百分比阀值
        public static int GetPTileThreshold(Mat hist, double tile = 40)
        {
            int Y;
            double amount = 0, sum = 0;
            for (Y = 0; Y < 256; Y++) amount += hist.Get<float>(Y);
            for (Y = 0; Y < 256; Y++)
            {
                sum = sum + hist.Get<float>(Y);
                if (sum >= amount * tile / 100) return Y;
            }
            return -1;
        }
        //判断直方图是否是双峰的函数
        public static bool IsDimodal(double[] histGram)
        {
            int count = 0;
            for (int i = 1; i < 255; i++)
            {
                if (histGram[i - 1] < histGram[i] && histGram[i + 1] < histGram[i])
                {
                    count++;
                    if (count > 2) return false;
                }
            }
            if (count == 2)
                return true;
            else
                return false;
        }
        //基于双峰平均值的阈值
        public static int GetIntermodesThreshold(Mat hist)
        {
            int Y, Iter = 0, Index;
            double[] HistGramC = new double[256];           // 基于精度问题,一定要用浮点数来处理,否则得不到正确的结果
            double[] HistGramCC = new double[256];          // 求均值的过程会破坏前面的数据,因此需要两份数据
            for (Y = 0; Y < 256; Y++)
            {
                HistGramC[Y] = hist.Get<float>(Y);
                HistGramCC[Y] = hist.Get<float>(Y);
            }
            // 通过三点求均值来平滑直方图
            while (IsDimodal(HistGramCC) == false)                                                  // 判断是否已经是双峰的图像了      
            {
                HistGramCC[0] = (HistGramC[0] + HistGramC[0] + HistGramC[1]) / 3;                   // 第一点
                for (Y = 1; Y < 255; Y++)
                    HistGramCC[Y] = (HistGramC[Y - 1] + HistGramC[Y] + HistGramC[Y + 1]) / 3;       // 中间的点
                HistGramCC[255] = (HistGramC[254] + HistGramC[255] + HistGramC[255]) / 3;           // 最后一点
                System.Buffer.BlockCopy(HistGramCC, 0, HistGramC, 0, 256 * sizeof(double));         // 备份数据,为下一次迭代做准备
                Iter++;
                if (Iter >= 10000) return -1;                                                       // 似乎直方图无法平滑为双峰的,返回错误代码
            }
            // 阈值为两峰值的平均值
            int[] Peak = new int[2];
            for (Y = 1, Index = 0; Y < 255; Y++)
                if (HistGramCC[Y - 1] < HistGramCC[Y] && HistGramCC[Y + 1] < HistGramCC[Y]) Peak[Index++] = Y - 1;
            return ((Peak[0] + Peak[1]) / 2);

        }

        private static CvBlobs AutoThreshBlobs(ref Mat imageMat,int blobArea,out int standArea,RadiusPt radiusPt,RadiusPt radiusPtOut)
        {
            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的忽略
                    if (startIndex == -1)
                    {
                        startIndex = i;
                    }
                    endIndex = i - 1;
                    percent = percent + len / total;
                    //近似的认为元器件的灰度值 数量占总数的百分比小于10%
                    if (percent > 0.1)
                    {
                        break;
                    }
                }
            }

            int avgIndex = (startIndex + endIndex) / 2;

            //int avgIndex = GetIntermodesThreshold(hist);

            Mat threshMat = new Mat();
            Cv2.Threshold(imageMat, threshMat, avgIndex, 255, ThresholdTypes.BinaryInv);
            //Mat erodeMat = Mat.Ones(new OpenCvSharp.Size(3, 3), MatType.CV_8UC1);
            //Cv2.MorphologyEx(threshMat,threshMat,MorphTypes.Open,erodeMat);
            CvBlobs resultBlobs = new CvBlobs();
            resultBlobs.Label(threshMat);
            List<CvBlob> autoBlobList = resultBlobs.Values.Where(b => b.Area > blobArea).ToList();
            int blobCount = resultBlobs.Count();
            int threshIndex = avgIndex;
            double theArea = blobArea * 0.8;
            if (theArea < 1) theArea = 1;

            while (true)
            {
                //阈值向下走,找满足条件Blob数量最多的
                threshIndex = threshIndex - 1;
                Cv2.Threshold(imageMat, threshMat, threshIndex, 255, ThresholdTypes.BinaryInv);
                //Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open, erodeMat);
                CvBlobs blobs = new CvBlobs();
                blobs.Label(threshMat);
                List<CvBlob> blobList = blobs.Values.Where(b => b.Area > theArea).ToList();
                if (blobList.Count > blobCount)
                {
                    resultBlobs = blobs;
                    blobCount = blobList.Count;
                }
                else
                {
                    break;
                }
            }
            threshIndex = avgIndex;
            while (true)
            {
                //阈值向上走,找满足条件Blob数量最多的
                threshIndex = threshIndex + 1;
                Cv2.Threshold(imageMat, threshMat, threshIndex, 255, ThresholdTypes.BinaryInv);
                //Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open, erodeMat);
                CvBlobs blobs = new CvBlobs();
                blobs.Label(threshMat);
                List<CvBlob> blobList = blobs.Values.Where(b => b.Area > theArea).ToList();
                if (blobList.Count > blobCount)
                {
                    resultBlobs = blobs;
                    blobCount = blobList.Count;
                }
                else
                {
                    break;
                }
            }

            List<CvBlob> averBlobs = resultBlobs.Values.Where(a => a.Area > blobArea * 0.5 && a.Area < blobArea * 3).ToList();
            if (averBlobs.Count != 0 && blobArea < 120)
            {
                double averArea = averBlobs.Sum(a => a.Area) / averBlobs.Count;
                double veri = averBlobs.Sum(a => Math.Pow(a.Area - averArea, 2)) / averBlobs.Count;
                double standerdeviation = Math.Sqrt(veri);
                standArea = (int)Math.Round(averArea + standerdeviation);
                threshIndex = avgIndex;
                theArea = (int)Math.Round(averArea - standerdeviation);
                while (true)
                {
                    //阈值向下走,找满足条件Blob数量最多的
                    threshIndex = threshIndex - 1;
                    Cv2.Threshold(imageMat, threshMat, threshIndex, 255, ThresholdTypes.BinaryInv);
                    //Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open, erodeMat);
                    CvBlobs blobs = new CvBlobs();
                    blobs.Label(threshMat);
                    List<CvBlob> blobList = blobs.Values.Where(b => b.Area > theArea).ToList();
                    if (blobList.Count > blobCount)
                    {
                        resultBlobs = blobs;
                        blobCount = blobList.Count;
                    }
                    else
                    {
                        break;
                    }
                }
                threshIndex = avgIndex;
                while (true)
                {
                    //阈值向上走,找满足条件Blob数量最多的
                    threshIndex = threshIndex + 1;
                    Cv2.Threshold(imageMat, threshMat, threshIndex, 255, ThresholdTypes.BinaryInv);
                    //Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open, erodeMat);
                    CvBlobs blobs = new CvBlobs();
                    blobs.Label(threshMat);
                    List<CvBlob> blobList = blobs.Values.Where(b => b.Area > theArea).ToList();
                    if (blobList.Count > blobCount)
                    {
                        resultBlobs = blobs;
                        blobCount = blobList.Count;
                    }
                    else
                    {
                        break;
                    }
                }

                List<CvBlob> blobL = resultBlobs.Values.Where(a => a.Area > 0 && a.Area < averArea * 3).ToList();
                standArea = (int)Math.Round((double)blobL.Sum(a => a.Area) / blobL.Count);

            }
            else
            {
                standArea = blobArea;
            }
            imageMat = threshMat;
            Console.WriteLine("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;
            double k = 1.5;
            if (averageArea < 50)
            {
                minArea = 0.2 * averageArea;
            }
            if (blobArea < minArea*2/3)
            {
                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 = 0;
            //if (blobArea < 130)
            //{
            //    count = (int)((blobArea + k * averageArea) / (k * averageArea));
            //}
            //else
            //{
            //    count = (int)Math.Round((blobArea + k * averageArea) / (k * averageArea));
            //}
            //count = (int)((blobArea + k * averageArea) / (k * averageArea));
            count = (int)((blobArea + k * averageArea) / (k * averageArea));

            if (count == 0 || count == 1)
            {
                count = 1;
            }
            //if (count <= 10000)
            //{
                return count;
            //}
            //return 0;
        }

        /// <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;
        }
        public struct CircleStruct
        {
           public  OpenCvSharp.Point centerPt;
            public double radius;
        }
        private static int startI = -1;
        private static List<CircleStruct> resultList = new List<CircleStruct>();
        private static List<List<CircleStruct>> spitList = new List<List<CircleStruct>>();
        private static CircleStruct circleStruct = new CircleStruct();
        //private static List<CircleStruct> sampList = new List<CircleStruct>();
        /// <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 List<List<CircleStruct>> findCircleInBlobNew(double[,] matDistanceArr, CvBlobs blobs, CvBlob blob, Point2d reelCenter, double oneBlobWidth = -1, double oneBlobRadius = -1)
        {          
            resultList.Clear();
            spitList.Clear();          
            for (int y = blob.MinY; y < blob.MaxY; y++)
            {
                for (int x = blob.MinX; x < blob.MaxX; x++)

                {
                    double distance = matDistanceArr[x, y];
                    if (distance > 0)
                    {
                        int label = blobs.GetLabel(x, y);
                        if (label != blob.Label)
                        {
                            continue;
                        }
                        else
                        {
                            if (distance >= oneBlobRadius*2/3)
                            {
                                circleStruct.centerPt.X = x;
                                circleStruct.centerPt.Y = y;
                                circleStruct.radius = oneBlobRadius*2/3;
                                if (startI == -1)
                                {
                                    startI = 1;
                                    resultList.Add(circleStruct);
                                }
                                else
                                {
                                    bool intersectionB = false;
                                    foreach (CircleStruct item in resultList)
                                    {
                                        if (item.centerPt.DistanceTo(circleStruct.centerPt) <= item.radius)
                                        {
                                            intersectionB = true;
                                            break;
                                        }
                                    }
                                    if (!intersectionB)
                                    {
                                        resultList.Add(circleStruct);
                                    }
                                }
                            }
                        }

                    }

                }

            }
            //分离          
            while (resultList.Count != 0)
            {
                List<CircleStruct> sampList = new List<CircleStruct>();
                CircleStruct itemC = new CircleStruct();
                //sampList.Clear();
                bool startB = false;
                for (int i = 0; i < resultList.Count; i++)
                {
                    if (!startB)
                    {
                        startB = true;
                        sampList.Add(resultList[i]);
                        itemC = resultList[i];
                        resultList.RemoveAt(i);
                        i -= 1;
                    }
                    else
                    {
                        for (int j = 0; j < sampList.Count; j++)
                        {
                            double distan = Math.Abs(resultList[i].centerPt.DistanceTo(new OpenCvSharp.Point(reelCenter.X, reelCenter.Y)) - sampList[j].centerPt.DistanceTo(new OpenCvSharp.Point(reelCenter.X, reelCenter.Y)));
                            if (distan <= oneBlobRadius*1.78  && resultList[i].centerPt.DistanceTo(itemC.centerPt) <= oneBlobWidth*1.1)
                            {
                                sampList.Add(resultList[i]);
                                resultList.RemoveAt(i);
                                i -= 1;
                                break;
                            }
                            else
                            {
                                break;
                            }

                        }
                    }
                }
                spitList.Add(sampList);
                if (resultList.Count < spitList[spitList.Count - 1].Count / 9)
                    break;
            }
            return spitList;
        }

        /// <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, RadiusPt radiusPt,RadiusPt radiusPtOut)
        {
            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];                     
                    }
                }
                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) ;
            ////查找中心            
            reelCenter.X = radiusPtOut.pt.X;
            reelCenter.Y = radiusPtOut.pt.Y;
            srcMat.Line(new OpenCvSharp.Point(radiusPtOut.pt.X - 10, radiusPtOut.pt.Y), new OpenCvSharp.Point(radiusPtOut.pt.X + 10, radiusPtOut.pt.Y), Scalar.Blue);
            srcMat.Line(new OpenCvSharp.Point(radiusPtOut.pt.X, radiusPtOut.pt.Y - 10), new OpenCvSharp.Point(radiusPtOut.pt.X, radiusPtOut.pt.Y + 10), Scalar.Blue);          
            Console.WriteLine("Start find reel Max Radius, max Width");
            //最大
            double maxRadius = 0;
            double maxWidth = 0;
            List<SplitItem> averItem = new List<SplitItem>();
            averItem.Clear();
            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);
                    averItem.Add(item);

                    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);
                    }
                }
            }
            //平均半径
            double averRadius = averItem.Sum(a => a.circles.Sum(b => b.radius)) / averItem.Sum(a => a.circles.Count);
            //maxRadius = averRadius*3/2;
            maxRadius = averRadius;
            //放大宽度,防止误判断
            //maxWidth = maxWidth * 1.6;
            Console.WriteLine("Start count");
            int totalCount = 0;
            bool end = false;
            foreach (CvBlob blob in blobs.Values)
            {
                int count = BlobHasItem(avgArea, blob);
                if (count == 1)
                {
                    //单个元器件
                    if (blob.Centroid.DistanceTo(new Point2d(radiusPt.pt.X,radiusPt.pt.Y)) < radiusPt.radius-10)
                    {
                        continue;
                    }
                    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(reelCenter) < radiusPt.radius)
                    //    {
                    //        continue;
                    //    }
                    //    //if (blob.Centroid.DistanceTo(new Point2d(srcMat.Cols / 2, srcMat.Rows / 2)) < 200)
                    //    //{
                    //    //    continue;
                    //    //}
                    //}
                    if (blob.Centroid.DistanceTo(new Point2d(radiusPt.pt.X, radiusPt.pt.Y)) < radiusPt.radius-10)
                    {
                        continue;
                    }
                    //////多个元器件,查找 所有圆
                    //SplitItem item = findCircleInBlob(distanceArr, blobs, blob, reelCenter, maxWidth, maxRadius);
                    ////对所有圆进行分组
                    //List<List<Circle>> groupCircles = item.groupCircles(maxWidth, maxRadius, reelCenter);
                    //foreach (List<Circle> groupCircle in groupCircles)
                    //{
                    //    if (groupCircle.Count == 0)
                    //    {
                    //        continue;
                    //    }
                    //    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)cg.radius, color);
                    //    //}
                    //}

                    List<List<CircleStruct>> resultList = findCircleInBlobNew(distanceArr, blobs, blob, reelCenter, maxWidth, maxRadius);
                    foreach (List<CircleStruct> item in resultList)
                    {
                        
                        srcMat.Circle(item[0].centerPt, (int)item[0].radius, Scalar.Yellow);
                        totalCount = totalCount + 1;
                    }                    
                }
            }

            Cv2.PutText(srcMat, totalCount + "", new OpenCvSharp.Point(reelCenter.X-40, reelCenter.Y+30), HersheyFonts.HersheySimplex, 1.0, Scalar.LightGreen);
            Console.WriteLine("===========" + totalCount);
            return totalCount;

        }

        private static List<CircleStruct> GetMaxDistance(CvBlob item, double[,] distanceArr, CvBlobs blobs)
        {
            double maxDistance = -1;
            double standerd = -1;
            int maxX = -1;
            int maxY = -1;
            CircleStruct pR = new CircleStruct();
            List<CircleStruct> pTList = new List<CircleStruct>();
            bool selectB = false;
            while (true)
            {
                bool blobB = false;
                bool threreIs = false;
                for (int Y = item.MinY; Y < item.MaxY; Y++)
                {
                    for (int X = item.MinX; X < item.MaxX; X++)
                    {
                        double distance = distanceArr[X, Y];
                        if (item.Label != blobs.GetLabel(X, Y))
                        {
                            continue;
                        }
                        if (!selectB)
                        {
                            if (maxDistance == -1)
                            {
                                if (distance < 0)
                                {
                                    continue;
                                }
                                maxDistance = distance;
                                maxX = X;
                                maxY = Y;
                                pR.centerPt.X = X;
                                pR.centerPt.Y = Y;
                                pR.radius = distance;
                                blobB = true;
                            }
                            else
                            {
                                if (maxDistance < distance)
                                {
                                    maxDistance = distance;
                                    maxX = X;
                                    maxY = Y;
                                    pR.centerPt.X = X;
                                    pR.centerPt.Y = Y;
                                    pR.radius = distance;
                                    blobB = true;
                                }
                            }
                        }
                        else
                        {
                            if (distance > maxDistance * 0.7)
                            {
                                foreach (var singleBlob in pTList)
                                {
                                    if (singleBlob.centerPt.DistanceTo(new OpenCvSharp.Point(X, Y)) < singleBlob.radius + distance)
                                    {
                                        threreIs = true;
                                        break;
                                    }
                                }
                                if (threreIs)
                                {
                                    threreIs = false;
                                    continue;
                                }
                                standerd = distance;
                                pR.centerPt.X = X;
                                pR.centerPt.Y = Y;
                                pR.radius = distance;
                                blobB = true;
                            }

                        }



                    }
                }


                selectB = true;
                if (!blobB)
                {
                    break;
                }
                pTList.Add(pR);
            }
            return pTList;

        }
        public static int GetGrayValue(ref Image image, int markX, int markY)
        {
            Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
            RadiusPt radiusPt, radiusPtOut;
            GetCenter(imageMat, out radiusPt);
            GetOutContour(imageMat, out radiusPtOut);
            Mat grayMat = new Mat();
            Mat thresholdMat = new Mat();
            int minThreshold = -1;
            CvBlobs blobs = new CvBlobs();
            //imageMat.SaveImage("d:\\image\\test\\image.jpg");
            //imageMat = new Mat("d:\\image\\test\\image.jpg");
            Cv2.CvtColor(imageMat, grayMat, ColorConversionCodes.RGB2GRAY);
            Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.BGRA2BGR);
            Mat[] mats = new Mat[] { grayMat };//一张图片,初始化为panda
            //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, true, false);//计算灰度图,dim为1 1维
            minThreshold = GetIntermodesThreshold(hist);
            Cv2.Threshold(grayMat, thresholdMat, minThreshold, 255, ThresholdTypes.BinaryInv);
            blobs.Label(thresholdMat);
            CvBlob selectBlob = null;
            foreach (CvBlob item in blobs.Values)
            {
                if (item.Rect.Contains(markX, markY))
                {
                    if (selectBlob == null)
                    {
                        selectBlob = item;
                    }
                    else
                    {
                        if (selectBlob.Area>item.Area)
                        {
                            selectBlob = item;
                        }
                    }
                }
            }
            if (selectBlob == null)
            {
                return -1;
            }
            selectBlob.Contour.Render(imageMat, Scalar.Red);
            image = BitmapConverter.ToBitmap(imageMat);
            return selectBlob.Area;


        }

        /// <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));
            Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.BGRA2BGR);
            Mat dst = new Mat();


            //Cv2.CvtColor(imageMat, gradMat, ColorConversionCodes.RGB2GRAY);
            ////全局二值化
            //Cv2.Threshold(gradMat, dst, 0, 255, ThresholdTypes.Otsu |ThresholdTypes.BinaryInv);

            //image = BitmapConverter.ToBitmap(dst);
            //CvBlobs blobs = new CvBlobs();
            //blobs.Label(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;
            //        }
            //    }
            //}

            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的忽略
                    if (startIndex == -1)
                    {
                        startIndex = i;
                    }
                    endIndex = i - 1;
                    percent = percent + len / total;
                    //近似的认为元器件的灰度值 数量占总数的百分比小于10%
                    //if (percent > 0.1)
                    //{
                    //    break;
                    //}
                }
            }

            int areaBlob = -1;
            int blobCount = 0;
            Mat grayMat = new Mat();
            CvBlob minBlob = null;
            Cv2.CvtColor(imageMat, grayMat, ColorConversionCodes.RGB2GRAY);

            for (int i = endIndex; i > startIndex; i--)
            {

                CvBlobs blobs = new CvBlobs();
                Cv2.Threshold(grayMat, dst, i, 255, ThresholdTypes.BinaryInv);
                blobs.Label(dst);
                int minArea = -1;
                foreach (CvBlob blob in blobs.Values)
                {
                    if (blob.Rect.Contains(new OpenCvSharp.Point(markX, markY)))
                    {
                        if (blob.Area < minArea || minArea == -1)
                        {
                            minArea = blob.Area;
                            if (minBlob==null)
                            {
                                minBlob = blob;
                            }
                        }
                    }
                }


                List<CvBlob> blobList = blobs.Values.Where(b => b.Area > minArea).ToList<CvBlob>();
                int currentBlobCount = blobList.Count;
                if(currentBlobCount <= 20 || minArea == -1)
                {
                    continue;
                }
                if (minArea * 2 <= areaBlob && areaBlob != -1 && blobCount * 1.5 < currentBlobCount && blobCount != -1)
                {
                    Console.WriteLine("thresh:" + i + " = " + minArea + "  count = " + currentBlobCount);
                    minBlob.Contour.Render(imageMat,Scalar.Red);
                    //image = BitmapConverter.ToBitmap(imageMat);
                    image = BitmapConverter.ToBitmap(dst);

                    return minArea;
                }
                areaBlob = minArea;
                blobCount = currentBlobCount;
            }

            Console.WriteLine("End");
            return -1;
        }
        //获取圆心半径
        public struct RadiusPt
        {
            public OpenCvSharp.Point pt;
            public int radius;
        }
        public static bool GetCenter(Mat srcMat, out RadiusPt radiusPt)
        {
            Mat grayMAT = srcMat.Clone();        
            Cv2.CvtColor(grayMAT, grayMAT, ColorConversionCodes.BGR2GRAY);
            Binarizer.Sauvola(grayMAT, grayMAT, 91, 0.1, 61);
            Cv2.MedianBlur(grayMAT, grayMAT, 5);
            Mat element = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(41, 41));
            Cv2.Erode(grayMAT, grayMAT, element);
            CvBlobs blobs = new CvBlobs();
            blobs.Label(grayMAT);
            CvBlob centerMat = null;
            Point2d pt;
            foreach (CvBlob item in blobs.Values)
            {
                item.SetMoments();
                pt = item.CalcCentroid();
                if (pt.X - 3072 * 0.5 < 150 && pt.Y - 3072 * 0.5 < 150 && 3072 * 0.5 - pt.X < 150 && 3072 * 0.5 - pt.Y < 150 && item.Rect.Width < 900)
                {
                    if (centerMat == null)
                    {
                        centerMat = item;
                    }
                    else if (centerMat.Rect.Width < item.Rect.Width)
                    {
                        centerMat = item;
                    }
                }

            }
            if (centerMat != null)
            {            
                pt = centerMat.CalcCentroid();
                radiusPt.pt.X = centerMat.Rect.Width/2+centerMat.Rect.X;
                radiusPt.pt.Y = centerMat.Rect.Height/ 2 + centerMat.Rect.Y;
                if (centerMat.Rect.Width < centerMat.Rect.Height)
                    radiusPt.radius = (int)Math.Round(centerMat.Rect.Width * 0.5);
                else
                    radiusPt.radius = (int)Math.Round(centerMat.Rect.Height * 0.5);                        
                return true;
            }
            else
            {
                radiusPt.radius = -1;
                radiusPt.pt = new OpenCvSharp.Point(0, 0);
                return false;
            }

        }
        //获取最外轮廓
        public static bool GetOutContour(Mat srcMat, out RadiusPt radiusPt)
        {
            Mat grayMAT = srcMat.Clone();
            Cv2.CvtColor(grayMAT, grayMAT, ColorConversionCodes.BGR2GRAY);
            Binarizer.Sauvola(grayMAT, grayMAT, 91, 0.1, 61);
            Cv2.MedianBlur(grayMAT, grayMAT, 5);
            Mat element = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(41, 41));
            Cv2.Erode(grayMAT, grayMAT, element);
            grayMAT = ~grayMAT;
            CvBlobs blobs = new CvBlobs();
            blobs.Label(grayMAT);
            CvBlob centerMat = null;
            Point2d pt;
            foreach (CvBlob item in blobs.Values)
            {
                item.SetMoments();
                pt = item.CalcCentroid();
                if (pt.X - 3072 * 0.5 < 150 && pt.Y - 3072 * 0.5 < 150 && 3072 * 0.5 - pt.X < 150 && 3072 * 0.5 - pt.Y < 150)
                {
                    if (centerMat == null)
                    {
                        centerMat = item;
                    }
                    else if (centerMat.Rect.Width < item.Rect.Width)
                    {
                        centerMat = item;
                    }
                }

            }
            if (centerMat != null)
            {
                pt = centerMat.CalcCentroid();
                radiusPt.pt.X = (int)pt.X;
                radiusPt.pt.Y = (int)pt.Y;
                if (centerMat.Rect.Width > centerMat.Rect.Height)
                    radiusPt.radius = (int)Math.Round(centerMat.Rect.Width * 0.5);
                else
                    radiusPt.radius = (int)Math.Round(centerMat.Rect.Height * 0.5);
                return true;
            }
            else
            {
                radiusPt.radius = -1;
                radiusPt.pt = new OpenCvSharp.Point(0, 0);
                return false;
            }
        }
    }
}