Esempio n. 1
0
        public Contour()
        {
            // cvContourArea, cvArcLength
            // 輪郭によって区切られた領域の面積と,輪郭の長さを求める
            
            const int SIZE = 500;

            // (1)画像を確保し初期化する
            using (CvMemStorage storage = new CvMemStorage())
            using (IplImage img = new IplImage(SIZE, SIZE, BitDepth.U8, 3))
            {
                img.Zero();
                // (2)点列を生成する 
                CvSeq<CvPoint> points = new CvSeq<CvPoint>(SeqType.PolyLine, storage);
                CvRNG rng = new CvRNG((ulong)DateTime.Now.Ticks);
                double scale = rng.RandReal() + 0.5;
                CvPoint pt0 = new CvPoint
                {
                    X = (int)(Math.Cos(0) * SIZE / 4 * scale + SIZE / 2),
                    Y = (int)(Math.Sin(0) * SIZE / 4 * scale + SIZE / 2)
                };
                img.Circle(pt0, 2, CvColor.Green);
                points.Push(pt0);
                for (int i = 1; i < 20; i++)
                {
                    scale = rng.RandReal() + 0.5;
                    CvPoint pt1 = new CvPoint
                    {
                        X = (int)(Math.Cos(i * 2 * Math.PI / 20) * SIZE / 4 * scale + SIZE / 2),
                        Y = (int)(Math.Sin(i * 2 * Math.PI / 20) * SIZE / 4 * scale + SIZE / 2)
                    };
                    img.Line(pt0, pt1, CvColor.Green, 2);
                    pt0.X = pt1.X;
                    pt0.Y = pt1.Y;
                    img.Circle(pt0, 3, CvColor.Green, Cv.FILLED);
                    points.Push(pt0);
                }
                img.Line(pt0, points.GetSeqElem(0).Value, CvColor.Green, 2);
                // (3)包含矩形,面積,長さを求める
                CvRect rect = points.BoundingRect(false);
                double area = points.ContourArea();
                double length = points.ArcLength(CvSlice.WholeSeq, 1);
                // (4)結果を画像に書き込む
                img.Rectangle(new CvPoint(rect.X, rect.Y), new CvPoint(rect.X + rect.Width, rect.Y + rect.Height), CvColor.Red, 2);
                string text_area = string.Format("Area:   wrect={0}, contour={1}", rect.Width * rect.Height, area);
                string text_length = string.Format("Length: rect={0}, contour={1}", 2 * (rect.Width + rect.Height), length);
                using (CvFont font = new CvFont(FontFace.HersheySimplex, 0.7, 0.7, 0, 1, LineType.AntiAlias))
                {
                    img.PutText(text_area, new CvPoint(10, img.Height - 30), font, CvColor.White);
                    img.PutText(text_length, new CvPoint(10, img.Height - 10), font, CvColor.White);
                }
                // (5)画像を表示,キーが押されたときに終了 
                using (CvWindow window = new CvWindow("BoundingRect", WindowMode.AutoSize))
                {
                    window.Image = img;
                    CvWindow.WaitKey(0);
                }
            }
        }
Esempio n. 2
0
        public BoundingRect()
        {
            // cvBoundingRect 
            // 点列を包含する矩形を求める

            // (1)画像とメモリストレージを確保し初期化する
            // (メモリストレージは、CvSeqを使わないのであれば不要)
            using (IplImage img = new IplImage(640, 480, BitDepth.U8, 3))
            using (CvMemStorage storage = new CvMemStorage(0))
            {
                img.Zero();
                CvRNG rng = new CvRNG(DateTime.Now);
                // (2)点列を生成する
                ///*
                // お手軽な方法 (普通の配列を使う)
                CvPoint[] points = new CvPoint[50];
                for (int i = 0; i < 50; i++)
                {
                    points[i] = new CvPoint()
                    {
                        X = (int)(rng.RandInt() % (img.Width / 2) + img.Width / 4),
                        Y = (int)(rng.RandInt() % (img.Height / 2) + img.Height / 4)
                    };
                    img.Circle(points[i], 3, new CvColor(0, 255, 0), Cv.FILLED);
                }
                //*/
                /*
                // サンプルに準拠した方法 (CvSeqを使う)
                CvSeq points = new CvSeq(SeqType.EltypePoint, CvSeq.SizeOf, CvPoint.SizeOf, storage);
                for (int i = 0; i < 50; i++) {
                    CvPoint pt = new CvPoint();
                    pt.X = (int)(rng.RandInt() % (img.Width / 2) + img.Width / 4);
                    pt.Y = (int)(rng.RandInt() % (img.Height / 2) + img.Height / 4);
                    points.Push(pt);
                    img.Circle(pt, 3, new CvColor(0, 255, 0), Cv.FILLED);
                }
                //*/
                // (3)点列を包含する矩形を求めて描画する
                CvRect rect = Cv.BoundingRect(points);
                img.Rectangle(new CvPoint(rect.X, rect.Y), new CvPoint(rect.X + rect.Width, rect.Y + rect.Height), new CvColor(255, 0, 0), 2);
                // (4)画像の表示,キーが押されたときに終了 
                using (CvWindow w = new CvWindow("BoundingRect", WindowMode.AutoSize, img))
                {
                    CvWindow.WaitKey(0);
                }
            }
        }
Esempio n. 3
0
 /// <summary>
 /// ヒストグラムの描画
 /// </summary>
 /// <param name="img"></param>
 /// <param name="hist"></param>
 /// <param name="histSize"></param>
 private static void DrawHist(IplImage img, CvHistogram hist, int histSize)
 {
     img.Set(CvColor.White);
     int binW = Cv.Round((double)img.Width / histSize);
     for (int i = 0; i < histSize; i++)
     {
         img.Rectangle(
             new CvPoint(i * binW, img.Height),
             new CvPoint((i + 1) * binW, img.Height - Cv.Round(hist.Bins[i])),
             CvColor.Black, -1, LineType.AntiAlias, 0
         );
     }
 }
Esempio n. 4
0
        //--------------------------------------------------------------------------------------
        // private 
        //---------------------------------------------------------------------------------------

        private void Debug_DispPredict()
        {
            using (IplImage retPlot = new IplImage(300, 300, BitDepth.U8, 3))
            {
                for (int x = 0; x < 300; x++)
                {
                    for (int y = 0; y < 300; y++)
                    {
                        float[] sample = { x / 300f, y / 300f };
                        CvMat sampleMat = new CvMat(1, 2, MatrixType.F32C1, sample);
                        int ret = (int)svm.Predict(sampleMat);
                        CvRect plotRect = new CvRect(x, 300 - y, 1, 1);
                        if (ret == 1)
                            retPlot.Rectangle(plotRect, CvColor.Red);
                        else if (ret == 2)
                            retPlot.Rectangle(plotRect, CvColor.GreenYellow);
                    }
                }
                CvWindow.ShowImages(retPlot);
            }

        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            IplImage bestMatch = new IplImage();
            CvMat mapMatrix;
            CvPoint2D32f center;
            double[] maxArray = new double[8];
            int numberOfFiles = 50;//Can change the number of input files if I want
            double angle = 0.0, scale = 1.0, bestAngle = 0.0;
            mapMatrix = new CvMat(2, 3, MatrixType.F32C1);

            while (fileReader < numberOfFiles)//Number of files to read in folder
            {

                uavSourceImg = new IplImage("C:\\OpenCvSharp\\SummerPractice13RotateAndScale4DataInfo2\\Testing Different UAV Inputs\\RenameFolder\\Kamien " + fileReader + ".bmp", LoadMode.AnyColor);

                tempImg = new IplImage("C:\\OpenCvSharp\\SummerPractice1\\SummerDatabase\\BigGoogleTemplate2.jpg", LoadMode.AnyColor);//Big template test

                CvRect drawRectangle = new CvRect(200, 200, 300, 300);
                timer.Start();
                while (angle < 15.0)//Angle change while loop. Can change if necessary
                {
                    while (i < 10)//Scaling while loop. Can change this if necessary.
                    {

                        //***********************DECLARATION

                        //tempImg = theBigTemplate.GetSubImage(drawRectangle);
                        CvSize destSize;
                        graySource = new IplImage(uavSourceImg.Size, BitDepth.U8, 1);
                        grayTemp = new IplImage(tempImg.Size, BitDepth.U8, 1);
                        tempDestImg = new IplImage(grayTemp.Size, BitDepth.U8, 1);

                        double minValue, maxValue;
                        CvPoint minLoc, maxLoc;
                        //**********************END DECLARATIONS

                        //**********************CONVERT TO GRAY
                        uavSourceImg.CvtColor(graySource, ColorConversion.BgrToGray);
                        tempImg.CvtColor(grayTemp, ColorConversion.BgrToGray);
                        //**********************END CONVERT TO GRAY
                        //**********************ROTATION
                        center = new CvPoint2D32f(grayTemp.Width * 0.5, grayTemp.Height * 0.5);
                        grayTemp.Copy(tempDestImg);
                        Cv._2DRotationMatrix(center, angle, scale, out mapMatrix);
                        Cv.WarpAffine(grayTemp, tempDestImg, mapMatrix, Interpolation.FillOutliers, Cv.ScalarAll(255));
                        //**********************END ROTATION

                        theRotatedSubTemp = tempDestImg.GetSubImage(drawRectangle);

                        //**********************RESIZE PART
                        CvSize size = new CvSize(graySource.Width / i, graySource.Height / i);//Manipulate the source image size

                        CvSize size2 = new CvSize(theRotatedSubTemp.Width / i, theRotatedSubTemp.Height / i);//theRotatedSubTemp test

                        graySourceHolder = new IplImage(size, BitDepth.U8, 1);//1 for grayholder ORIGINAL
                        grayTempHolder = new IplImage(size2, BitDepth.U8, 1);
                        graySource.Resize(graySourceHolder);//ORIGINAL(resize the grayscale source image before template matching)

                        theRotatedSubTemp.Resize(grayTempHolder);//TEST theRotatedSubTemp
                        //*********************END RESIZE PART

                        //*********************TEMPLATE MATCHING PART
                        destSize = new CvSize(graySourceHolder.Width - grayTempHolder.Width + 1, graySourceHolder.Height - grayTempHolder.Height + 1);
                        //TEST RESIZE BEFORE WITH RESIZED TEMPLATE
                        resizeDestImg = new IplImage(destSize, BitDepth.F32, 1);
                        graySourceHolder.MatchTemplate(grayTempHolder, resizeDestImg, MatchTemplateMethod.CCoeffNormed);
                        resizeDestImg.MinMaxLoc(out minValue, out maxValue, out minLoc, out maxLoc);
                        graySourceHolder.Rectangle(maxLoc.X, maxLoc.Y, maxLoc.X + grayTempHolder.Width, maxLoc.Y + grayTempHolder.Height, CvColor.Red, 3);//Testing resize before with resized template
                        //********************END TEMPLATE MATCHING PART
                        Console.WriteLine("Divided by {0}, there was a {1} percent match", i, maxValue);
                        if (maxValue > theBestMax)
                        {
                            theBestMax = maxValue;
                            bestMatch = graySourceHolder.Clone();
                            bestAngle = angle;
                            iHolder = i;

                        }

                        Cv.NamedWindow("Rotating Template", WindowMode.AutoSize);
                        Cv.NamedWindow("Sub Template", WindowMode.AutoSize);
                        Cv.ShowImage("Rotating Template", tempDestImg);
                        Cv.ShowImage("Sub Template", theRotatedSubTemp);
                        //Cv.WaitKey(0);
                        Cv.WaitKey(1);
                        i++;

                        Cv.ReleaseData(graySourceHolder);
                        Cv.ReleaseData(grayTempHolder);
                        Cv.ReleaseData(tempDestImg);
                        Cv.ReleaseData(graySource);
                        Cv.ReleaseData(grayTemp);
                        Cv.ReleaseData(resizeDestImg);
                        Cv.ReleaseData(theRotatedSubTemp);//Added for big template test
                    }//End 3rd Inner while loop
                    angle += 1.5;
                    //This changes the angle tilt of the template.  Can change if necessary.
                    i = 1;//This changes the scale divider.  Can change if necessary.
                    Console.WriteLine("***************************************SHIFTING TEMPLATE\n");
                    //Cv.DestroyAllWindows();
                }//End 2nd Inner while loop

            //***************SHOWING RESULT INFO
            timer.Stop();
            //This section writes the results to a text file
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\OpenCvSharp\\SummerPractice12RotateAndScale3DataInfo\\Data Info Folder\\Best Match Data.txt", true))
            {

                file.WriteLine("{0}\t{1}\t\t{2}\t1/{3}", timer.ElapsedMilliseconds, theBestMax.ToString("#.###"), bestAngle, iHolder);

            }
            Console.WriteLine("---------RESULTS");

            //*************END SHOWING RESULT INFO

            //*************IMPORTANT SAVES
            bestMatch.SaveImage("C:\\OpenCvSharp\\SummerPractice12RotateAndScale3DataInfo\\Data Info Folder\\Best Match" + fileReader.ToString() + ".jpg");

            Console.WriteLine("ITEM SAVED IN DATA INFO FOLDER!");
            //*************END IMPORTANT SAVES
            Cv.WaitKey(1);
            fileReader++;
            theBestMax = double.MinValue;
            iHolder = int.MinValue;
            bestAngle = double.MinValue;
            angle = 0.0;
            i = 1;
            Cv.ReleaseData(bestMatch);//TEST
                if(fileReader < numberOfFiles)
            Console.WriteLine("Switching Input...");
            }//End while loop
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch(),timer2 = new Stopwatch();
             IplImage topLayer, smallerTop, uavLayer, smallerUAV, uavTemplate, destImg;
             CvPoint minLoc, maxLoc, brightMinLoc, brightMaxLoc;
             double minValue, maxValue, bestMatch = 0;
              CvSize makeTopSmaller, makeUAVSmaller, destSize;//scale originalSize x 12
               //CvRect uavRect;
              CvMat mapMatrix;
              CvPoint2D32f center;
             StreamWriter writer2 = new StreamWriter
              (@"C:\\OpenCvSharp\\FallProgram5TopLayerTimeMeasure\\Top Layer Measure.txt");
            double angle = 0.0, scale = 1.0, topScale = 0.09,
                bestScale = 0, bestAngle = 0, brightMinVal = 0, brightMaxVal = 0;
            topLayer = new IplImage("C:\\OpenCvSharp\\FallProgram5TopLayerTimeMeasure\\TrueSizedMosaic.bmp", LoadMode.GrayScale);
            uavLayer = new IplImage("C:\\Summer14\\EO_Run07_s7_301_16_00_51_278385\\Oct-28-12-00-57_523977-Frame-30.bmp", LoadMode.GrayScale);

            //************************Brighten input image section
            Cv.MinMaxLoc(topLayer, out brightMinVal, out brightMaxVal, out brightMinLoc, out brightMaxLoc);
            double brightScale = 255 / 70;//90 smaller denominator makes it brighter
            double brightShift = -brightMinVal * brightScale;
            Cv.ConvertScale(topLayer, topLayer, brightScale, brightShift);
            timer.Start();
            //************************End brighten section
            while (topScale > 0.06)
            {

                /*****************Manipulate the size of top layer and uav*/
                makeTopSmaller = new CvSize((int)(topLayer.Width * topScale), (int)(topLayer.Height * topScale));
                //make top layer original size x0.07
                makeUAVSmaller = new CvSize((int)(uavLayer.Width * .08), (int)(topLayer.Height * .03));
                //***************************************

                while (angle > -361.0)
                {
                    //*********************************
                    /*PART 1 This section makes the top layer and uav layer smaller*/

                    smallerTop = new IplImage(makeTopSmaller, topLayer.Depth, topLayer.NChannels);//Make the top layer smaller
                    smallerUAV = new IplImage(makeUAVSmaller, uavLayer.Depth, uavLayer.NChannels);//Make the uav layer smaller

                    topLayer.Resize(smallerTop);//Resize the top Layer
                    uavLayer.Resize(smallerUAV);//Resize the uav Layer

                    //*******************END 1

                    //******************Part 2 ROTATING SECTION
                    mapMatrix = new CvMat(2, 3, MatrixType.F32C1);
                    center = new CvPoint2D32f(smallerUAV.Width * 0.5, smallerUAV.Height * 0.5);
                    Cv._2DRotationMatrix(center, angle, scale, out mapMatrix);

                    Cv.WarpAffine(smallerUAV, smallerUAV, mapMatrix, Interpolation.Linear, Cv.ScalarAll(255));
                    angle -= 0.1;

                    //***********************END 2
                    //***********************PART 3 This section handles getting the template
                    uavRect = new CvRect((smallerUAV.Width / 2) - 75, (smallerUAV.Height / 2) - 75, 150, 150);//200x200
                    smallerUAV.Rectangle(uavRect, CvColor.Red, 2);
                    uavTemplate = smallerUAV.GetSubImage(uavRect);

                    //**********************END 3
                    //**********************PART 4 This is where template matching begins
                    destSize = new CvSize(smallerTop.Width - uavTemplate.Width + 1, smallerTop.Height - uavTemplate.Height + 1);
                    destImg = new IplImage(destSize, BitDepth.F32, 1);
                    //Recording the time on each step
                    timer2.Start();
                    smallerTop.MatchTemplate(uavTemplate, destImg, MatchTemplateMethod.CCoeffNormed);
                    timer2.Stop();
                    writer2.WriteLine("{0} {1} {2}",topScale,counter, timer2.ElapsedMilliseconds);//scale multiplier,scale count, time
                    timer2.Reset();
                    counter++;
                    //End section
                    destImg.MinMaxLoc(out minValue, out maxValue, out minLoc, out maxLoc);
                    smallerTop.Rectangle(maxLoc.X, maxLoc.Y, maxLoc.X + uavTemplate.Width, maxLoc.Y + uavTemplate.Height, CvColor.Red, 3);
                    //*******Records best match
                    if (maxValue > bestMatch)
                    {
                        x = maxLoc.X;
                        y = maxLoc.Y;
                        bestAngle = angle;
                        bestScale = topScale;
                        bestMatch = maxValue;
                        bestTopLayer = new IplImage(makeTopSmaller, smallerTop.Depth, smallerTop.NChannels);//decaration for the best match
                        smallerTop.Copy(bestTopLayer);
                        Console.WriteLine("New best match: {0}", bestMatch);
                        //******IMPORTANT SAVE!!!
                        uavTemplate.SaveImage("C:\\OpenCvSharp\\SummerPractice24UAVTrack3\\Used Template.bmp");
                        //******END IMPORTANT SAVE!!!
                    }
                    //*******End Record Best Match
                    //*******Output test
                    Cv.ShowImage("Top Layer", smallerTop);
                    Cv.ShowImage("smaller uav", smallerUAV);
                    Cv.ShowImage("Template", uavTemplate);
                    Cv.WaitKey(1);
                    //*******End Output test

                    //*****************END 4
                    Cv.ReleaseData(smallerTop);
                    Cv.ReleaseData(smallerUAV);
                    Cv.ReleaseData(uavTemplate);
                    Cv.ReleaseData(destImg);

                }//End Inner While loop
                angle = 0.0;
                topScale -= 0.01;
                Console.WriteLine("Scaling top layer down.....");
                counter = 0;
            }//End While loop

            timer.Stop();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter
                (@"C:\\OpenCvSharp\\FallProgram5TopLayerTimeMeasure\\Total Top Measure.txt", true))
            {
                writer.WriteLine
                    ("{0}\t{1}\t\t{2}\t{3}\t{4}", timer.ElapsedMilliseconds, bestMatch.ToString("#.###"),
                    bestAngle.ToString("###.#"), bestScale.ToString(), "(X: " + x.ToString() + ", Y: " + y.ToString() + ")");
            }
            //**********************IMPORTANT SAVE!!!
            bestTopLayer.SaveImage("C:\\OpenCvSharp\\FallProgram5TopLayerTimeMeasure\\TL Match Image.bmp");

            //**********************END IMPORTANT SAVE!!!
            Cv.ShowImage("The Best Match", bestTopLayer);
            Cv.WaitKey(0);
        }
Esempio n. 7
0
        //作成した辞書を図でみる
        public void Debug_DispPredict()
        {
            //辞書ファイルのロード
            this.libSVM_model = SVM.LoadModel(@"libsvm_model.xml");

            using (IplImage retPlot = new IplImage(300, 300, BitDepth.U8, 3))
            {
                for (int x = 0; x < 300; x++)
                {
                    for (int y = 0; y < 300; y++)
                    {
                        float[] sample = { x / 300f, y / 300f };
                        //問題を作成
                        SVMNode[] node_array = new SVMNode[2];
                        node_array[0] = new SVMNode(1, sample[0]);
                        node_array[1] = new SVMNode(2, sample[1]);
                        int ret_double = (int)SVM.Predict(libSVM_model, node_array);
                        int ret_i = (int)ret_double;
                        CvRect plotRect = new CvRect(x, 300 - y, 1, 1);
                        if (ret_i == 1)
                            retPlot.Rectangle(plotRect, CvColor.Red);
                        else if (ret_i == 2)
                            retPlot.Rectangle(plotRect, CvColor.GreenYellow);
                    }
                }
                CvWindow.ShowImages(retPlot);
            }
        }