2017年10月3日火曜日

物体のエッジ検出フィルタ(canyフィルタ)をかけてみる

例によってまるパクリです。

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

using OpenCvSharp;

namespace _02_cameraFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowCamera();
        }

        static void ShowCamera()
        {
            //カメラ映像を表示
            int cameraPort = 0;
            using (var capture = Cv.CreateCameraCapture(cameraPort))
            {
                IplImage frame = new IplImage();

                //  W640 x H480 (default resolution)のウィンドウを作る
                int w = 640, h = 480;

                // カメラ映像の画サイズ設定
                Cv.SetCaptureProperty(capture, CaptureProperty.FrameWidth, w);
                Cv.SetCaptureProperty(capture, CaptureProperty.FrameHeight, h);

                //ESCキー押さない限り
                while (Cv.WaitKey(1) != 27)
                {
                    // 画像の取得
                    frame = Cv.QueryFrame(capture);

                    if (frame != null)
                    {
                        int threshold1 = 120;
                        int threshold2 = 80;

                        //trimmingするための座標
                        int trimmingX = 50;
                        int trimmingY = 20;
                        int trimmingW = 300;
                        int trimmingH = 300;

                        IplImage edgeFrame = new IplImage(frame.Width, frame.Height, BitDepth.U8, 1);
                        frame.Canny(edgeFrame, threshold1, threshold2);

                        //frameをトリミングする
                        IplImage trimmedFrame = trimming(edgeFrame, trimmingX, trimmingY, trimmingW, trimmingH);

                        Cv.ShowImage("Liveカメラ(元)", frame);
                        Cv.ShowImage("Liveカメラ(Edge)", edgeFrame);
                        Cv.ShowImage("抽出した映像", trimmedFrame);

                        //メモリ解放
                        Cv.ReleaseImage(trimmedFrame);
                        Cv.ReleaseImage(edgeFrame);
                        Cv.ReleaseImage(frame);
                    }
                }
                //ESCキーが押されたら
                //全ての画像やwindowを削除
                Cv.DestroyAllWindows();
                capture.Dispose();

            }
        }

        //frameをtrimmingする
        static IplImage trimming(IplImage src, int x, int y, int width, int height)
        {
            IplImage dest = new IplImage(width, height, src.Depth, src.NChannels);
            Cv.SetImageROI(src, new CvRect(x, y, width, height));
            dest = Cv.CloneImage(src);
            Cv.ResetImageROI(src);
            return dest;
        }

    }
}

参照
http://www.thedesignium.com/development/8237

0 件のコメント:

コメントを投稿