ラベル WPF の投稿を表示しています。 すべての投稿を表示
ラベル WPF の投稿を表示しています。 すべての投稿を表示

2017/02/20

WPF PrismとNyARToolKitCSで複数のマーカー位置推定

先ほど、マーカーの位置推定プログラムを書きましたが、今度は複数のマーカーの位置推定を行うプログラムです。
http://kowaimononantenai.blogspot.jp/2017/02/wpf-prismnyartoolkit.html

ファイル構成は上のサイトと同じです。

初めにViewのXamlです。これは上のサイトと全く同じです。

    
        
        

次はViewModelです。
カメラ画像を表示するために、async/awaitで非同期処理を行っています。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;

using System.Threading;
using System.Windows.Media.Imaging;
using System.Numerics;  //.Net Framework 4.6以上

namespace NyARCaptureTest
{
    class MainWindowViewModel: BindableBase
    {
        NyARPositionEstimation NyAr;
        bool isTask;

        /// 
        /// Notifying Property Change
        /// 
        private WriteableBitmap bmp;
        public WriteableBitmap Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }

        /// 
        /// DelegateCommand
        /// 
        private DelegateCommand startCommand;
        public DelegateCommand StartCommand
        {
            get{ return startCommand ?? (startCommand = new DelegateCommand(Start));}
        }
        private async void Start()
        {
            NyAr.Start();

            isTask = true;
            await ShowImage();
        }

        private DelegateCommand stopCommand;
        public DelegateCommand StopCommand
        {
            get { return stopCommand ?? (stopCommand = new DelegateCommand(Stop)); }
        }
        private void Stop()
        {
            NyAr.Stop();
            isTask = false;
        }


        public MainWindowViewModel()
        {
            NyAr = new NyARPositionEstimation();
        }

        /// 
        /// Task
        /// 
        /// 
        private async Task ShowImage()
        {
            while (isTask)
            {
                if (NyAr.IsCaptureOk)
                {
                    Bmp = NyAr.GetImage();

                    Matrix4x4[] matrix;
                    bool[] isEstimateOk;
                    NyAr.GetMatrix(out matrix, out isEstimateOk);

                    if (isEstimateOk[0] == true)
                    {
                        Console.WriteLine(matrix[0]);
                    }
                }
                await Task.Delay(30);
            }
        }
    }
}




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

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.Threading;
using System.Numerics;  //.Net Framework 4.6以上

using jp.nyatla.nyartoolkit.cs;
using jp.nyatla.nyartoolkit.cs.core;
using jp.nyatla.nyartoolkit.cs.detector;
using NyARToolkitCSUtils.Capture;
using NyARToolkitCSUtils.Direct3d;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using OpenCvSharp.Extensions;

namespace NyARCaptureTest
{
    class NyARPositionEstimation : CaptureListener
    {
        private NyARToolkitCSUtils.Capture.CaptureDevice cap;
        private String[] arCodeFile = { "patt.hiro", "patt.kanji" };
        private const String arCameraFile = "camera_para.dat";
        private NyARDetectMarker ar;
        private DsRgbRaster raster;
        private Mat img;
        private Object lockObj = new object();
        private Matrix4x4[] Matrix;

        public bool IsCaptureOk { get; private set; }


        public NyARPositionEstimation()
        {
            IsCaptureOk = false;
            Matrix = new Matrix4x4[2];
            Matrix[0] = Matrix4x4.Identity;
            Matrix[1] = Matrix4x4.Identity;

            //ARの設定
            //AR用カメラパラメタファイルをロード
            NyARParam ap = NyARParam.loadFromARParamFile(File.OpenRead(arCameraFile), 320, 240);

            //AR用のパターンコードを読み出し
            NyARCode[] code = new NyARCode[2];
            code[0] = NyARCode.loadFromARPattFile(File.OpenRead(arCodeFile[0]), 16, 16);
            code[1] = NyARCode.loadFromARPattFile(File.OpenRead(arCodeFile[1]), 16, 16);

            //計算モードの設定
            //キャプチャを作る
            /**************************************************
            このコードは、0番目(一番初めに見つかったキャプチャデバイス)
            を使用するようにされています。
            複数のキャプチャデバイスを持つシステムの場合、うまく動作しないかもしれません。
            n番目のデバイスを使いたいときには、CaptureDevice cap=cl[0];←ここの0を変えてください。
            手動で選択させる方法は、SimpleLiteDirect3Dを参考にしてください。
            **************************************************/
            CaptureDeviceList cl = new CaptureDeviceList();
            NyARToolkitCSUtils.Capture.CaptureDevice cap = cl[0];
            cap.SetCaptureListener(this);
            cap.PrepareCapture(320, 240, 30);
            this.cap = cap;

            //ラスタを作る。
            this.raster = new DsRgbRaster(cap.video_width, cap.video_height);

            this.ar = new NyARDetectMarker(ap, code, new double[] { 80.0, 80.0 }, 2);
            this.ar.setContinueMode(false);
        }


        public void Start()
        {
            this.cap.StartCapture();
        }

        public void Stop()
        {
            this.cap.StopCapture();
        }


        public WriteableBitmap GetImage()
        {
            WriteableBitmap bmp;
            lock (lockObj)
            {
                bmp = img.ToWriteableBitmap();
            }
            return bmp;
        }
        
        public void GetMatrix(out Matrix4x4[] matrix, out bool[] isEstimateOk)
        {
            lock (lockObj)
            {
                matrix = new Matrix4x4[2];
                matrix[0] = GetDeepCopyMatrix4x4(Matrix[0]);
                matrix[1] = GetDeepCopyMatrix4x4(Matrix[1]);

                isEstimateOk = new bool[2];
                if (matrix[0].Equals(Matrix4x4.Identity))
                {
                    isEstimateOk[0] = false;
                }
                else
                {
                    isEstimateOk[0] = true;
                }

                if (matrix[1].Equals(Matrix4x4.Identity))
                {
                    isEstimateOk[1] = false;
                }
                else
                {
                    isEstimateOk[1] = true;
                }
            }
        }
        
        
        public void OnBuffer(NyARToolkitCSUtils.Capture.CaptureDevice i_sender, double i_sample_time, IntPtr i_buffer, int i_buffer_len)
        {
            int w = i_sender.video_width;
            int h = i_sender.video_height;
            int s = w * (i_sender.video_bit_count / 8);

            Bitmap b = new Bitmap(w, h, s, PixelFormat.Format32bppRgb, i_buffer);
            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            this.raster.setBuffer(i_buffer, i_buffer_len, i_sender.video_vertical_flip);

            lock (lockObj)
            {
                img = b.ToMat();
                int detectedMarkerNum = this.ar.detectMarkerLite(this.raster, 100);
                int markerId = 0;

                for (int marker = 0; marker < detectedMarkerNum; marker++)
                {
                    markerId = ar.getARCodeIndex(marker);

                    if (markerId == 0)
                    {
                        NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();
                        this.ar.getTransmationMatrix(markerId, result_mat);
                        Matrix[0] = ConvertNyARDoubleMatrix44ToMatrix4x4(result_mat);
                        NyARSquare square = ar.getSquare(markerId);

                        var point = new OpenCvSharp.CPlusPlus.Point[4];
                        for (int i = 0; i < 4; i++)
                        {
                            point[i] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[i].x, square.sqvertex[i].y);
                        }
                        img.FillConvexPoly(point, new Scalar(0, 0, 255));
                    }

                    if (markerId == 1)
                    {
                        NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();
                        this.ar.getTransmationMatrix(markerId, result_mat);
                        Matrix[1] = ConvertNyARDoubleMatrix44ToMatrix4x4(result_mat);
                        NyARSquare square = ar.getSquare(markerId);

                        var point = new OpenCvSharp.CPlusPlus.Point[4];
                        for (int i = 0; i < 4; i++)
                        {
                            point[i] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[i].x, square.sqvertex[i].y);
                        }
                        img.FillConvexPoly(point, new Scalar(255, 0, 0));
                    }
                }

                if (detectedMarkerNum == 1)
                {
                    if (markerId == 0)
                    {
                        Matrix[1] = Matrix4x4.Identity;
                    }
                    else if (markerId == 1)
                    {
                        Matrix[0] = Matrix4x4.Identity;
                    }
                }
                else if (detectedMarkerNum == 0)
                {
                    Matrix[0] = Matrix4x4.Identity;
                    Matrix[1] = Matrix4x4.Identity;
                }
                IsCaptureOk = true;
            }
        }

        private Matrix4x4 ConvertNyARDoubleMatrix44ToMatrix4x4(NyARDoubleMatrix44 m)
        {
            return new Matrix4x4((float)m.m00,
                                    (float)m.m01,
                                    (float)m.m02,
                                    (float)m.m03,
                                    (float)m.m10,
                                    (float)m.m11,
                                    (float)m.m12,
                                    (float)m.m13,
                                    (float)m.m20,
                                    (float)m.m21,
                                    (float)m.m22,
                                    (float)m.m23,
                                    (float)m.m30,
                                    (float)m.m31,
                                    (float)m.m32,
                                    (float)m.m33);
        }

        private Matrix4x4 GetDeepCopyMatrix4x4(Matrix4x4 m)
        {
            return new Matrix4x4(m.M11,
                                    m.M12,
                                    m.M13,
                                    m.M14,
                                    m.M21,
                                    m.M22,
                                    m.M23,
                                    m.M24,
                                    m.M31,
                                    m.M32,
                                    m.M33,
                                    m.M34,
                                    m.M41,
                                    m.M42,
                                    m.M43,
                                    m.M44);
        }
    }
}







WPF PrismとNyARToolKitでマーカー位置推定

マーカーの位置推定を行うプログラムです。
以下のことを行います。
①カメラ座標系からマーカー座標系への同時変換行列を取得(Consoleに出力)
②マーカーにグラフィックを描画して、カメラ画像を表示

 これでは、NyARToolKitCS, OpenCVSharp,Prism.MVVMを使用しています。


初めにXamlです。


    
        
        


次にViewModelです。

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

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;

using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Windows.Threading;
using System.Threading;
using System.Windows.Media.Imaging;

namespace NyARCaptureTest
{
    class MainWindowViewModel: BindableBase
    {
        NyARPositionEstimation NyAr;
        bool isTask;

        /// 
        /// Notifying Property Change
        /// 
        private WriteableBitmap bmp;
        public WriteableBitmap Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }

        /// 
        /// DelegateCommand
        /// 
        private DelegateCommand startCommand;
        public DelegateCommand StartCommand
        {
            get{ return startCommand ?? (startCommand = new DelegateCommand(Start));}
        }
        private async void Start()
        {
            NyAr.Start();

            isTask = true;
            await ShowImage();
        }

        private DelegateCommand stopCommand;
        public DelegateCommand StopCommand
        {
            get { return stopCommand ?? (stopCommand = new DelegateCommand(Stop)); }
        }
        private void Stop()
        {
            NyAr.Stop();
            isTask = false;
        }


        public MainWindowViewModel()
        {
            NyAr = new NyARPositionEstimation();
        }

        /// 
        /// Task
        /// 
        /// 
        private async Task ShowImage()
        {

            while (isTask)
            {
                if (NyAr.IsCaptureOK)
                {
                    Bmp = NyAr.GetImage();
                    Console.WriteLine(NyAr.Matrix);
                }

                await Task.Delay(30);
            }
        }
    }
}


最後にModelです。
マーカーの位置推定はNyARToolKitCSのサンプルを参考にNyARPositionEstimationクラスを作りました。
基本的に処理はこちらで行っています。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Drawing.Imaging;
using jp.nyatla.nyartoolkit.cs;
using jp.nyatla.nyartoolkit.cs.core;
using jp.nyatla.nyartoolkit.cs.detector;
using NyARToolkitCSUtils.Capture;
using NyARToolkitCSUtils.Direct3d;
using System.IO;

using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using OpenCvSharp.Extensions;

using System.Windows.Threading;
using System.Windows.Media.Imaging;

using System.Numerics;  //.Net Framework 4.6以上

namespace NyARCaptureTest
{
    class NyARPositionEstimation : CaptureListener
    {
        private NyARToolkitCSUtils.Capture.CaptureDevice m_cap;
        private const String AR_CODE_FILE = "patt.hiro";
        private const String AR_CAMERA_FILE = "camera_para.dat";
        private NyARSingleDetectMarker m_ar;
        private DsRgbRaster m_raster;

        private Mat Img;
        public Matrix4x4 Matrix { get; private set; }

        public bool IsCaptureOK { get; private set; }


        public NyARPositionEstimation()
        {
            IsCaptureOK = false;
            //ARの設定
            //AR用カメラパラメタファイルをロード
            NyARParam ap = NyARParam.loadFromARParamFile(File.OpenRead(AR_CAMERA_FILE), 320, 240);

            //AR用のパターンコードを読み出し 
            NyARCode code = NyARCode.loadFromARPattFile(File.OpenRead(AR_CODE_FILE), 16, 16);

            //NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();
            //計算モードの設定
            //キャプチャを作る
            /**************************************************
            このコードは、0番目(一番初めに見つかったキャプチャデバイス)
            を使用するようにされています。
            複数のキャプチャデバイスを持つシステムの場合、うまく動作しないかもしれません。
            n番目のデバイスを使いたいときには、CaptureDevice cap=cl[0];←ここの0を変えてください。
            手動で選択させる方法は、SimpleLiteDirect3Dを参考にしてください。
            **************************************************/
            CaptureDeviceList cl = new CaptureDeviceList();
            NyARToolkitCSUtils.Capture.CaptureDevice cap = cl[0];
            cap.SetCaptureListener(this);
            cap.PrepareCapture(320, 240, 30);
            this.m_cap = cap;
            //ラスタを作る。
            this.m_raster = new DsRgbRaster(cap.video_width, cap.video_height);
            //1パターンのみを追跡するクラスを作成
            this.m_ar = NyARSingleDetectMarker.createInstance(ap, code, 80.0);
            this.m_ar.setContinueMode(false);
        }


        public void Start()
        {
            this.m_cap.StartCapture();
        }

        public void Stop()
        {
            this.m_cap.StopCapture();
        }


        public WriteableBitmap GetImage()
        {
            return Img.ToWriteableBitmap();
        }


        public void OnBuffer(NyARToolkitCSUtils.Capture.CaptureDevice i_sender, double i_sample_time, IntPtr i_buffer, int i_buffer_len)
        {
            int w = i_sender.video_width;
            int h = i_sender.video_height;
            int s = w * (i_sender.video_bit_count / 8);

            Bitmap b = new Bitmap(w, h, s, PixelFormat.Format32bppRgb, i_buffer);

            // If the image is upsidedown
            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            Img = b.ToMat();

            //ARの計算
            this.m_raster.setBuffer(i_buffer, i_buffer_len, i_sender.video_vertical_flip);
            if (this.m_ar.detectMarkerLite(this.m_raster, 100))
            {
                NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();
                this.m_ar.getTransmationMatrix(result_mat);
                Matrix = ConvertNyARDoubleMatrix44ToMatrix4x4(result_mat);

                //Console.WriteLine("Maker is found.");

                NyARSquare square = m_ar.refSquare();

                var point = new OpenCvSharp.CPlusPlus.Point[4];
                for (int i = 0; i < 4; i++)
                {
                    point[i] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[i].x, square.sqvertex[i].y);
                }
                Img.FillConvexPoly(point, new Scalar(0, 0, 255));
            }
            else
            {
                //Console.WriteLine("Maker is NOT found.");
            }

            IsCaptureOK = true;
        }

        private Matrix4x4 ConvertNyARDoubleMatrix44ToMatrix4x4(NyARDoubleMatrix44 m)
        {
            return new Matrix4x4(   (float)m.m00,
                                    (float)m.m01,
                                    (float)m.m02,
                                    (float)m.m03,
                                    (float)m.m10,
                                    (float)m.m11,
                                    (float)m.m12,
                                    (float)m.m13,
                                    (float)m.m20,
                                    (float)m.m21,
                                    (float)m.m22,
                                    (float)m.m23,
                                    (float)m.m30,
                                    (float)m.m31,
                                    (float)m.m32,
                                    (float)m.m33);
        }
    }
}



2017/02/05

WPF PrismとOpenCVSharpでWebカメラの画像表示

OpenCVSharpを使ってWebカメラの画像を取得し、WPFのImageで表示します。
プロジェクトは以下のようになっていて、View、Model、ViewModelそれぞれ1ファイルづつあります。

初めに、ViewのMainWindow.xamlです。

    
        
        



次にViewModelのMainWindowViewModel.cs。
画像の表示は別タスクにしていて、async/awaitで非同期処理を行っています。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CaptureCamera.Model;

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using System.Windows.Media.Imaging;

namespace CaptureCamera.ViewModel
{
    class MainWindowViewModel: BindableBase
    {
        Camera camera;
        bool isTask = true;

        public MainWindowViewModel()
        {
        }

        /// 
        /// Change Property
        /// 
        private WriteableBitmap bmp;
        public WriteableBitmap Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }


        /// 
        /// DelegateCommand
        /// 
        private DelegateCommand startCaptureCommand;
        public DelegateCommand StartCaptureCommand
        {
            get { return startCaptureCommand ?? (startCaptureCommand = new DelegateCommand(StartCapture)); }
        }
        private async void StartCapture()
        {
            camera = new Camera();
            await ShowImage();
        }

        private DelegateCommand stopCaptureCommand;
        public DelegateCommand StopCaptureCommand
        {
            get { return stopCaptureCommand ?? (stopCaptureCommand = new DelegateCommand(StopCapture)); }
        }
        private void StopCapture()
        {
            isTask = false;
        }


        /// 
        /// Task
        /// 
        /// 
        private async Task ShowImage()
        {
            while (isTask)
            {
                Bmp = camera.Capture();
                if (Bmp == null) break;

                await Task.Delay(30);
            }
        }
    }
}


最後にModelのCamera.cs。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Win32;
using System.Windows.Media.Imaging;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using OpenCvSharp.Extensions;

namespace CaptureCamera.Model
{
    class Camera
    {
        VideoCapture capture;
        Mat frame;

        public Camera()
        {
            capture = new VideoCapture(0);
            if (!capture.IsOpened())
                throw new Exception("capture initialization failed");
            frame = new Mat();
        }

        public WriteableBitmap Capture()
        {
            capture.Read(frame);
            if (frame.Empty())
                return null;

            return frame.ToWriteableBitmap();
        }
    }
}


WPF PrismとOpenCVSharpを使って画像の表示

先ほど、Prismを使って画像を表示するWPFアプリケーションを作成しました。

○○○○に怖いものなんてない!!: WPF(Prism)で画像の表示
http://kowaimononantenai.blogspot.jp/2017/02/wpfprism.html

画像処理等にはOpenCVSharpを使用することが多いので、
画像入力はOpenCVSharpを使用して、Matで管理するサンプルプログラムに変更しました。
でも、画像の表示はWPFのImageで表示しています。

プログラムは同じようにView,ViewModel,Modelに分けて管理しています。

まずはDisplayImageWindow.xamlです。

    
        
        



次はDisplayImageWindowViewModel.cs。
さきほどと違うのはBitmapImageからWriteableBitmapに変更になったところです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using DisplayImage.Model;

using System.Windows.Media.Imaging;

namespace DisplayImage.ViewModel
{
    class DisplayImageWindowViewModel: BindableBase
    {
        public DisplayImageWindowViewModel()
        {
            Displayer = new ImageDisplayer();
        }

        ImageDisplayer Displayer;

        //=================
        //Change Property
        //=================
        private string filePath;
        public string FilePath
        {
            get { return filePath; }
            set { SetProperty(ref filePath, value); }
        }

        private WriteableBitmap bmp;
        public WriteableBitmap Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }

        //=================
        //DeligateCommand
        //=================
        private DelegateCommand fileOpenCommand;
        public DelegateCommand FileOpenCommand
        {
            get { return fileOpenCommand ?? (fileOpenCommand = new DelegateCommand(FileOpen)); }
        }
        public void FileOpen()
        {
            Displayer.FileOpen();

            FilePath = Displayer.FilePath;
            Bmp = Displayer.GetImage();
        }
    }
}


最後にImageDisplayer.csです。
OpenCVSharpで画像を入力した後、表示するときだけWriteableBitmapに変換して渡します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Win32;
using System.Windows.Media.Imaging;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using OpenCvSharp.Extensions;

namespace DisplayImage.Model
{
    class ImageDisplayer
    {
        public ImageDisplayer()
        {
        }

        public string FilePath { get; set; }
        private Mat Img;

        public void FileOpen()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Image File.";
            dlg.Filter = "Image File|*.jpg";

            if (dlg.ShowDialog() == true)
            {
                FilePath = dlg.FileName;
                Img = new Mat(FilePath);
            }
        }

        public WriteableBitmap GetImage()
        {
            return Img.ToWriteableBitmap();
        }
    }
}





WPF(Prism)で画像の表示

Prismを利用したWPFアプリケーションで、選択した画像を表示するプログラムを作成します。

実際に作ったのは下図で、このような機能があります。
①Openボタンでファイル選択ダイヤログが開き、jpgファイルを選択する
②TextBoxにファイルのパスが表示される
③画像が下に表示される


まず、NuGetで「Prism.MVVM」をインストールしておいてください。
プロジェクトでは下図のように3つのフォルダでMVVMごとに管理しています。


 まず、DisplayImageWindow.xamlは以下のようになります。

    
        
        

次に、DisplayImageWindowViewModelは以下のようになります。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using DisplayImage.Model;

using System.Windows.Media.Imaging;

namespace DisplayImage.ViewModel
{
    class DisplayImageWindowViewModel: BindableBase
    {
        public DisplayImageWindowViewModel()
        {
            Displayer = new ImageDisplayer();
        }

        ImageDisplayer Displayer;

        //=================
        //Change Property
        //=================
        private string filePath;
        public string FilePath
        {
            get { return filePath; }
            set { SetProperty(ref filePath, value); }
        }

        private BitmapImage bmp;
        public BitmapImage Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }

        //=================
        //DeligateCommand
        //=================
        private DelegateCommand fileOpenCommand;
        public DelegateCommand FileOpenCommand
        {
            get { return fileOpenCommand ?? (fileOpenCommand = new DelegateCommand(FileOpen)); }
        }
        public void FileOpen()
        {
            Displayer.FileOpen();

            FilePath = Displayer.FilePath;
            Bmp = Displayer.Bmp;
        }
    }
}


最後にImageDisplayerです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Win32;
using System.Windows.Media.Imaging;

namespace DisplayImage.Model
{
    class ImageDisplayer
    {
        public ImageDisplayer()
        {
        }

        public string FilePath { get; set; }
        public BitmapImage Bmp;

        public void FileOpen()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Image File.";
            dlg.Filter = "Image File|*.jpg";

            if (dlg.ShowDialog() == true)
            {
                FilePath = dlg.FileName;

                Bmp = new BitmapImage();
                Bmp.BeginInit();
                Bmp.UriSource = new Uri(FilePath);
                Bmp.EndInit();

            }
        }
    }
}


2016/11/05

WPF(Livet)とNyARToolKitでマーカー検出

マーカーの位置検出を行うために、マーカーの検出をNyARToolKitで行うサンプルプログラムを作成しました。
次のようなことをやります。
  1. Livetを使用したWPFアプリケーション
  2. NyARToolKitでカメラキャプチャとマーカー検出
  3. OpenCVSharpでマーカー位置に矩形を描画
初めにXAML。Grid内だけ変更しています。ボタンを押すとマーカー検出がスタートします。
    
        


次にVeiwModel。
NyARToolKitはその実装の関係上「onBuffer」という関数が呼ばれるので、その中で処理をしています。
NyARToolKitのサンプル等ではBitmapで画像を処理しているので、
それをMatに変換してOpenCVSharpで矩形を描画しています。

そのあとに、MatをWriteableBitmapに直して、XAMLでBindingできるようにします。
ここで、onBufferという別タスクでUIで利用するWriteableBitmapを変更できないので、
Dispatchar.BeginInvokeを使用して、UI関係にアクセスできるようにしています。

using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

using jp.nyatla.nyartoolkit.cs;
using jp.nyatla.nyartoolkit.cs.core;
using jp.nyatla.nyartoolkit.cs.detector;
using NyARToolkitCSUtils.Capture;
using NyARToolkitCSUtils.Direct3d;

using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using OpenCvSharp.Extensions;

namespace ar_SimpleLite.ViewModels
{
    public class MainWindowViewModel : ViewModel, CaptureListener
    {
        private NyARToolkitCSUtils.Capture.CaptureDevice m_cap;
        private const String AR_CODE_FILE = "patt.hiro";
        private const String AR_CAMERA_FILE = "camera_para.dat";
        private NyARSingleDetectMarker m_ar;
        private DsRgbRaster m_raster;

        private Dispatcher dispatcher;

        public void Initialize()
        {
            //ARの設定
            //AR用カメラパラメタファイルをロード
            NyARParam ap = NyARParam.createFromARParamFile(new StreamReader(AR_CAMERA_FILE));
            ap.changeScreenSize(320, 240);

            //AR用のパターンコードを読み出し 
            NyARCode code = NyARCode.createFromARPattFile(new StreamReader(AR_CODE_FILE), 16, 16);

            NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();

            //計算モードの設定
            //キャプチャを作る
            /**************************************************
            このコードは、0番目(一番初めに見つかったキャプチャデバイス)
            を使用するようにされています。
            複数のキャプチャデバイスを持つシステムの場合、うまく動作しないかもしれません。
            n番目のデバイスを使いたいときには、CaptureDevice cap=cl[0];←ここの0を変えてください。
            手動で選択させる方法は、SimpleLiteDirect3Dを参考にしてください。
            **************************************************/
            CaptureDeviceList cl = new CaptureDeviceList();
            NyARToolkitCSUtils.Capture.CaptureDevice cap = cl[0];

            cap.SetCaptureListener(this);

            cap.PrepareCapture(320, 240, 30);
            this.m_cap = cap;
            //ラスタを作る。
            this.m_raster = new DsRgbRaster(cap.video_width, cap.video_height, NyARBufferType.OBJECT_CS_Bitmap);
            //1パターンのみを追跡するクラスを作成
            this.m_ar = NyARSingleDetectMarker.createInstance(ap, code, 80.0);
            this.m_ar.setContinueMode(false);

            dispatcher = Dispatcher.CurrentDispatcher;
        }


        #region WBmp変更通知プロパティ
        private WriteableBitmap _WBmp;

        public WriteableBitmap WBmp
        {
            get
            { return _WBmp; }
            set
            { 
                if (_WBmp == value)
                    return;
                _WBmp = value;
                RaisePropertyChanged();
            }
        }
        #endregion


        #region ButtonCommand
        private ViewModelCommand _ButtonCommand;

        public ViewModelCommand ButtonCommand
        {
            get
            {
                if (_ButtonCommand == null)
                {
                    _ButtonCommand = new ViewModelCommand(Button);
                }
                return _ButtonCommand;
            }
        }

        public void Button()
        {
            this.m_cap.StartCapture();
        }
        #endregion


        public void OnBuffer(NyARToolkitCSUtils.Capture.CaptureDevice i_sender, double i_sample_time, IntPtr i_buffer, int i_buffer_len)
        {            
            int w = i_sender.video_width;
            int h = i_sender.video_height;
            int s = w * (i_sender.video_bit_count / 8);

            Bitmap b = new Bitmap(w, h, s, System.Drawing.Imaging.PixelFormat.Format32bppRgb, i_buffer);

            // If the image is upsidedown
            b.RotateFlip(RotateFlipType.RotateNoneFlipY);
            Mat img = b.ToMat();

            //ARの計算
            this.m_raster.setBuffer(i_buffer, i_buffer_len, i_sender.video_vertical_flip);
            if (this.m_ar.detectMarkerLite(this.m_raster, 100))
            {
                NyARDoubleMatrix44 result_mat = new NyARDoubleMatrix44();
                this.m_ar.getTransmationMatrix(result_mat);
                Console.WriteLine("Maker is found.");

                NyARSquare square = m_ar.refSquare();

                var point = new OpenCvSharp.CPlusPlus.Point[4];
                point[0] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[0].x, square.sqvertex[0].y);
                point[1] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[1].x, square.sqvertex[1].y);
                point[2] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[2].x, square.sqvertex[2].y);
                point[3] = new OpenCvSharp.CPlusPlus.Point(square.sqvertex[3].x, square.sqvertex[3].y);

                img.FillConvexPoly(point, new Scalar(0, 0, 255));
            }
            else
            {
                Console.WriteLine("Maker is NOT found.");
            }

            dispatcher.BeginInvoke(new Action(delegate()
            {

                WBmp = img.ToWriteableBitmap();
            }));
        }

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
    }
}


2016/11/03

WPFで「using System.Windows.Forms」を行うとエラーになる

WPFでもWindows Formを使用することはよくあることなのですが、
たまに
using System.Windows.Forms
をするとエラーになってしまう時があります。


こうなった時には次の対処を行うことで解決できます。

メニュー -> プロジェクト -> 参照の追加

System.Windows.Formsにチェックを入れて、おk。

これでエラーが出なくなりました。

2016/10/30

WPF(Livet)でasync/awaitを使って非同期処理

async/awaitを使って非同期処理を行うサンプルを載せます。
ただ非同期処理をするだけではなく、進捗状況をProgressBarで表示し、CancelボタンでCancelできるようにしています。

 
 まずはXAMLです。Grid内だけ記載しています。
    
        

ViewModelです。
非同期処理を行う関数はTaskFuncなのですが、CancellationTokenを引数に取っているので、Cancelすると例外を出します。
進捗状況はProgressPercentに直接値を代入してXAMLのほうでProgressBarにBindingしています。
Windows FormではIProgressクラスを使用して値をUIスレッドに渡さないといけないのですが、
そもそもWPFではBindingによってUIスレッドとは切り離されているので、ただBindingするだけでいいと思います。
using System.Windows;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwaiteSample.ViewModels
{
    public class MainWindowViewModel : ViewModel
    {
        CancellationTokenSource cancelSrc;

        public void Initialize()
        {
        }

        #region ProgressPercent変更通知プロパティ
        private int _ProgressPercent;

        public int ProgressPercent
        {
            get
            { return _ProgressPercent; }
            set
            { 
                if (_ProgressPercent == value)
                    return;
                _ProgressPercent = value;
                RaisePropertyChanged();
            }
        }
        #endregion


        #region StartCommand
        private ViewModelCommand _StartCommand;

        public ViewModelCommand StartCommand
        {
            get
            {
                if (_StartCommand == null)
                {
                    _StartCommand = new ViewModelCommand(Start);
                }
                return _StartCommand;
            }
        }

        public async void Start()
        {
            cancelSrc = new CancellationTokenSource();

            await Task.Run(() => TaskFunc(cancelSrc.Token));

        }
        #endregion


        #region StopCommand
        private ViewModelCommand _StopCommand;

        public ViewModelCommand StopCommand
        {
            get
            {
                if (_StopCommand == null)
                {
                    _StopCommand = new ViewModelCommand(Stop);
                }
                return _StopCommand;
            }
        }

        public void Stop()
        {
            cancelSrc.Cancel();
        }
        #endregion


        private void TaskFunc(CancellationToken cancel)
        {
            try
            {
                //時間がかかる処理
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(100);

                    cancel.ThrowIfCancellationRequested();
                    ProgressPercent = i;
                }
                MessageBox.Show("Finish!!");
            }
            catch (OperationCanceledException ex)
            {
                MessageBox.Show("Cancelされました",
                                "エラー",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
            }
        }
    }





}









2016/10/29

WPF(Livet)でBehaviorを利用してViewからViewModelにデータを渡す

LivetでViewからViewModelにデータを渡すとき、
例えばViewModelCommandを利用して、「ボタンを押したときにTextの値を読み込む」等が例として挙げられていますが、
そのようなやり方ではなく、ViewからViewModelにトリガ経由で値を渡したくなる時があります。
例えば、
・画像をクリックしたとき
・マウスのホイールを動かしたとき
・マウスのカーソルを動かしたとき
等々。。。

そんな時はBehaviorを利用して、値を渡します。
次の例は「表示した画像の中でマウスカーソルが示すPixel数をTextに表示させる」というものです。




 ファイルの構成は以下のようになります。Behaviorフォルダを切って、MouseMoveBehavior.csを新規追加します。


まずは、XAMLです。今回はGrid外にも編集しているので、全部載せます。
xmlns:b="clr-namespace:LivetSample.Behaviors"
でXAMLからMouseMoveBehavior.csにアクセスできるようにしているので、
<b:MouseMoveAction として、使用できるっていうことですね。






    
        
    

    
        
            
        

        
            
        
    

    
        
        



次にViewModelです。
ここでは、MouseMoveのトリガを受けるListenerCommandを定義しています。
そこでViewにBindingしているMousePosに値を代入しています。
using Microsoft.Win32;
using System.Windows;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace LivetSample.ViewModels
{
    public class MainWindowViewModel : ViewModel
    {
        public void Initialize()
        {
        }

        #region FileUri変更通知プロパティ
        private string _FileUri;

        public string FileUri
        {
            get
            { return _FileUri; }
            set
            { 
                if (_FileUri == value)
                    return;
                _FileUri = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region MousePos変更通知プロパティ
        private Point _MousePos;

        public Point MousePos
        {
            get
            { return _MousePos; }
            set
            { 
                if (_MousePos == value)
                    return;
                _MousePos = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region WBitmap変更通知プロパティ
        private WriteableBitmap _WBitmap;

        public WriteableBitmap WBitmap
        {
            get
            { return _WBitmap; }
            set
            { 
                if (_WBitmap == value)
                    return;
                _WBitmap = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region FileOpenCommand
        private ViewModelCommand _FileOpenCommand;

        public ViewModelCommand FileOpenCommand
        {
            get
            {
                if (_FileOpenCommand == null)
                {
                    _FileOpenCommand = new ViewModelCommand(FileOpen);
                }
                return _FileOpenCommand;
            }
        }

        public void FileOpen()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "ファイルを開く";
            dlg.Filter = "画像ファイル|*.jpg";
            if (dlg.ShowDialog() == true)
            {
                FileUri = dlg.FileName;
                using (var img = new IplImage(FileUri))
                {
                    WBitmap = img.ToWriteableBitmap();
                }
            }
        }
        #endregion

        #region MouseMoveCommand
        private ListenerCommand _MouseMoveCommand;

        public ListenerCommand MouseMoveCommand
        {
            get
            {
                if (_MouseMoveCommand == null)
                {
                    _MouseMoveCommand = new ListenerCommand(MouseMove);
                }
                return _MouseMoveCommand;
            }
        }

        public void MouseMove(Point parameter)
        {
            MousePos = parameter;
        }
        #endregion
    }
}


最後にMouseMoveBehavior.csです。ここでBehaviorを定義しています。
これは使用したいBehaviorごとに自分で作っていかないといけないみたいですね。。。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

using Livet;
using Livet.Commands;
using Livet.Messaging;
using Livet.Messaging.IO;
using Livet.EventListeners;
using Livet.Messaging.Windows;

using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;

namespace LivetSample.Behaviors
{
    public class MouseMoveAction : TriggerAction
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
            "Command", typeof(ICommand), typeof(MouseMoveAction), new UIPropertyMetadata(null)
            );

        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        protected override void Invoke(object parameter)
        {
            var eventArgs = parameter as MouseEventArgs;
            var element = AssociatedObject as IInputElement;

            if (Command == null || eventArgs == null || element == null) return;
            var position = eventArgs.GetPosition(element);

            if (Command.CanExecute(position))
            {
                Command.Execute(position);
            }
        }
    }
}