示例#1
0
        public void PreProcess()
        {
            //Cv.NamedWindow("anhthoai", WindowMode.AutoSize);
            IplConvKernel element = Cv.CreateStructuringElementEx(21, 3, 10, 2, ElementShape.Rect, null);
            timg = new IplImage(src.Size, BitDepth.U8, 1);
            IplImage temp = timg.Clone();
            IplImage dest = timg.Clone();
            src.CvtColor(timg, ColorConversion.RgbaToGray);
            pimg = timg.Clone();
            //Cv.Threshold(pimg, pimg, 128, 255, ThresholdType.Binary | ThresholdType.Otsu);
            Cv.Smooth(timg, timg, SmoothType.Gaussian);
            Cv.MorphologyEx(timg, dest, temp, element, MorphologyOperation.TopHat, 1);

            Cv.Threshold(dest, timg, 180, 255, ThresholdType.Binary | ThresholdType.Otsu);
            //Cv.AdaptiveThreshold(dest, timg, 255, AdaptiveThresholdType.MeanC, ThresholdType.Binary,75, 0);
            Cv.Smooth(timg, dest, SmoothType.Median);
            Cv.Dilate(dest, dest, element, 2);

            /*using (CvWindow window = new CvWindow("BoundingRect", WindowMode.AutoSize))
            {
                window.Image = dest;
                CvWindow.WaitKey(0);
            }*/
            //Cv.ShowImage("anhthoai", dest);
            Cv.ReleaseImage(temp);
            Cv.ReleaseImage(dest);
        }
示例#2
0
        public Watershed()
        {
            // cvWatershed
            // マウスで円形のマーカー(シード領域)の中心を指定し,複数のマーカーを設定する.
            // このマーカを画像のgradientに沿って広げて行き,gradientの高い部分に出来る境界を元に領域を分割する.
            // 領域は,最初に指定したマーカーの数に分割される. 

            // (2)画像の読み込み,マーカー画像の初期化,結果表示用画像領域の確保を行なう
            using (IplImage srcImg = new IplImage(Const.ImageGoryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            using (IplImage dspImg = srcImg.Clone())
            using (IplImage markers = new IplImage(srcImg.Size, BitDepth.S32, 1))
            {
                markers.Zero();

                // (3)入力画像を表示しシードコンポーネント指定のためのマウスイベントを登録する
                using (CvWindow wImage = new CvWindow("image", WindowMode.AutoSize))
                {
                    wImage.Image = srcImg;
                    // クリックにより中心を指定し,円形のシード領域を設定する   
                    int seedNum = 0;
                    wImage.OnMouseCallback += delegate(MouseEvent ev, int x, int y, MouseEvent flags)
                    {
                        if (ev == MouseEvent.LButtonDown)
                        {
                            seedNum++;
                            CvPoint pt = new CvPoint(x, y);
                            markers.Circle(pt, 20, CvScalar.ScalarAll(seedNum), Cv.FILLED, LineType.Link8, 0);
                            dspImg.Circle(pt, 20, CvColor.White, 3, LineType.Link8, 0);
                            wImage.Image = dspImg;
                        }
                    };
                    CvWindow.WaitKey();
                }

                // (4)watershed分割を実行する  
                Cv.Watershed(srcImg, markers);

                // (5)実行結果の画像中のwatershed境界(ピクセル値=-1)を結果表示用画像上に表示する
                for (int i = 0; i < markers.Height; i++)
                {
                    for (int j = 0; j < markers.Width; j++)
                    {
                        int idx = (int)(markers.Get2D(i, j).Val0);
                        if (idx == -1)
                        {
                            dstImg.Set2D(i, j, CvColor.Red);
                        }
                    }
                }
                using (CvWindow wDst = new CvWindow("watershed transform", WindowMode.AutoSize))
                {
                    wDst.Image = dstImg;
                    CvWindow.WaitKey();
                }
            }

        }
示例#3
0
        public Watershed()
        {
            using (var srcImg = new IplImage(FilePath.Image.Goryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (var dstImg = srcImg.Clone())
            using (var dspImg = srcImg.Clone())
            using (var markers = new IplImage(srcImg.Size, BitDepth.S32, 1))
            {
                markers.Zero();

                using (var window = new CvWindow("image", WindowMode.AutoSize))
                {
                    window.Image = srcImg;
                    // Mouse event  
                    int seedNum = 0;
                    window.OnMouseCallback += delegate(MouseEvent ev, int x, int y, MouseEvent flags)
                    {
                        if (ev == MouseEvent.LButtonDown)
                        {
                            seedNum++;
                            CvPoint pt = new CvPoint(x, y);
                            markers.Circle(pt, 20, CvScalar.ScalarAll(seedNum), Cv.FILLED, LineType.Link8, 0);
                            dspImg.Circle(pt, 20, CvColor.White, 3, LineType.Link8, 0);
                            window.Image = dspImg;
                        }
                    };
                    CvWindow.WaitKey();
                }

                Cv.Watershed(srcImg, markers);

                // draws watershed
                for (int i = 0; i < markers.Height; i++)
                {
                    for (int j = 0; j < markers.Width; j++)
                    {
                        int idx = (int)(markers.Get2D(i, j).Val0);
                        if (idx == -1)
                        {
                            dstImg.Set2D(i, j, CvColor.Red);
                        }
                    }
                }
                using (CvWindow wDst = new CvWindow("watershed transform", WindowMode.AutoSize))
                {
                    wDst.Image = dstImg;
                    CvWindow.WaitKey();
                }
            }

        }
示例#4
0
        public Morphology()
        {
            using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImgDilate = srcImg.Clone())
            using (IplImage dstImgErode = srcImg.Clone())
            using (IplImage dstImgOpening = srcImg.Clone())
            using (IplImage dstImgClosing = srcImg.Clone())
            using (IplImage dstImgGradient = srcImg.Clone())
            using (IplImage dstImgTophat = srcImg.Clone())
            using (IplImage dstImgBlackhat = srcImg.Clone())
            using (IplImage tmpImg = srcImg.Clone())
            {
                IplConvKernel element = Cv.CreateStructuringElementEx(9, 9, 4, 4, ElementShape.Rect, null);

                Cv.Dilate(srcImg, dstImgDilate, element, 1);
                Cv.Erode(srcImg, dstImgErode, element, 1);
                Cv.MorphologyEx(srcImg, dstImgOpening, tmpImg, element, MorphologyOperation.Open, 1);
                Cv.MorphologyEx(srcImg, dstImgClosing, tmpImg, element, MorphologyOperation.Close, 1);
                Cv.MorphologyEx(srcImg, dstImgGradient, tmpImg, element, MorphologyOperation.Gradient, 1);
                Cv.MorphologyEx(srcImg, dstImgTophat, tmpImg, element, MorphologyOperation.TopHat, 1);
                Cv.MorphologyEx(srcImg, dstImgBlackhat, tmpImg, element, MorphologyOperation.BlackHat, 1);

                using (new CvWindow("src", srcImg))
                using (new CvWindow("dilate", dstImgDilate))
                using (new CvWindow("erode", dstImgErode)) 
                using (new CvWindow("opening", dstImgOpening)) 
                using (new CvWindow("closing", dstImgClosing)) 
                using (new CvWindow("gradient", dstImgGradient)) 
                using (new CvWindow("tophat", dstImgTophat)) 
                using (new CvWindow("blackhat", dstImgBlackhat))
                {
                    Cv.WaitKey(0);
                }
            }
        }
示例#5
0
        public Perspective()
        {
            using (var srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (var dstImg = srcImg.Clone())
            {
                CvPoint2D32f[] srcPnt = new CvPoint2D32f[4];
                CvPoint2D32f[] dstPnt = new CvPoint2D32f[4];
                srcPnt[0] = new CvPoint2D32f(150.0f, 150.0f);
                srcPnt[1] = new CvPoint2D32f(150.0f, 300.0f);
                srcPnt[2] = new CvPoint2D32f(350.0f, 300.0f);
                srcPnt[3] = new CvPoint2D32f(350.0f, 150.0f);
                dstPnt[0] = new CvPoint2D32f(200.0f, 200.0f);
                dstPnt[1] = new CvPoint2D32f(150.0f, 300.0f);
                dstPnt[2] = new CvPoint2D32f(350.0f, 300.0f);
                dstPnt[3] = new CvPoint2D32f(300.0f, 200.0f);
                using (CvMat mapMatrix = Cv.GetPerspectiveTransform(srcPnt, dstPnt))
                {
                    Cv.WarpPerspective(srcImg, dstImg, mapMatrix, Interpolation.Linear | Interpolation.FillOutliers, CvScalar.ScalarAll(100));

                    using (new CvWindow("src", srcImg))
                    using (new CvWindow("dst", dstImg))
                    {
                        Cv.WaitKey(0);
                    }
                }
            }
        }
示例#6
0
        public LatentSVM()
        {
            using (var detector = new CvLatentSvmDetector(FilePath.Text.LatentSvmCat))
            using (var imageSrc = new IplImage(FilePath.Image.Cat, LoadMode.Color))
            using (var imageDst = imageSrc.Clone())
            using (var storage = new CvMemStorage())
            {
                Console.WriteLine("Running LatentSVM...");
                Stopwatch watch = Stopwatch.StartNew();

                CvSeq<CvObjectDetection> result = detector.DetectObjects(imageSrc, storage, 0.5f, 2);

                watch.Stop();
                Console.WriteLine("Elapsed time: {0}ms", watch.ElapsedMilliseconds);

                foreach (CvObjectDetection detection in result)
                {
                    CvRect boundingBox = detection.Rect;
                    imageDst.Rectangle(
                        new CvPoint(boundingBox.X, boundingBox.Y), 
                        new CvPoint(boundingBox.X + boundingBox.Width, boundingBox.Y + boundingBox.Height),
                        CvColor.Red, 3);
                }

                using (new CvWindow("LatentSVM result", imageDst))
                {
                    Cv.WaitKey();
                }
            }
        }
示例#7
0
        public Affine()
        {
            // cvGetAffineTransform + cvWarpAffine
            // 画像上の3点対応よりアフィン変換行列を計算し,その行列を用いて画像全体のアフィン変換を行う.

            // (1)画像の読み込み,出力用画像領域の確保を行なう
            using (IplImage srcImg = new IplImage(Const.ImageGoryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {

                // (2)三角形の回転前と回転後の対応する頂点をそれぞれセットし  
                //    cvGetAffineTransformを用いてアフィン行列を求める  
                CvPoint2D32f[] srcPnt = new CvPoint2D32f[3];
                CvPoint2D32f[] dstPnt = new CvPoint2D32f[3];
                srcPnt[0] = new CvPoint2D32f(200.0f, 200.0f);
                srcPnt[1] = new CvPoint2D32f(250.0f, 200.0f);
                srcPnt[2] = new CvPoint2D32f(200.0f, 100.0f);
                dstPnt[0] = new CvPoint2D32f(300.0f, 100.0f);
                dstPnt[1] = new CvPoint2D32f(300.0f, 50.0f);
                dstPnt[2] = new CvPoint2D32f(200.0f, 100.0f);
                using (CvMat mapMatrix = Cv.GetAffineTransform(srcPnt, dstPnt))
                {
                    // (3)指定されたアフィン行列により,cvWarpAffineを用いて画像を回転させる
                    Cv.WarpAffine(srcImg, dstImg, mapMatrix, Interpolation.Linear | Interpolation.FillOutliers, CvScalar.ScalarAll(0));
                    // (4)結果を表示する
                    using (new CvWindow("src", srcImg)) 
                    using (new CvWindow("dst", dstImg))
                    {
                        Cv.WaitKey(0);
                    }
                }
            }
        }
示例#8
0
        public CornerDetect()
        {
            // cvGoodFeaturesToTrack, cvFindCornerSubPix
            // 画像中のコーナー(特徴点)検出

            int cornerCount = 150;

            using (IplImage dstImg1 = new IplImage(Const.ImageLenna, LoadMode.AnyColor | LoadMode.AnyDepth))
            using (IplImage dstImg2 = dstImg1.Clone())
            using (IplImage srcImgGray = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage eigImg = new IplImage(srcImgGray.GetSize(), BitDepth.F32, 1))
            using (IplImage tempImg = new IplImage(srcImgGray.GetSize(), BitDepth.F32, 1))
            {
                CvPoint2D32f[] corners;
                // (1)cvCornerMinEigenValを利用したコーナー検出
                Cv.GoodFeaturesToTrack(srcImgGray, eigImg, tempImg, out corners, ref cornerCount, 0.1, 15);
                Cv.FindCornerSubPix(srcImgGray, corners, cornerCount, new CvSize(3, 3), new CvSize(-1, -1), new CvTermCriteria(20, 0.03));
                // (2)コーナーの描画
                for (int i = 0; i < cornerCount; i++)
                    Cv.Circle(dstImg1, corners[i], 3, new CvColor(255, 0, 0), 2);
                // (3)cvCornerHarrisを利用したコーナー検出
                cornerCount = 150;
                Cv.GoodFeaturesToTrack(srcImgGray, eigImg, tempImg, out corners, ref cornerCount, 0.1, 15, null, 3, true, 0.01);
                Cv.FindCornerSubPix(srcImgGray, corners, cornerCount, new CvSize(3, 3), new CvSize(-1, -1), new CvTermCriteria(20, 0.03));
                // (4)コーナーの描画
                for (int i = 0; i < cornerCount; i++)
                    Cv.Circle(dstImg2, corners[i], 3, new CvColor(0, 0, 255), 2);
                // (5)画像の表示 
                using (new CvWindow("EigenVal", WindowMode.AutoSize, dstImg1)) 
                using (new CvWindow("Harris", WindowMode.AutoSize, dstImg2))
                {
                    Cv.WaitKey(0);
                }
            }
        }
示例#9
0
        public CornerDetect()
        {
            int cornerCount = 150;

            using (IplImage dstImg1 = new IplImage(FilePath.Image.Lenna, LoadMode.AnyColor | LoadMode.AnyDepth))
            using (IplImage dstImg2 = dstImg1.Clone())
            using (IplImage srcImgGray = new IplImage(FilePath.Image.Lenna, LoadMode.GrayScale))
            using (IplImage eigImg = new IplImage(srcImgGray.GetSize(), BitDepth.F32, 1))
            using (IplImage tempImg = new IplImage(srcImgGray.GetSize(), BitDepth.F32, 1))
            {
                CvPoint2D32f[] corners;
                Cv.GoodFeaturesToTrack(srcImgGray, eigImg, tempImg, out corners, ref cornerCount, 0.1, 15);
                Cv.FindCornerSubPix(srcImgGray, corners, cornerCount, new CvSize(3, 3), new CvSize(-1, -1), new CvTermCriteria(20, 0.03));

                for (int i = 0; i < cornerCount; i++)
                    Cv.Circle(dstImg1, corners[i], 3, new CvColor(255, 0, 0), 2);

                cornerCount = 150;
                Cv.GoodFeaturesToTrack(srcImgGray, eigImg, tempImg, out corners, ref cornerCount, 0.1, 15, null, 3, true, 0.01);
                Cv.FindCornerSubPix(srcImgGray, corners, cornerCount, new CvSize(3, 3), new CvSize(-1, -1), new CvTermCriteria(20, 0.03));

                for (int i = 0; i < cornerCount; i++)
                    Cv.Circle(dstImg2, corners[i], 3, new CvColor(0, 0, 255), 2);

                using (new CvWindow("EigenVal", WindowMode.AutoSize, dstImg1)) 
                using (new CvWindow("Harris", WindowMode.AutoSize, dstImg2))
                {
                    Cv.WaitKey(0);
                }
            }
        }
示例#10
0
        public HoughCircles()
        {
            using (IplImage imgSrc = new IplImage(Const.ImageWalkman, LoadMode.Color))
            using (IplImage imgGray = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (IplImage imgHough = imgSrc.Clone())
            {
                Cv.CvtColor(imgSrc, imgGray, ColorConversion.BgrToGray);
                Cv.Smooth(imgGray, imgGray, SmoothType.Gaussian, 9);
                //Cv.Canny(imgGray, imgGray, 75, 150, ApertureSize.Size3);

                using (CvMemStorage storage = new CvMemStorage())
                {
                    CvSeq<CvCircleSegment> seq = imgGray.HoughCircles(storage, HoughCirclesMethod.Gradient, 1, 100, 150, 55, 0, 0);
                    foreach (CvCircleSegment item in seq)
                    {
                        imgHough.Circle(item.Center, (int)item.Radius, CvColor.Red, 3);
                    }
                }

                // (5)検出結果表示用のウィンドウを確保し表示する
                using (new CvWindow("gray", WindowMode.AutoSize, imgGray))
                using (new CvWindow("Hough circles", WindowMode.AutoSize, imgHough))
                {
                    CvWindow.WaitKey(0);
                }
            }
        }
示例#11
0
        public Undistort()
        {
            using (IplImage srcImg = new IplImage(FilePath.Image.Distortion, LoadMode.Color))
            using (IplImage dstImg = srcImg.Clone())
            {
                CvMat intrinsic, distortion;
                using (CvFileStorage fs = new CvFileStorage(FilePath.Text.Camera, null, FileStorageMode.Read))
                {
                    CvFileNode param = fs.GetFileNodeByName(null, "intrinsic");
                    intrinsic = fs.Read<CvMat>(param);
                    param = fs.GetFileNodeByName(null, "distortion");
                    distortion = fs.Read<CvMat>(param);
                }
                
                Cv.Undistort2(srcImg, dstImg, intrinsic, distortion);

                using (new CvWindow("Distortion", WindowMode.AutoSize, srcImg))
                using (new CvWindow("Undistortion", WindowMode.AutoSize, dstImg))
                {
                    CvWindow.WaitKey(0);
                }

                intrinsic.Dispose();
                distortion.Dispose();
            }
        }
示例#12
0
        public Undistort()
        {
            // cvUndistort2
            // キャリブレーションデータを利用して,歪みを補正する

            // (1)補正対象となる画像の読み込み
            using (IplImage srcImg = new IplImage(Const.ImageDistortion, LoadMode.Color))
            using (IplImage dstImg = srcImg.Clone())
            {

                // (2)パラメータファイルの読み込み
                CvMat intrinsic, distortion;
                using (CvFileStorage fs = new CvFileStorage(Const.XmlCamera, null, FileStorageMode.Read))
                {
                    CvFileNode param = fs.GetFileNodeByName(null, "intrinsic");
                    intrinsic = fs.Read<CvMat>(param);
                    param = fs.GetFileNodeByName(null, "distortion");
                    distortion = fs.Read<CvMat>(param);
                }

                // (3)歪み補正
                Cv.Undistort2(srcImg, dstImg, intrinsic, distortion);

                // (4)画像を表示,キーが押されたときに終了
                using (CvWindow w1 = new CvWindow("Distortion", WindowMode.AutoSize, srcImg))
                using (CvWindow w2 = new CvWindow("Undistortion", WindowMode.AutoSize, dstImg))
                {
                    CvWindow.WaitKey(0);
                }

                intrinsic.Dispose();
                distortion.Dispose();
            }
        }
示例#13
0
        public Perspective()
        {
            // cvGetPerspectiveTransform + cvWarpPerspective
            // 画像上の4点対応より透視投影変換行列を計算し,その行列を用いて画像全体の透視投影変換を行う.

            // (1)画像の読み込み,出力用画像領域の確保を行なう
            using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                // (2)四角形の変換前と変換後の対応する頂点をそれぞれセットし
                //    cvWarpPerspectiveを用いて透視投影変換行列を求める  
                CvPoint2D32f[] srcPnt = new CvPoint2D32f[4];
                CvPoint2D32f[] dstPnt = new CvPoint2D32f[4];
                srcPnt[0] = new CvPoint2D32f(150.0f, 150.0f);
                srcPnt[1] = new CvPoint2D32f(150.0f, 300.0f);
                srcPnt[2] = new CvPoint2D32f(350.0f, 300.0f);
                srcPnt[3] = new CvPoint2D32f(350.0f, 150.0f);
                dstPnt[0] = new CvPoint2D32f(200.0f, 200.0f);
                dstPnt[1] = new CvPoint2D32f(150.0f, 300.0f);
                dstPnt[2] = new CvPoint2D32f(350.0f, 300.0f);
                dstPnt[3] = new CvPoint2D32f(300.0f, 200.0f);
                using (CvMat mapMatrix = Cv.GetPerspectiveTransform(srcPnt, dstPnt))
                {
                    // (3)指定されたアフィン行列により,cvWarpAffineを用いて画像を回転させる
                    Cv.WarpPerspective(srcImg, dstImg, mapMatrix, Interpolation.Linear | Interpolation.FillOutliers, CvScalar.ScalarAll(100));
                    // (4)結果を表示する
                    using (new CvWindow("src", srcImg))
                    using (new CvWindow("dst", dstImg))
                    {
                        Cv.WaitKey(0);
                    }
                }
            }
        }
示例#14
0
文件: Affine.cs 项目: 0sv/opencvsharp
        public Affine()
        {
            // cvGetAffineTransform + cvWarpAffine

            using (IplImage srcImg = new IplImage(FilePath.Image.Goryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                CvPoint2D32f[] srcPnt = new CvPoint2D32f[3];
                CvPoint2D32f[] dstPnt = new CvPoint2D32f[3];
                srcPnt[0] = new CvPoint2D32f(200.0f, 200.0f);
                srcPnt[1] = new CvPoint2D32f(250.0f, 200.0f);
                srcPnt[2] = new CvPoint2D32f(200.0f, 100.0f);
                dstPnt[0] = new CvPoint2D32f(300.0f, 100.0f);
                dstPnt[1] = new CvPoint2D32f(300.0f, 50.0f);
                dstPnt[2] = new CvPoint2D32f(200.0f, 100.0f);
                using (CvMat mapMatrix = Cv.GetAffineTransform(srcPnt, dstPnt))
                {
                    Cv.WarpAffine(srcImg, dstImg, mapMatrix, Interpolation.Linear | Interpolation.FillOutliers, CvScalar.ScalarAll(0));

                    using (new CvWindow("src", srcImg)) 
                    using (new CvWindow("dst", dstImg))
                    {
                        Cv.WaitKey(0);
                    }
                }
            }
        }
        public System.Drawing.Bitmap FaceDetect(IplImage src)
        {
            
            // CvHaarClassifierCascade, cvHaarDetectObjects
            // 얼굴을 검출하기 위해서 Haar 분류기의 캐스케이드를 이용한다

            CvColor[] colors = new CvColor[]{
                new CvColor(0,0,255),
                new CvColor(0,128,255),
                new CvColor(0,255,255),
                new CvColor(0,255,0),
                new CvColor(255,128,0),
                new CvColor(255,255,0),
                new CvColor(255,0,0),
                new CvColor(255,0,255),
            };

            const double scale = 1.04;
            const double scaleFactor = 1.139;
            const int minNeighbors = 1;

            using (IplImage img = src.Clone())
            using (IplImage smallImg = new IplImage(new CvSize(Cv.Round(img.Width / scale), Cv.Round(img.Height / scale)), BitDepth.U8, 1))
            {
                // 얼굴 검출을 위한 화상을 생성한다.
                using (IplImage gray = new IplImage(img.Size, BitDepth.U8, 1))
                {
                    Cv.CvtColor(img, gray, ColorConversion.BgrToGray);
                    Cv.Resize(gray, smallImg, Interpolation.Linear);
                    Cv.EqualizeHist(smallImg, smallImg);
                }

                using (CvHaarClassifierCascade cascade = CvHaarClassifierCascade.FromFile(Environment.CurrentDirectory + "\\" + "haarcascade_frontalface_alt.xml"))
                using (CvMemStorage storage = new CvMemStorage())
                {
                    storage.Clear();

                    // 얼굴을 검출한다.
                    CvSeq<CvAvgComp> faces = Cv.HaarDetectObjects(smallImg, cascade, storage, scaleFactor, minNeighbors, 0, new CvSize(20, 20));

                    // 검출한 얼굴에 검은색 원을 덮어씌운다.
                    for (int i = 0; i < faces.Total; i++)
                    {
                        CvRect r = faces[i].Value.Rect;
                        CvPoint center = new CvPoint
                        {
                            X = Cv.Round((r.X + r.Width * 0.5) * scale),
                            Y = Cv.Round((r.Y + r.Height * 0.5) * scale)
                        };
                        int radius = Cv.Round((r.Width + r.Height) * 0.25 * scale);
                        img.Circle(center, radius, new CvColor(0, 0, 0), -1, LineType.Link8, 0);
                    }
                }
                FindFace = img.Clone();

                //생성한 IplImage 화상을 비트맵으로 변환해 반환한다.
                return FindFace.ToBitmap(System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            }
        }
示例#16
0
        public PixelSampling()
        {
            // 並進移動のためのピクセルサンプリング cvGetRectSubPix

            // (1) 画像の読み込み,出力用画像領域の確保を行なう 
            using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                // (2)dst_imgの画像中心になるsrc_img中の位置centerを指定する
                CvPoint2D32f center = new CvPoint2D32f
                {
                    X = srcImg.Width - 1,
                    Y = srcImg.Height - 1
                };
                // (3)centerが画像中心になるように,GetRectSubPixを用いて画像全体をシフトさせる
                Cv.GetRectSubPix(srcImg, dstImg, center);
                // (4)結果を表示する
                using (CvWindow wSrc = new CvWindow("src"))
                using (CvWindow wDst = new CvWindow("dst"))
                {
                    wSrc.Image = srcImg;
                    wDst.Image = dstImg;
                    Cv.WaitKey(0);
                }
            }


            // 回転移動のためのピクセルサンプリング cvGetQuadrangleSubPix

            const int angle = 45;
            // (1)画像の読み込み,出力用画像領域の確保を行なう
            using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                // (2)回転のための行列(アフィン行列)要素を設定し,CvMat行列Mを初期化する
                float[] m = new float[6];
                m[0] = (float)(Math.Cos(angle * Cv.PI / 180.0));
                m[1] = (float)(-Math.Sin(angle * Cv.PI / 180.0));
                m[2] = srcImg.Width * 0.5f;
                m[3] = -m[1];
                m[4] = m[0];
                m[5] = srcImg.Height * 0.5f;
                using (CvMat mat = new CvMat(2, 3, MatrixType.F32C1, m))
                {
                    // (3)指定された回転行列により,GetQuadrangleSubPixを用いて画像全体を回転させる
                    Cv.GetQuadrangleSubPix(srcImg, dstImg, mat);
                    // (4)結果を表示する
                    using (CvWindow wSrc = new CvWindow("src"))
                    using (CvWindow wDst = new CvWindow("dst"))
                    {
                        wSrc.Image = srcImg;
                        wDst.Image = dstImg;
                        Cv.WaitKey(0);
                    }
                }
            }
        }
示例#17
0
        /// <summary>
        /// constructor
        /// </summary>
        public GammaCorrection()
        {
            using (IplImage imgSrc = new IplImage(Const.ImageLenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage imgDst0_25 = imgSrc.Clone())
            using (IplImage imgDst0_5 = imgSrc.Clone())
            using (IplImage imgDst2 = imgSrc.Clone())            
            {
                CorrectGamma(imgSrc, imgDst0_25, 0.25);
                CorrectGamma(imgSrc, imgDst0_5, 0.5);
                CorrectGamma(imgSrc, imgDst2, 2.0);

                using (new CvWindow("src", imgSrc))
                using (new CvWindow("gamma = 0.25", imgDst0_25))
                using (new CvWindow("gamma = 0.5", imgDst0_5))
                using (new CvWindow("gamma = 2.0", imgDst2))                
                {
                    Cv.WaitKey(0);
                }
            }
        }
示例#18
0
        public PixelSampling()
        {
            // cvGetRectSubPix

            using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                CvPoint2D32f center = new CvPoint2D32f
                {
                    X = srcImg.Width - 1,
                    Y = srcImg.Height - 1
                };

                Cv.GetRectSubPix(srcImg, dstImg, center);

                using (CvWindow wSrc = new CvWindow("src"))
                using (CvWindow wDst = new CvWindow("dst"))
                {
                    wSrc.Image = srcImg;
                    wDst.Image = dstImg;
                    Cv.WaitKey(0);
                }
            }


            // cvGetQuadrangleSubPix

            const int angle = 45;

            using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImg = srcImg.Clone())
            {
                float[] m = new float[6];
                m[0] = (float)(Math.Cos(angle * Cv.PI / 180.0));
                m[1] = (float)(-Math.Sin(angle * Cv.PI / 180.0));
                m[2] = srcImg.Width * 0.5f;
                m[3] = -m[1];
                m[4] = m[0];
                m[5] = srcImg.Height * 0.5f;
                using (CvMat mat = new CvMat(2, 3, MatrixType.F32C1, m))
                {
                    Cv.GetQuadrangleSubPix(srcImg, dstImg, mat);

                    using (CvWindow wSrc = new CvWindow("src"))
                    using (CvWindow wDst = new CvWindow("dst"))
                    {
                        wSrc.Image = srcImg;
                        wDst.Image = dstImg;
                        Cv.WaitKey(0);
                    }
                }
            }
        }
示例#19
0
        public BinarizationMethods()
        {
            const int Size = 61;

            using (var imgSrc = new IplImage(FilePath.Image.Binarization, LoadMode.GrayScale))
            using (var imgGauss = imgSrc.Clone())
            using (var imgNiblack = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (var imgSauvola = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (var imgBernsen = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (var imgNick = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            {
                //Cv.Smooth(imgSrc, imgGauss, SmoothType.Gaussian, 9);
                //Cv.EqualizeHist(imgGauss, imgGauss);

                Stopwatch sw = Stopwatch.StartNew();
                {
                    const double K = -0.2;
                    Binarizer.NiblackFast(imgGauss, imgNiblack, Size, K);
                }
                Console.WriteLine("Niblack: {0}ms", sw.ElapsedMilliseconds);
                sw.Reset(); sw.Start();
                {
                    const double K = 0.2;
                    const double R = 64;
                    Binarizer.SauvolaFast(imgGauss, imgSauvola, Size, K, R);
                }
                Console.WriteLine("Sauvola: {0}ms", sw.ElapsedMilliseconds); 
                sw.Reset(); sw.Start();
                {
                    const byte ContrastMin = 15;
                    const byte BgThreshold = 127;
                    Binarizer.Bernsen(imgGauss, imgBernsen, Size, ContrastMin, BgThreshold);
                }
                Console.WriteLine("bernsen: {0}ms", sw.ElapsedMilliseconds);
                sw.Reset(); sw.Start();
                {
                    const double K = -0.14;
                    Binarizer.Nick(imgGauss, imgNick, Size, K);
                }
                Console.WriteLine("nick: {0}ms", sw.ElapsedMilliseconds);

                using (new CvWindow("src", imgSrc))
                //using (new CvWindow("gauss", imgGauss))
                using (new CvWindow("niblack", imgNiblack))
                using (new CvWindow("sauvola", imgSauvola))
                using (new CvWindow("bernsen", imgBernsen))
                using (new CvWindow("nick", imgNick))
                {
                    Cv.WaitKey();
                }
            }
        }
示例#20
0
        public Histogram()
        {
            // cvCalcHist
            // コントラストや明度をいろいろ変えられるサンプル

            const int histSize = 64;
            float[] range0 = { 0, 256 };
            float[][] ranges = { range0 };

            // 画像の読み込み
            using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dstImg = srcImg.Clone())
            using (IplImage histImg = new IplImage(new CvSize(400, 400), BitDepth.U8, 1))
            using (CvHistogram hist = new CvHistogram(new int[] { histSize }, HistogramFormat.Array, ranges, true))
            {
                using (CvWindow windowImage = new CvWindow("image", WindowMode.AutoSize))
                using (CvWindow windowHist = new CvWindow("histogram", WindowMode.AutoSize))
                {
                    // トラックバーが動かされた時の処理
                    CvTrackbar ctBrightness = null;
                    CvTrackbar ctContrast = null;
                    CvTrackbarCallback callback = delegate(int pos)
                    {
                        int brightness = ctBrightness.Pos - 100;
                        int contrast = ctContrast.Pos - 100;
                        // LUTの適用
                        byte[] lut = CalcLut(contrast, brightness);
                        srcImg.LUT(dstImg, lut);
                        // ヒストグラムの描画
                        CalcHist(dstImg, hist);
                        DrawHist(histImg, hist, histSize);
                        // ウィンドウに表示
                        windowImage.ShowImage(dstImg);
                        windowHist.ShowImage(histImg);
                        dstImg.Zero();
                        histImg.Zero();
                    };

                    // トラックバーの作成
                    // (OpenCVでは現在位置にポインタを渡すことでトラックバーの位置の変化が取得できるが、
                    // .NETではGCによりポインタが移動してしまうので廃止した。別の方法でうまく取得すべし。)
                    ctBrightness = windowImage.CreateTrackbar("brightness", 100, 200, callback);
                    ctContrast = windowImage.CreateTrackbar("contrast", 100, 200, callback);
                    // 初回描画
                    callback(0);

                    // キー入力待ち
                    Cv.WaitKey(0);
                }
            }
        }
示例#21
0
        public ContourScanner()
        {
            // create IplImages
            using (var src = new IplImage(FilePath.Image.Lenna, LoadMode.Color))
            using (var gray = new IplImage(src.Size, BitDepth.U8, 1))
            using (var canny = new IplImage(src.Size, BitDepth.U8, 1))
            using (var result = src.Clone())
            {
                // detect edges
                Cv.CvtColor(src, gray, ColorConversion.BgrToGray);
                Cv.Canny(gray, canny, 50, 200);

                // find all contours
                using (CvMemStorage storage = new CvMemStorage())
                {
                    // find contours by CvContourScanner

                    // native style
                    /*
                    CvContourScanner scanner = Cv.StartFindContours(canny, storage, CvContour.SizeOf, ContourRetrieval.Tree, ContourChain.ApproxSimple);
                    while (true)
                    {
                        CvSeq<CvPoint> c = Cv.FindNextContour(scanner);
                        if (c == null)
                            break;
                        else
                            Cv.DrawContours(result, c, CvColor.Red, CvColor.Green, 0, 3, LineType.AntiAlias);
                    }
                    Cv.EndFindContours(scanner);
                    //*/

                    // wrapper style
                    using (CvContourScanner scanner = new CvContourScanner(canny, storage, CvContour.SizeOf, ContourRetrieval.Tree, ContourChain.ApproxSimple))
                    {
                        foreach (CvSeq<CvPoint> c in scanner)
                        {
                            result.DrawContours(c, CvColor.Red, CvColor.Green, 0, 3, LineType.AntiAlias);
                        }
                    }                    
                }

                // show canny and result
                using (new CvWindow("ContourScanner canny", canny))
                using (new CvWindow("ContourScanner result", result))
                {
                    Cv.WaitKey();
                }             
            }
        }
示例#22
0
        /// <summary>
        /// 
        /// </summary>
        public SkinDetector()
        {
            using (IplImage imgSrc = new IplImage(Const.ImageBalloon, LoadMode.Color))            
            using (IplImage imgHueMask = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (IplImage imgDst = imgSrc.Clone())
            {
                CvAdaptiveSkinDetector detector = new CvAdaptiveSkinDetector(1, MorphingMethod.None);
                detector.Process(imgSrc, imgHueMask);
                DisplaySkinPoints(imgHueMask, imgDst, CvColor.Green);

                using (CvWindow windowSrc = new CvWindow("src", imgSrc))
                using (CvWindow windowDst = new CvWindow("skin", imgDst))
                {
                    Cv.WaitKey(0);
                }
            }
        }
示例#23
0
        public PyrSegmentation()
        {
            // cvPyrSegmentation
            // レベルを指定して画像ピラミッドを作成し,その情報を用いて画像のセグメント化を行なう.

            const double threshold1 = 255.0;
            const double threshold2 = 50.0; 

            // (1)画像の読み込み
            using (IplImage srcImg = new IplImage(Const.ImageGoryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            {
                // level1から4それぞれでやってみる
                IplImage[] dstImg = new IplImage[4];
                for (int level = 0; level < dstImg.Length; level++)
                {
                    // (2)領域分割のためにROIをセットする
                    CvRect roi = new CvRect()
                    {
                        X = 0,
                        Y = 0,
                        Width = srcImg.Width & -(1 << (level + 1)),
                        Height = srcImg.Height & -(1 << (level + 1))
                    };
                    srcImg.ROI = roi;
                    // (3)分割結果画像出力用の画像領域を確保し,領域分割を実行
                    dstImg[level] = srcImg.Clone();
                    Cv.PyrSegmentation(srcImg, dstImg[level], level + 1, threshold1, threshold2);
                }

                // (4)入力画像と分割結果画像の表示
                CvWindow wSrc = new CvWindow("src", srcImg);
                CvWindow[] wDst = new CvWindow[dstImg.Length];
                for (int i = 0; i < dstImg.Length; i++)
                {
                    wDst[i] = new CvWindow("dst" + i, dstImg[i]);
                }
                CvWindow.WaitKey();
                CvWindow.DestroyAllWindows();

                foreach (IplImage item in dstImg)
                {
                    item.Dispose();
                }
            }

        }
	// Update is called once per frame
	void Update () {
		//capture = CvCapture.FromCamera (0);
		if (!close) {
			capture.GrabFrame ();
			frame = capture.RetrieveFrame ();
			next = frame.Clone();
			Cv.CvtColor(frame,next,ColorConversion.BgrToGray);

			windowCapture.ShowImage (frame);
		}

		if(Input.GetKey(KeyCode.Escape))
		{
			windowCapture.Close();
			close = true;
		}
		
	}
示例#25
0
        public MSERSample()
        {
            using (var imgSrc = new IplImage(FilePath.Image.Distortion, LoadMode.Color))
            using (var imgGray = new IplImage(imgSrc.Size, BitDepth.U8, 1))
            using (var imgDst = imgSrc.Clone())
            {
                Cv.CvtColor(imgSrc, imgGray, ColorConversion.BgrToGray);

                CStyleMSER(imgGray, imgSrc);  // C style

                using (new CvWindow("MSER src", imgSrc))
                using (new CvWindow("MSER gray", imgGray))
                using (new CvWindow("MSER dst", imgDst))
                {
                    Cv.WaitKey();
                }
            }
        }
示例#26
0
        public Histogram()
        {
            // cvCalcHist

            const int histSize = 64;
            float[] range0 = { 0, 256 };
            float[][] ranges = { range0 };

            using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.GrayScale))
            using (IplImage dstImg = srcImg.Clone())
            using (IplImage histImg = new IplImage(new CvSize(400, 400), BitDepth.U8, 1))
            using (CvHistogram hist = new CvHistogram(new int[] { histSize }, HistogramFormat.Array, ranges, true))
            {
                using (CvWindow windowImage = new CvWindow("image", WindowMode.AutoSize))
                using (CvWindow windowHist = new CvWindow("histogram", WindowMode.AutoSize))
                {
                    CvTrackbar ctBrightness = null;
                    CvTrackbar ctContrast = null;
                    CvTrackbarCallback callback = delegate(int pos)
                    {
                        int brightness = ctBrightness.Pos - 100;
                        int contrast = ctContrast.Pos - 100;
                        // perform LUT
                        byte[] lut = CalcLut(contrast, brightness);
                        srcImg.LUT(dstImg, lut);
                        // draws histogram
                        CalcHist(dstImg, hist);
                        DrawHist(histImg, hist, histSize);

                        windowImage.ShowImage(dstImg);
                        windowHist.ShowImage(histImg);
                        dstImg.Zero();
                        histImg.Zero();
                    };

                    ctBrightness = windowImage.CreateTrackbar("brightness", 100, 200, callback);
                    ctContrast = windowImage.CreateTrackbar("contrast", 100, 200, callback);
                    // initial action
                    callback(0);

                    Cv.WaitKey(0);
                }
            }
        }
示例#27
0
        //画像ファイルロード
        private bool LoadImageFile(String file_name)
        {
            //カスケード分類器の特徴量を取得する
            CvHaarClassifierCascade cascade = CvHaarClassifierCascade.FromFile(@"C:\opencv2.4.10\sources\data\haarcascades\haarcascade_frontalface_alt.xml");
            CvMemStorage strage = new CvMemStorage(0);   // メモリを確保
            this.ImageFileName = file_name;

            using (IplImage img = new IplImage(this.ImageFileName))
            {
                //グレースケールに変換
                using( IplImage gray_image = Cv.CreateImage(new CvSize(img.Width,img.Height),BitDepth.U8,1) )
                {
                    Cv.CvtColor(img, gray_image, ColorConversion.BgrToGray);

                    //発見した矩形
                    var result = Cv.HaarDetectObjects(gray_image, cascade, strage);
                    for (int i = 0; i < result.Total; i++)
                    {
                        //矩形の大きさに書き出す
                        CvRect rect = result[i].Value.Rect;
                        Cv.Rectangle(img, rect, new CvColor(255, 0, 0));

                        //iplimageをコピー
                        img.ROI = rect;
                        CvRect roi_rect = img.ROI;
                        IplImage ipl_image = Cv.CreateImage(new CvSize(img.Width, img.Height), BitDepth.U8, 1);
                        ipl_image = img.Clone(img.ROI);
/*
                        //確認
                        new CvWindow(ipl_image);
                        Cv.WaitKey();
*/
                        //見つけた顔候補をすべてチェックするために記録する
                        this.FaceIplList.Add(ipl_image);
                    }
                }

                //メモリ解放
                cascade.Dispose();
                strage.Dispose();

                return true;
            }
        }
示例#28
0
        public Morphology()
        {
            // cvMorphologyEx
            // 構造要素を指定して,様々なモルフォロジー演算を行なう

            //(1)画像の読み込み,演算結果画像領域の確保を行なう
            using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.AnyDepth | LoadMode.AnyColor))
            using (IplImage dstImgDilate = srcImg.Clone())
            using (IplImage dstImgErode = srcImg.Clone())
            using (IplImage dstImgOpening = srcImg.Clone())
            using (IplImage dstImgClosing = srcImg.Clone())
            using (IplImage dstImgGradient = srcImg.Clone())
            using (IplImage dstImgTophat = srcImg.Clone())
            using (IplImage dstImgBlackhat = srcImg.Clone())
            using (IplImage tmpImg = srcImg.Clone())
            {
                //(2)構造要素を生成する 
                IplConvKernel element = Cv.CreateStructuringElementEx(9, 9, 4, 4, ElementShape.Rect, null);
                //(3)各種のモルフォロジー演算を実行する 
                Cv.Dilate(srcImg, dstImgDilate, element, 1);
                Cv.Erode(srcImg, dstImgErode, element, 1);
                Cv.MorphologyEx(srcImg, dstImgOpening, tmpImg, element, MorphologyOperation.Open, 1);
                Cv.MorphologyEx(srcImg, dstImgClosing, tmpImg, element, MorphologyOperation.Close, 1);
                Cv.MorphologyEx(srcImg, dstImgGradient, tmpImg, element, MorphologyOperation.Gradient, 1);
                Cv.MorphologyEx(srcImg, dstImgTophat, tmpImg, element, MorphologyOperation.TopHat, 1);
                Cv.MorphologyEx(srcImg, dstImgBlackhat, tmpImg, element, MorphologyOperation.BlackHat, 1);

                //(4)モルフォロジー演算結果を表示する 
                using (new CvWindow("src", srcImg))
                using (new CvWindow("dilate", dstImgDilate))
                using (new CvWindow("erode", dstImgErode)) 
                using (new CvWindow("opening", dstImgOpening)) 
                using (new CvWindow("closing", dstImgClosing)) 
                using (new CvWindow("gradient", dstImgGradient)) 
                using (new CvWindow("tophat", dstImgTophat)) 
                using (new CvWindow("blackhat", dstImgBlackhat))
                {
                    Cv.WaitKey(0);
                }
            }
        }
        public PyrMeanShiftFiltering()
        {
            // cvPyrMeanShiftFiltering
            // 平均値シフト法による画像のセグメント化を行う

            const int level = 2;

            // (1)画像の読み込み
            using (IplImage srcImg = new IplImage(Const.ImageGoryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            {
                if (srcImg.NChannels != 3)
                {
                    throw new Exception();
                }
                if (srcImg.Depth != BitDepth.U8)
                {
                    throw new Exception();
                }

                // (2)領域分割のためにROIをセットする
                CvRect roi = new CvRect
                {
                    X = 0,
                    Y = 0,
                    Width = srcImg.Width & -(1 << level),
                    Height = srcImg.Height & -(1 << level)
                };
                srcImg.ROI = roi;

                // (3)分割結果画像出力用の画像領域を確保し,領域分割を実行
                using (IplImage dstImg = srcImg.Clone())
                {
                    Cv.PyrMeanShiftFiltering(srcImg, dstImg, 30.0, 30.0, level, new CvTermCriteria(5, 1));
                    // (4)入力画像と分割結果画像の表示
                    using (CvWindow wSrc = new CvWindow("Source", srcImg))
                    using (CvWindow wDst = new CvWindow("MeanShift", dstImg))
                    {
                        CvWindow.WaitKey();
                    }
                }
            }

        }
示例#30
0
        public PyrSegmentation()
        {
            const double threshold1 = 255.0;
            const double threshold2 = 50.0; 

            using (IplImage srcImg = new IplImage(FilePath.Image.Goryokaku, LoadMode.AnyDepth | LoadMode.AnyColor))
            {
                IplImage[] dstImg = new IplImage[4];
                for (int level = 0; level < dstImg.Length; level++)
                {
                    CvRect roi = new CvRect()
                    {
                        X = 0,
                        Y = 0,
                        Width = srcImg.Width & -(1 << (level + 1)),
                        Height = srcImg.Height & -(1 << (level + 1))
                    };
                    srcImg.ROI = roi;

                    dstImg[level] = srcImg.Clone();
                    Cv.PyrSegmentation(srcImg, dstImg[level], level + 1, threshold1, threshold2);
                }

                CvWindow wSrc = new CvWindow("src", srcImg);
                CvWindow[] wDst = new CvWindow[dstImg.Length];
                for (int i = 0; i < dstImg.Length; i++)
                {
                    wDst[i] = new CvWindow("dst" + i, dstImg[i]);
                }
                CvWindow.WaitKey();
                CvWindow.DestroyAllWindows();

                foreach (IplImage item in dstImg)
                {
                    item.Dispose();
                }
            }
        }