Exemplo n.º 1
0
        public ConvertToBitmapSource()
        {
            BitmapSource bs = null;

            // OpenCVによる画像処理 (Threshold)
            using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> BitmapSource
                bs = dst.ToBitmapSource();
                //bs = BitmapSourceConverter.ToBitmapSource(dst);
            }

            // WPFのWindowに表示してみる
            Image image = new Image { Source = bs };
            Window window = new Window
            {
                Title = "from IplImage to BitmapSource",
                Width = bs.PixelWidth,
                Height = bs.PixelHeight,
                Content = image
            };

            Application app = new Application();
            app.Run(window);
        }
        public ConvertToWriteableBitmap()
        {
            WriteableBitmap wb = null;

            // OpenCVによる画像処理 (Threshold)
            using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> WriteableBitmap
                wb = dst.ToWriteableBitmap(PixelFormats.BlackWhite);
                //wb = WriteableBitmapConverter.ToWriteableBitmap(dst, PixelFormats.BlackWhite);
            }

            // WPFのWindowに表示してみる
            Image image = new Image { Source = wb };
            Window window = new Window
            {
                Title = "from IplImage to WriteableBitmap",
                Width = wb.PixelWidth,
                Height = wb.PixelHeight,
                Content = image
            };

            Application app = new Application();
            app.Run(window);
        }
Exemplo n.º 3
0
        public ConvertToWriteableBitmap()
        {
            WriteableBitmap wb = null;

            // OpenCV processing
            using (var src = new IplImage(FilePath.Image.Lenna, LoadMode.GrayScale))
            using (var dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> WriteableBitmap
                wb = dst.ToWriteableBitmap(PixelFormats.BlackWhite);
                //wb = WriteableBitmapConverter.ToWriteableBitmap(dst, PixelFormats.BlackWhite);
            }

            // Shows WriteableBitmap to WPF window
            var image = new Image { Source = wb };
            var window = new Window
            {
                Title = "from IplImage to WriteableBitmap",
                Width = wb.PixelWidth,
                Height = wb.PixelHeight,
                Content = image
            };

            var app = new Application();
            app.Run(window);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 画像データのファイルストレージへの書き込み
        /// </summary>
        /// <param name="fileName">書きこむXML or YAMLファイル</param>
        private static void SampleFileStorageWriteImage(string fileName)
        {
            // cvWrite, cvWriteComment
            // IplImage構造体の情報をファイルに保存する

            // (1)画像を読み込む
            using (IplImage colorImg = new IplImage(Const.ImageLenna, LoadMode.Color))
            using (IplImage grayImg = new IplImage(colorImg.Size, BitDepth.U8, 1))
            {
                // (2)ROIの設定と二値化処理
                colorImg.CvtColor(grayImg, ColorConversion.BgrToGray);
                CvRect roi = new CvRect(0, 0, colorImg.Width / 2, colorImg.Height / 2);
                grayImg.SetROI(roi);
                colorImg.SetROI(roi);
                grayImg.Threshold(grayImg, 90, 255, ThresholdType.Binary);
                // (3)xmlファイルへの書き出し 
                using (CvFileStorage fs = new CvFileStorage(fileName, null, FileStorageMode.Write))
                {
                    fs.WriteComment("This is a comment line.", false);
                    fs.Write("color_img", colorImg);
                    fs.StartNextStream();
                    fs.Write("gray_img", grayImg);
                }
                // (4)書きこんだxmlファイルを開く
                //using (Process p = Process.Start(fileName)) {
                //    p.WaitForExit();
                //}                
            }
        }
Exemplo n.º 5
0
        public ConvertToBitmap()
        {
            Bitmap bitmap = null;

            // do cvThreshold
            using (IplImage src = new IplImage(FilePath.Image.Lenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> Bitmap
                bitmap = dst.ToBitmap();
                //bitmap = BitmapConverter.ToBitmap(dst);
            }

            // visualize using WindowsForm
            Form form = new Form
            {
                Text = "from IplImage to Bitmap",
                ClientSize = bitmap.Size,
            };
            PictureBox pictureBox = new PictureBox
            {
                Dock = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.StretchImage,
                Image = bitmap
            };

            form.Controls.Add(pictureBox);
            form.ShowDialog();

            form.Dispose();
            bitmap.Dispose();
        }
Exemplo n.º 6
0
 public Threshold()
 {
     using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.Color))
     using (IplImage srcGray = new IplImage(src.Size, BitDepth.U8, 1))
     using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
     using (CvWindow window = new CvWindow("SampleThreshold"))
     {
         src.CvtColor(srcGray, ColorConversion.BgrToGray);
         srcGray.Smooth(srcGray, SmoothType.Gaussian, 5);
         int threshold = 90;
         window.CreateTrackbar("threshold", threshold, 255, delegate(int pos)
         {
             srcGray.Threshold(dst, pos, 255, ThresholdType.Binary);
             window.Image = dst;
         });
         srcGray.Threshold(dst, threshold, 255, ThresholdType.Binary);
         window.Image = dst;
         CvWindow.WaitKey();
     }
 }
Exemplo n.º 7
0
        public ConvertToBitmap()
        {
            Bitmap bitmap = null;

            // OpenCVによる画像処理 (Threshold)
            using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.GrayScale))
            using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1))
            {
                src.Smooth(src, SmoothType.Gaussian, 5);
                src.Threshold(dst, 0, 255, ThresholdType.Otsu);
                // IplImage -> Bitmap
                bitmap = dst.ToBitmap();
                //bitmap = BitmapConverter.ToBitmap(dst);
            }

            // WindowsFormに表示してみる
            Form form = new Form
            {
                Text = "from IplImage to Bitmap",
                ClientSize = bitmap.Size,
            };
            PictureBox pictureBox = new PictureBox
            {
                Dock = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.StretchImage,
                Image = bitmap
            };
            /*
            Imageプロパティに設定するのはもしかするとちょっと微妙、できればこのように
            pictureBox.Paint += delegate(object sender, PaintEventArgs e) {
                e.Graphics.DrawImage(bitmap, new Rectangle(new Point(0, 0), form.ClientSize));
            };
            */
            form.Controls.Add(pictureBox);
            form.ShowDialog();

            form.Dispose();
            bitmap.Dispose();
        }
Exemplo n.º 8
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        private static void SampleFileStorageWriteImage(string fileName)
        {
            // cvWrite, cvWriteComment

            using (IplImage colorImg = new IplImage(FilePath.Image.Lenna, LoadMode.Color))
            using (IplImage grayImg = new IplImage(colorImg.Size, BitDepth.U8, 1))
            {
                colorImg.CvtColor(grayImg, ColorConversion.BgrToGray);
                CvRect roi = new CvRect(0, 0, colorImg.Width / 2, colorImg.Height / 2);
                grayImg.SetROI(roi);
                colorImg.SetROI(roi);
                grayImg.Threshold(grayImg, 90, 255, ThresholdType.Binary);

                using (CvFileStorage fs = new CvFileStorage(fileName, null, FileStorageMode.Write))
                {
                    fs.WriteComment("This is a comment line.", false);
                    fs.Write("color_img", colorImg);
                    fs.StartNextStream();
                    fs.Write("gray_img", grayImg);
                }
            }
        }
        /// <summary>
        /// 認識処理を行う
        /// </summary>
        /// <param name="imagePath">認識対象の画像パス</param>
        /// <param name="isDebug">デバッグモード</param>
        /// <returns></returns>
        public static String Recognize(String imagePath, bool isDebug = false)
        {
            List<String> results = new List<string>();

            // 検出対象の画像を読み込み
            IplImage src = new IplImage(imagePath, LoadMode.GrayScale);

            using (IplImage tmpImage = new IplImage(src.Size, BitDepth.U8, 1))
            {
                // 1)検出前処理

                // エッジ強調
                src.UnsharpMasking(src, 3);

                // 大津の手法による二値化処理
                // 大津, "判別および最小2乗基準に基づく自動しきい値選定法", 電子通信学会論文誌, Vol.J63-D, No.4, pp.349-356, 1980.
                src.Threshold(tmpImage, 200, 250, ThresholdType.Otsu);

                src.Dispose();

                Dictionary<int, List<double>> shapeMatchResults = new Dictionary<int, List<double>>();

                List<string> answerFileNames = washTagDictionary.Keys.ToList();
                foreach (var answerFileName in answerFileNames)
                {
                    var washTagInfo = washTagDictionary[answerFileName];
                    var answerImagePath = String.Format(@"answer\{0}.png", answerFileName);

                    // 2) 検出処理
                    var resultSURF = SURF(tmpImage, answerImagePath, isDebug);

                    // 3) 検出候補の評価
                    string result = null;

                    // その1:頂点がある場合
                    if (resultSURF.dstCorners != null)
                    {
                        // TODO:平面評価
                        //result = fileBaseName + " : " + washTagDictionary[fileBaseName];
                    }

                    // その2:形状マッチング
                    if (result == null && resultSURF.findPointList.Count > 0)
                    {
                        // ROIの1辺は、横に4つ位入る大きさで(何となくw)
                        CvSize roiSize = new CvSize(tmpImage.Width / 4, tmpImage.Width / 4);

                        List<double> matchResults = new List<double>();
                        foreach (var findPoint in resultSURF.findPointList)
                        {
                            // ROIを設定
                            tmpImage.SetROI(
                                (int)findPoint.Pt.X - roiSize.Width / 2,
                                (int)findPoint.Pt.Y - roiSize.Height / 2,
                                roiSize.Width, roiSize.Height
                            );
                            // Huモーメントによる形状マッチング [回転・スケーリング・反転に強い]
                            matchResults.Add(
                                CompareShapeMoment(tmpImage, answerImagePath, MatchShapesMethod.I1)
                            );
                            // ROIをリセット
                            tmpImage.ResetROI();
                        }

                        // 閾値以下だった場合に検出と見なす
                        if (matchResults.Min() < 0.005)
                        {
                            // カテゴリに値が無ければ確保
                            if (shapeMatchResults.ContainsKey(washTagInfo.CategoryNo) == false)
                            {
                                shapeMatchResults.Add(washTagInfo.CategoryNo, new List<double>());
                            }

                            shapeMatchResults[washTagInfo.CategoryNo].Add(matchResults.Min());
                        }
                    }
                }

                // 4)認識結果の整理
                foreach (var categoryNo in shapeMatchResults.Keys)
                {
                    var matchResult = shapeMatchResults[categoryNo];

                    var min = matchResult.Min();
                    var index = matchResult.FindIndex((x) =>
                    {
                        return x == min;
                    });

                    var id = String.Format("{0:0}{1:00}", categoryNo, index + 1);
                    var recognitionWashTag = washTagDictionary[id];

                    // 結果を格納
                    results.Add(
                        String.Format(isDebug ? "{0} : {1} ({2})" : "{0} : {1}", id, recognitionWashTag.Description, min)
                    );

                }

                // デバッグ表示
                if (isDebug)
                {
                    using (CvWindow win = new CvWindow("image", tmpImage))
                    {
                        CvWindow.WaitKey();
                    }
                }
            }

            return results.Count > 0
                ? String.Join("\n", results.ToArray())
                : "検出する事が出来ませんでした。";
        }
Exemplo n.º 10
0
        private void OnClick_マスク画像(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Multiselect = false,  // 複数選択の可否
                Filter =  // フィルタ
                "画像ファイル|*.bmp;*.gif;*.jpg;*.png|全てのファイル|*.*",
            };
            //ダイアログを表示
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                // ファイル名をタイトルバーに設定
                this.Text = dialog.SafeFileName;
                if (マスク画像 != null) マスク画像.Dispose();
                if (背景 != null) 背景.Dispose();

                マスク画像 = Cv.LoadImage(dialog.FileName, LoadMode.GrayScale);
                マスク画像.Threshold(マスク画像,254,255,ThresholdType.Binary);
                背景 = マスク画像.Clone();
                if (マスク画像 != null && 検査対象 != null)
                {
                    合成画像 = 検査対象.Clone();
                    合成画像 = 画像合成(検査対象, マスク画像);
                    背景 = 合成画像;

                }
                //評価画面.Instance.Show();
                pictureBoxIpl1.ImageIpl = 背景;

                System.Diagnostics.Debug.WriteLine("マスク画像の平均=" + マスク画像.Avg().Val0.ToString("f"));
            }
        }