using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenCV.OpenCV
{
    internal partial class OpenCVClass : IDisposable
    {

        public IplImage FindContour(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            Cv.Copy(src, _cvt);
            _bin = Binary(src, 150);

            CvMemStorage storage = new CvMemStorage();
            CvSeq<CvPoint> contours;

            Cv.FindContours(_bin, storage, out contours, CvContour.SizeOf, ContourRetrieval.List, ContourChain.ApproxNone);

            //while (contours != null)
            //{
            //    for (int i = 0; i < contours.Total; i++)
            //    {
            //        Cv.DrawCircle(_cvt, contours[i].Value, 3, CvColor.Red);

            //    }

            //    contours = contours.HNext;
            //}

            Cv.DrawContours(_cvt, contours, CvColor.Yellow, CvColor.Red, 1, 2, LineType.AntiAlias);
            Cv.ReleaseMemStorage(storage);
            Cv.ClearSeq(contours);

            return _cvt;
        }

        public IplImage ScanContour(IplImage src)
        {
            _cvt = new IplImage(src.Size, BitDepth.U8, 3);
            Cv.Copy(src, _cvt);
            _bin = Binary(src, 150);

            CvMemStorage storage = new CvMemStorage();
            //CvSeq<CvPoint> contours;

            CvContourScanner scanner = Cv.StartFindContours(_bin, storage, CvContour.SizeOf, ContourRetrieval.List, ContourChain.ApproxNone);

            //while ((contours = Cv.FindNextContour(scanner)) != null)
            //{
            //    if (contours[0].Value == new CvPoint(1, 1))
            //        continue;

            //    Cv.DrawContours(_cvt, contours, CvColor.Yellow, CvColor.Red, 1, 2, LineType.AntiAlias);
            //}

            foreach (CvSeq<CvPoint> contour in scanner)
            {
                if (contour[0].Value == new CvPoint(1, 1))
                    continue;

                _cvt.DrawContours(contour, CvColor.Yellow, CvColor.Red, 1, 2, LineType.AntiAlias);
            }

            //Cv.EndFindContours(scanner);

            Cv.ReleaseMemStorage(storage);

            return _cvt;
        }
    }
}
