ImageUtil.cs 36.2 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
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
    {

        public static bool selectB = false;
        public static bool pngB = false;
        /// <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"))
                {
                    pngB = false;               
                    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
                {
                    pngB = true;
                    image = Image.FromFile(imagePath);                 
                }
            }catch(Exception)
            {

            }
            
            return image;
        }

        public static Image FindCircle(Image image, int thresh, bool inv)
        {

            Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
            Cv2.PyrDown(imageMat, imageMat);
            Mat threshMat = Threshhold(imageMat, thresh, inv);
            //Cv2.GaussianBlur(imageMat, imageMat, new OpenCvSharp.Size(7, 7), 5);
            //threshMat = Threshhold(imageMat, thresh, inv);


             Mat k1 = Mat.Ones(new OpenCvSharp.Size(21, 21), MatType.CV_8UC1);
            Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open, k1);
            CircleSegment[] circles = Cv2.HoughCircles(threshMat, HoughMethods.Gradient, 1, 5);
            foreach(CircleSegment circle in circles)
            {
                Point2f center = circle.Center;
                Cv2.Circle(imageMat, new OpenCvSharp.Point(center.X, center.Y), (int)circle.Radius, Scalar.White);
            }

            return BitmapConverter.ToBitmap(threshMat);
        }
      
        
        /// <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, bool inv=true)
        {
            Mat imageMat =BitmapConverter.ToMat(new Bitmap(image));
            Mat threshMat = Threshhold(imageMat, thresh, inv);
            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, bool inv = true)
        {
            Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
            List<CvBlob> blobList = GetBlobs(imageMat, thresh, inv);
            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, inv);
            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 itemFeature, int thresh = -1, bool inv = true)
        {
            Mat imageMat = BitmapConverter.ToMat(new Bitmap(image));
            Mat grayMat = BitmapConverter.ToMat(new Bitmap(image));
            Cv2.CvtColor(grayMat, grayMat, ColorConversionCodes.RGBA2RGB);
            if (pngB)
            {
                Cv2.Threshold(imageMat, imageMat, 70, 255, ThresholdTypes.Binary);
            }
            else
            {
                Cv2.Threshold(imageMat, imageMat, 0, 255, ThresholdTypes.Binary);
            }          
            List<CvBlob> blobList = GetBlobs(imageMat, thresh, inv);
            int itemArea = (itemFeature + 23) * 3 /5;
            if(itemArea <= 0)
            {
                itemArea = 3;
            }
            int totalCount = CountBlobs(blobList, 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);
        }
        /// <summary>
        /// 获取Blob个数
        /// </summary>
        /// <param name="blobList"></param>
        /// <param name="avgArea"></param>
        /// <param name="srcMat"></param>
        /// <returns></returns>
        private static int CountBlobs(List<CvBlob> blobList, int avgArea, ref Mat srcMat)
        {
            //List<CvBlob> filterBlobList = blobList.Where(b => b.Area > 0.3 * avgArea).ToList();
            List<CvBlob> filterBlobList = blobList.Where(b => b.Area > 0).ToList();
            if (blobList.Count == 0)
            {
                return 0;
            }
            //CvBlob markBlob = null;
            //double labelStep = GetLabelStep(blobList, avgArea, out markBlob);

            //string[] labels = new string[filterBlobList.Count];

            //double markBlobX = markBlob.Centroid.X;
            //double markBlobY = markBlob.Centroid.Y;
            //LabelBlobsInCircle(ref labels, filterBlobList, markBlobX, markBlobY, labelStep);

            //int totalCount = 0;
            //for (int i = 0; i < labels.Length; i++)
            //{
            //    if (labels[i] != null)
            //    {
            //        CvBlob blob = filterBlobList[i];
            //        Scalar color = Scalar.Red;
            //        int count = BlobHasItem(avgArea, blob);
            //        if (count > 0)
            //        {
            //            if (count == 1)
            //            {
            //                color = Scalar.Green;
            //            }
            //            else if (count == 2)
            //            {
            //                color = Scalar.Blue;
            //                //Cv2.PutText(srcMat, count + "", blob.Centroid, HersheyFonts.HersheySimplex, 0.5, color);
            //            }
            //            else if (count >= 3)
            //            {
            //                color = Scalar.Red;
            //                Point2d center = blob.Centroid;
            //                Cv2.PutText(srcMat, count + "", new OpenCvSharp.Point(center.X, center.Y), HersheyFonts.HersheySimplex, 0.5, color);
            //            }

            //            totalCount = totalCount + count;
            //            blob.Contour.Render(srcMat, color);
            //        }
            //    }
            //}

            int totalCount = 0;
            foreach (CvBlob blob in filterBlobList)
            {
                Scalar color = Scalar.Red;
                if (blob.MaxX - blob.MinX > 450 && blob.MaxY - blob.MinY > 450) continue;
                int count = BlobHasItem(avgArea, blob);
                if (count > 0)
                {
                    if (count == 1)
                    {
                        color = Scalar.Green;
                    }
                    else if (count == 2)
                    {
                        color = Scalar.Blue;
                        //Cv2.PutText(srcMat, count + "", blob.Centroid, HersheyFonts.HersheySimplex, 0.5, color);
                    }
                    else if (count >= 3)
                    {
                        color = Scalar.Red;
                        Point2d center = blob.Centroid;
                        Cv2.PutText(srcMat, count + "", new OpenCvSharp.Point(center.X, center.Y), HersheyFonts.HersheySimplex, 0.5, color);
                    }
                    totalCount = totalCount + count;
                    blob.Contour.Render(srcMat, color);
                }
            }
            string countText = "Count: " + totalCount;
            int baseLine = 0;
            OpenCvSharp.Size textSize = Cv2.GetTextSize(countText, HersheyFonts.HersheySimplex, 1, 1, out baseLine);
            Cv2.PutText(srcMat, countText, new OpenCvSharp.Point(srcMat.Width / 2 - textSize.Width / 2, srcMat.Height / 2 - textSize.Height / 2), HersheyFonts.HersheySimplex, 1, Scalar.Blue);

            //Cv2.Circle(srcMat, markBlob.Centroid, (int)labelStep, Scalar.Red, 2);
            return totalCount;
        }

        
        
        /// <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, bool inv = false)
        {
            Mat dst = new Mat();
            Cv2.CvtColor(imageMat, dst, ColorConversionCodes.RGB2GRAY);
            //if (selectB)
            //{
            //    //全局二值化
            //    Cv2.Threshold(dst, dst, 30, 255, ThresholdTypes.Binary);
            //}
            //else
            //{
            //    //全局二值化
            //    Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Binary);
            //}
            //if (selectB)
            //{
            //    if (thresh == -1)
            //    {
            //        //自动局部二值化
            //        Binarizer.Sauvola(dst, dst, 21, 0.2, 32);
            //    }
            //    else
            //    {
            //        //全局二值化
            //        if (pngB)
            //        {
            //            Cv2.Threshold(dst, dst, 70, 255, ThresholdTypes.Binary);
            //        }
            //        else
            //        {
            //            Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Binary);
            //        }

            //    }
            //    if (inv)
            //    {
            //        if (pngB)
            //        {
            //            Cv2.Threshold(dst, dst, 70, 150, ThresholdTypes.BinaryInv);
            //        }
            //        else
            //        {
            //            Cv2.Threshold(dst, dst, 0, 150, ThresholdTypes.BinaryInv);
            //        }

            //    }

            //}
            //else
            //{
            //    if (pngB)
            //    {
            //        Cv2.Threshold(dst, dst, 70, 255, ThresholdTypes.Binary);
            //        Cv2.Threshold(dst, dst, 0, 150, ThresholdTypes.BinaryInv);
            //    }
            //    else
            //    {
            //        Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Binary);
            //        Cv2.Threshold(dst, dst, 0, 150, ThresholdTypes.BinaryInv);
            //    }

            //}
            if (thresh == -1)
            {
                //自动局部二值化
                Binarizer.Sauvola(dst, dst, 21, 0.2, 32);
            }
            else
            {
                //全局二值化
                Cv2.Threshold(dst, dst, 0, 255, ThresholdTypes.Otsu);
            }
            if (inv)
            {
                Cv2.Threshold(dst, dst, 0, thresh, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu);
            }

            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, bool inv = false)
        {
            Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.RGBA2BGR);
            //Cv2.CvtColor(imageMat, imageMat, ColorConversionCodes.RGB2GRAY);
            Mat dst = Threshhold(imageMat, thresh, inv);          
            Mat k1 = Mat.Ones(new OpenCvSharp.Size(1, 1), MatType.CV_8UC1);
            Cv2.MorphologyEx(dst, dst, MorphTypes.Open, k1);
            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 1;
            }
            //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> findContourPoints(CvBlob blob)
        {
            CvContourChainCode contour = blob.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;
        }
        public static Image Mark(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, inv);
            //TODO:查找标记Blob,这里可遍历blobList,对BlobHasItem结果为1的blob进行标记,查找最小的内接半径
            CvBlob markBlob = findMarkBlob(blobList, markX, markY, thresh, inv);
            if(markBlob != null)
            {
                OpenCvSharp.Point center = new OpenCvSharp.Point() ;
                double r = 0;
                findCircle(markBlob, out center, out r);
                Cv2.Circle(imageMat, center, (int)r, Scalar.Red);
                Console.WriteLine("" + r);
                int markArea = markBlob.Area;
                int totalCount = 0;
                foreach(CvBlob blob in blobList)
                {
                    int count = BlobHasItem(markArea, blob);
                    totalCount = totalCount + count;
                    if (count  == 1)
                    {//单个Blob
                        blob.Contour.Render(imageMat, Scalar.Green);
                    }
                    else if (count >0 && count < 100)
                    {
                        //查找对大一点的Blob的内接圆数量,进行标记
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        List<OpenCvSharp.Point> centers = markBlobInImage(blob, r);
                        foreach(OpenCvSharp.Point c in centers)
                        {
                            Cv2.Circle(imageMat, c, (int)r, Scalar.Red);
                        }
                        sw.Stop();
                        Console.WriteLine("耗时:" + sw.ElapsedMilliseconds + " ms 数量:"+ centers.Count);
                        
                    }
                }
                
            }

            return BitmapConverter.ToBitmap(imageMat);
        }

        /// <summary>
        /// 查找Blob包含多少个指定半径的圆
        /// </summary>
        /// <param name="blob"></param>
        /// <param name="radius">指定半径</param>
        /// <returns>找到的圆的中心点列表,一个中心点为一个圆</returns>
        private static List<OpenCvSharp.Point> markBlobInImage(CvBlob blob, double radius)
        {
            List<OpenCvSharp.Point> centers = new List<OpenCvSharp.Point>();
            List<OpenCvSharp.Point> contourPoints = findContourPoints(blob);
            CvContourPolygon polygon = blob.Contour.ConvertToPolygon();
            //从左向右,从上到下遍历
            int x = blob.MinX;
            while(x <= blob.MaxX)
            {
                int y = blob.MinY;
                while (y <= blob.MaxY)
                {
                    //当前的遍历的点
                    OpenCvSharp.Point currentPoint = new OpenCvSharp.Point(x, y);
                    double distance = Cv2.PointPolygonTest(contourPoints, currentPoint, true);
                    //TODO: 内轮廓也需要判断
                    if(distance >= radius)
                    {
                        //当前点到轮廓的最小距离大于半径时,判断是否与其他圆相交,如果相交,忽略这个点
                        bool valid = true;
                        foreach (OpenCvSharp.Point c in centers)
                        {
                            double dis = currentPoint.DistanceTo(c);
                            if (dis <  2 * radius)
                            {
                                valid = false;
                                break;
                            }
                        }
                        if (valid)
                        {
                            //找到一个,从当前点向下偏移一个半径的距离
                            y = (int)(y + radius);
                            Console.WriteLine("" + x + ", " + y + " dis=" + distance + "  ");
                            centers.Add(currentPoint);
                        }
                        else
                        {
                            //与其他圆相交,忽略,继续下一个点
                            y++;
                        }
                    }
                    else
                    {
                        //当前点到轮廓的最小距离小于半径,继续下一个点
                        y++;
                    }
                }
                x++;
            }
            return centers;
        }

        /// <summary>
        /// 查找Blob最大的内接圆
        /// </summary>
        /// <param name="blob"></param>
        /// <param name="centerPoint"></param>
        /// <param name="r"></param>
        private static void findCircle(CvBlob blob, out OpenCvSharp.Point centerPoint, out double r)
        {
            //TODO: 需要进行修改,找多个,这里只找了一个
            List<OpenCvSharp.Point> contourPoints = findContourPoints(blob);
            OpenCvSharp.Point center = new OpenCvSharp.Point(-1,-1);
            double ridus = 0;
            for (int x = blob.MinX; x < blob.MaxX; x++)
            {
                for(int y= blob.MinY; y<blob.MaxY; y++)
                {
                    OpenCvSharp.Point currentPoint = new OpenCvSharp.Point(x, y);
                    double minDistance = -1;
                    foreach (OpenCvSharp.Point p in contourPoints)
                    {
                        double distance = currentPoint.DistanceTo(p);
                        if (distance < minDistance || minDistance == -1)
                        {
                            minDistance = distance;
                        }
                    }
                    if(minDistance > ridus)
                    {
                        ridus = minDistance;
                        center = currentPoint;
                    }
                }
            }
            centerPoint = center;
            r = ridus;
        }
    }
}