예제 #1
0
        private void поискПоКадруToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Bitmap             bmp     = (Bitmap)pictureBox1.Image;
                Image <Gray, Byte> myImage = new Image <Gray, Byte>(bmp);
                DenseHistogram     hist    = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
                hist.Calculate <Byte>(new Image <Gray, byte>[] { myImage }, true, null);

                var imList = DBOPS.GetSearchImagesList();
                for (int i = 0; i < imList.Count; i++)
                {
                    Bitmap             myBmp    = (Bitmap)Image.FromFile(System.IO.Directory.GetCurrentDirectory() + imList[i].path);
                    Image <Gray, Byte> myImage2 = new Image <Gray, Byte>(myBmp);
                    DenseHistogram     hist2    = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
                    hist2.Calculate <Byte>(new Image <Gray, byte>[] { myImage2 }, true, null);
                    var a = CvInvoke.CompareHist(hist, hist2, Emgu.CV.CvEnum.HistogramCompMethod.Chisqr);
                    imList[i].distance = a;
                }
                var sortedimgs = imList.OrderBy(a => a.distance).ToList();
                List <SearchImageListTable> top10img = new List <SearchImageListTable>();
                for (int i = 0; i < 10; i++)
                {
                    top10img.Add(sortedimgs[i]);
                }
                var myForm = new Top10Form(top10img);
                //myForm.FormClosed += new FormClosedEventHandler(myForm_FormClosed);
                myForm.Show();
            }
            catch (Exception ex) { }
        }
예제 #2
0
        public void Compare(Mat mat1, Mat mat2)
        {
            CvInvoke.Resize(mat2, mat2, mat1.Size);
            CvInvoke.CvtColor(mat1, mat1, ColorConversion.Bgr2Gray);
            CvInvoke.CvtColor(mat2, mat2, ColorConversion.Bgr2Gray);

            //直方图尺寸设置
            //一个灰度值可以设定一个bins,256个灰度值就可以设定256个bins
            //对应HSV格式,构建二维直方图
            //每个维度的直方图灰度值划分为256块进行统计,也可以使用其他值
            int hBins = 256, sBins = 256;

            int[] histSize = { hBins };
            //H:0~180, S:0~255,V:0~255
            //H色调取值范围
            float[] hRanges = { 0, 180 };
            //S饱和度取值范围
            float[]   sRanges = { 180 };
            float[][] ranges = { new float[] { 0, 40 }, new float[] { 40, 80 }, new float[] { 40, 255 } };
            int[]     channels = { 0 };//二维直方图
            Mat       hist1 = new Mat(), hist2 = new Mat();

            CvInvoke.CalcHist(mat1, channels, new Mat(), hist1, histSize, sRanges, false);
            CvInvoke.CalcHist(mat2, channels, new Mat(), hist2, histSize, sRanges, false);
            var result = CvInvoke.CompareHist(hist1, hist2, HistogramCompMethod.Correl);

            Console.WriteLine($"result:{result}");
        }
        private bool CompareHistogram(string imgOne, string imgTwo)
        {
            // based on the outdated code from: http://www.emgu.com/forum/viewtopic.php?t=2956
            var imageOne = new Image <Rgb, byte>(imgOne);
            var imageTwo = new Image <Rgb, byte>(imgTwo);

            // separate image one by channel
            DenseHistogram     imageOneBlueHist  = new DenseHistogram(64, new RangeF(0, 64));
            DenseHistogram     imageOneGreenHist = new DenseHistogram(64, new RangeF(0, 64));
            DenseHistogram     imageOneRedHist   = new DenseHistogram(64, new RangeF(0, 64));
            Image <Gray, Byte> imageOneBlue      = imageOne[2];
            Image <Gray, Byte> imageOneGreen     = imageOne[1];
            Image <Gray, Byte> imageOneRed       = imageOne[0];

            // calculate histogram of image one
            imageOneBlueHist.Calculate(new Image <Gray, Byte>[] { imageOneBlue }, true, null);
            imageOneGreenHist.Calculate(new Image <Gray, Byte>[] { imageOneGreen }, true, null);
            imageOneRedHist.Calculate(new Image <Gray, Byte>[] { imageOneRed }, true, null);

            // separate image two by channels
            DenseHistogram     imageTwoBlueHist  = new DenseHistogram(64, new RangeF(0, 64));
            DenseHistogram     imageTwoGreenHist = new DenseHistogram(64, new RangeF(0, 64));
            DenseHistogram     imageTwoRedHist   = new DenseHistogram(64, new RangeF(0, 64));
            Image <Gray, Byte> imageTwoBlue      = imageTwo[2];
            Image <Gray, Byte> imageTwoGreen     = imageTwo[1];
            Image <Gray, Byte> imageTwoRed       = imageTwo[0];

            // calculate histogram of image two
            imageTwoBlueHist.Calculate(new Image <Gray, Byte>[] { imageTwoBlue }, true, null);
            imageTwoGreenHist.Calculate(new Image <Gray, Byte>[] { imageTwoGreen }, true, null);
            imageTwoRedHist.Calculate(new Image <Gray, Byte>[] { imageTwoRed }, true, null);

            // comparing histograms
            double blueResult
                = CvInvoke.CompareHist(
                      imageTwoBlueHist, imageOneBlueHist, Emgu.CV.CvEnum.HistogramCompMethod.Correl);
            double greenResult
                = CvInvoke.CompareHist(
                      imageTwoGreenHist, imageOneGreenHist, Emgu.CV.CvEnum.HistogramCompMethod.Correl);
            double redResult
                = CvInvoke.CompareHist(
                      imageTwoRedHist, imageOneRedHist, Emgu.CV.CvEnum.HistogramCompMethod.Correl);

            // judge the comparison result
            if ((blueResult * greenResult * redResult) >= HISTOGRAM_SIMILARITY)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #4
0
        public static double MatchHistograms(List <Mat> hist1, List <Mat> hist2)
        {
            double distance = 0;

            for (int i = 0; i < hist1.Count; i++)
            {
                double tmp = CvInvoke.CompareHist(hist1[i], hist2[i], HistogramCompMethod.ChisqrAlt);
                distance += tmp;
            }

            return(distance);
        }
        private double CheckSimilarity(ref Mat refStateImg)
        {
            Mat tempImg = CaptureMatWindow();

            double compareRatio = CvInvoke.CompareHist(refStateImg, tempImg, Emgu.CV.CvEnum.HistogramCompMethod.Chisqr);

            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                ((MainWindow)Application.Current.MainWindow).img_reference.Source = BitmapSourceExtension.ToBitmapSource(tempImg);
                ((MainWindow)Application.Current.MainWindow).btn_start.Content    = Convert.ToString(Convert.ToInt32(compareRatio));
            }));

            return(compareRatio);
        }
예제 #6
0
        private void button5_Click(object sender, EventArgs e)
        {
            //在比较直方图时,最佳操作是在HSV空间中操作,所以需要将BGR空间转换为HSV空间
            Mat srcHsvImage     = new Mat(CvInvoke.cvGetSize(src1), DepthType.Cv8U, 3);
            Mat compareHsvImage = new Mat(CvInvoke.cvGetSize(src2), DepthType.Cv8U, 3);

            CvInvoke.CvtColor(src1, srcHsvImage, ColorConversion.Bgr2Hsv);
            CvInvoke.CvtColor(src2, compareHsvImage, ColorConversion.Bgr2Hsv);

            //采用H-S直方图进行处理
            //首先得配置直方图的参数
            Mat srcHist  = new Mat(CvInvoke.cvGetSize(src1), DepthType.Cv8U, 3);
            Mat compHist = new Mat(CvInvoke.cvGetSize(src2), DepthType.Cv8U, 3);

            //H、S通道
            int[] channels = new int[2] {
                0, 1
            };
            int[] histSize = new int[2] {
                30, 32
            };
            float[] Ranges = new float[2] {
                0, 180
            };

            //进行原图直方图的计算
            CvInvoke.CalcHist(srcHsvImage, channels, null, srcHist, histSize, Ranges, true);
            //对需要比较的图进行直方图的计算
            CvInvoke.CalcHist(compareHsvImage, channels, null, compHist, histSize, Ranges, true);

            //注意:这里需要对两个直方图进行归一化操作
            CvInvoke.Normalize(srcHist, srcHist, 1, 0, NormType.MinMax);
            CvInvoke.Normalize(compHist, compHist, 1, 0, NormType.MinMax);

            //对得到的直方图对比
            //相关:CV_COMP_CORREL
            //卡方:CV_COMP_CHISQR
            //直方图相交:CV_COMP_INTERSECT
            //Bhattacharyya距离:CV_COMP_BHATTACHARYYA
            double g_dCompareRecult = CvInvoke.CompareHist(srcHist, compHist, his[comboBox1.SelectedIndex]);

            richTextBox1.Text = "方法 " + comboBox1.SelectedIndex + ":两幅图像比较的结果为:" + g_dCompareRecult + "\r\n";
        }
예제 #7
0
        public static double CompareHistograms(Mat img, Mat img2)
        {
            using (Mat hist = new Mat())
                using (Mat hist2 = new Mat())
                    using (VectorOfMat vm = new VectorOfMat())
                        using (VectorOfMat vm2 = new VectorOfMat()) {
                            vm.Push(img);
                            vm2.Push(img2);
                            var channels = new int[] { 0 };
                            var histSize = new int[] { 256 };
                            var ranges   = new float[] { 0, 256, };
                            CvInvoke.CalcHist(vm, channels, null, hist, histSize, ranges, false);
                            CvInvoke.CalcHist(vm2, channels, null, hist2, histSize, ranges, false);

                            //CvInvoke.Normalize(hist, hist, 0, 255, NormType.MinMax);
                            //CvInvoke.Normalize(hist2, hist2, 0, 255, NormType.MinMax);

                            //double res = CvInvoke.CompareHist(hist, hist2, HistogramCompMethod.Bhattacharyya);
                            //Debug.Log("Cards in Stock: " + (res > 0.5));

                            return(CvInvoke.CompareHist(hist, hist2, HistogramCompMethod.Correl));
                        }
        }
예제 #8
0
        public double calculateDifference()//简化代码量,直接默认输入图像都是BGR三通道彩色图像
        {
            DenseHistogram[] histogramOfBaseImage  = new DenseHistogram[3];
            DenseHistogram[] histogramOfInputImage = new DenseHistogram[3];
            for (int i = 0; i < 3; i++)
            {
                histogramOfBaseImage[i] = new DenseHistogram(nBins, new RangeF(0f, 255.1f));
                histogramOfBaseImage[i].Calculate <byte>(new Image <Gray, byte>[] { baseImg.ToImage <Bgr, byte>().Split()[i] }, false, null);
                histogramOfInputImage[i] = new DenseHistogram(nBins, new RangeF(0f, 255.1f));
                histogramOfInputImage[i].Calculate <byte>(new Image <Gray, byte>[] { inputImg.ToImage <Bgr, byte>().Split()[i] }, false, null);
            }
            Image <Bgr, float> histOfBaseImg  = new Image <Bgr, float>(nBins, 1);
            Image <Bgr, float> histOfInputImg = new Image <Bgr, float>(nBins, 1);

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < nBins; j++)
                {
                    histOfBaseImg.Data[0, j, i]  = (float)histogramOfBaseImage[i].GetBinValues()[j];
                    histOfInputImg.Data[0, j, i] = (float)histogramOfInputImage[i].GetBinValues()[j];
                }
            }
            return(CvInvoke.CompareHist(histOfBaseImg, histOfInputImg, HistogramCompMethod.Bhattacharyya));//也可以不用巴氏系数,采用其他比较方法
        }
예제 #9
0
        public void Detection()
        {
            try
            {
                check = comp1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    capturedImg = new Image <Gray, byte>(faceDetected);
                    DBImg       = new Image <Gray, byte>((dt.Rows[i].ItemArray[0]).ToString());

                    hist1 = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
                    hist2 = new DenseHistogram(256, new RangeF(0.0f, 255.0f));

                    hist1.Calculate(new Image <Gray, byte>[] { capturedImg }, false, null);
                    hist2.Calculate(new Image <Gray, byte>[] { DBImg }, false, null);

                    mat1 = new Mat();
                    hist1.CopyTo(mat1);
                    mat2 = new Mat();
                    hist2.CopyTo(mat2);


                    comp1 = CvInvoke.CompareHist(mat1, mat2, Emgu.CV.CvEnum.HistogramCompMethod.Bhattacharyya);
                    if (comp1 > check)
                    {
                        check = comp1;
                        index = i;
                    }
                }
                MessageBox.Show(check + " " + index.ToString());
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
예제 #10
0
 public double CompareTo(PageMetric other)
 {
     return(CvInvoke.CompareHist(this.histogram, other.histogram, HistogramCompMethod.Chisqr));
 }
예제 #11
0
        public string Predict(Matrix <float> data, out Dictionary <string, float> probabilities, int[] best = null)
        {
            float response = -1;

            probabilities = new Dictionary <string, float>();

            if (type == ClassifierType.SVM)
            {
                if (svm == null)
                {
                    if (nameForID.Count > 0)
                    {
                        return(nameForID[0]);
                    }
                    else
                    {
                        return("null");
                    }
                }

                if (nameForID.Count == 1)
                {
                    response = 0;
                }
                else
                {
                    int      numFeatures = Math.Max(data.Cols, 2);
                    double[] input       = new double[numFeatures];
                    for (int i = 0; i < numFeatures; i++)
                    {
                        input[i] = data[0, Math.Min(data.Cols - 1, i)];
                    }
                    double[] responses = new double[nameForID.Count];
                    response = svm.Compute(input, out responses);
                    for (int i = 0; i < responses.Length; i++)
                    {
                        probabilities.Add(nameForID[i], (float)responses[i]);
                    }
                }
            }
            else if (type == ClassifierType.NeuralNet)
            {
                double[] input = new double[data.Cols];
                for (int i = 0; i < data.Cols; i++)
                {
                    input[i] = data[0, i];
                }
                double[] fusion = network.Compute(input);
                int      prediction; fusion.Max(out prediction);
                response = prediction;
            }
            else if (type == ClassifierType.KMeans)
            {
                double[] dataRow = new double[data.Cols];
                for (int i = 0; i < dataRow.Length; i++)
                {
                    dataRow[i] = data[0, i];
                }
                if (kmeans == null)
                {
                    return("null");
                }
                List <Tuple <double, int> > clusterDistances = new List <Tuple <double, int> >();
                for (int i = 0; i < kmeans.Clusters.Count; i++)
                {
                    double dist = Utils.DistL2Sqr(kmeans.Clusters[i].Mean, dataRow);
                    clusterDistances.Add(new Tuple <double, int>(dist, i));
                }
                clusterDistances.Sort((Tuple <double, int> a, Tuple <double, int> b) => { return(a.Item1.CompareTo(b.Item1)); });
                int mostInstances = 0;
                int totalCount    = 0;
                foreach (int classLabel in clusterClasses[clusterDistances[0].Item2].Keys)
                {
                    int instances = clusterClasses[clusterDistances[0].Item2][classLabel];
                    totalCount += instances;
                    if (instances > mostInstances)
                    {
                        mostInstances = instances;
                        response      = classLabel;
                    }
                }
            }
            else
            {
                if (trainData == null)
                {
                    return("error: no training data");
                }

                List <Tuple <double, int, float> > results = new List <Tuple <double, int, float> >();
                for (int i = 0; i < trainData.Rows; i++)
                {
                    double dist = CvInvoke.CompareHist(trainData.GetRow(i), data, HistogramCompMethod.Chisqr);
                    results.Add(new Tuple <double, int, float>(dist, i, trainLabels[i, 0]));
                }
                results.Sort((Tuple <double, int, float> a, Tuple <double, int, float> b) => { return(a.Item1.CompareTo(b.Item1)); });
                response = results[0].Item3;
                if (best != null)
                {
                    int n = Math.Min(results.Count, best.Length);
                    for (int i = 0; i < n; i++)
                    {
                        best[i] = results[i].Item2;
                    }
                }
            }

            int    classID   = (int)Math.Round(response);
            string className = (classID >= 0 && classID < nameForID.Count) ? nameForID[classID] : "no_match";

            return(className);
        }
예제 #12
0
        public void Detection()
        {
            try
            {
                check = comp1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    capturedImg = new Image <Gray, byte>(pbDetectedFace.Image.Bitmap);
                    DBImg       = new Image <Gray, byte>((dt.Rows[i].ItemArray[0]).ToString());

                    hist1 = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
                    hist2 = new DenseHistogram(256, new RangeF(0.0f, 255.0f));

                    hist1.Calculate(new Image <Gray, byte>[] { capturedImg }, false, null);
                    hist2.Calculate(new Image <Gray, byte>[] { DBImg }, false, null);

                    mat1 = new Mat();
                    hist1.CopyTo(mat1);
                    mat2 = new Mat();
                    hist2.CopyTo(mat2);

                    //float[] histFloat = new float[256];
                    //hist1.CopyTo(histFloat);

                    //float[] hist2Float = new float[256];
                    //hist2.CopyTo(hist2Float);

                    //double count1 = 0, count2 = 0;
                    //for (int j = 0; j < 256; j++)
                    //{
                    //    count1 += histFloat[j];
                    //    count2 += hist2Float[j];
                    //}

                    //unsafe
                    //{
                    //    fixed (char* ch = (dt.Rows[i].ItemArray[0]).ToString().ToCharArray())
                    //    {
                    //        fixed (char* ch2 = (dt.Rows[i].ItemArray[0]).ToString().ToCharArray())
                    //        {
                    //            OpenCVWrapper.OpencvWrapperClass obj = new OpencvWrapperClass();
                    //            sbyte* pic1 = (sbyte*)ch2;
                    //            sbyte* pic2 = (sbyte*)ch;
                    //            comp1=obj.CompareHistogram(pic1, pic2);
                    //        }
                    //    }
                    //}

                    comp1 = CvInvoke.CompareHist(mat1, mat2, Emgu.CV.CvEnum.HistogramCompMethod.Correl);
                    if (comp1 > check && comp1 < 0.40 && comp1 > 0.221)
                    {
                        check = comp1;
                        index = i;
                    }
                }
                MessageBox.Show(check + " " + index.ToString());
            }
            catch (IndexOutOfRangeException index)
            {
                MessageBox.Show(index.Message);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }
예제 #13
0
파일: Form1.cs 프로젝트: xiaodelea/Emgucv
        private void compareToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (pictureBox1.Image == null)
                {
                    return;
                }

                var img = new Bitmap(pictureBox1.Image)
                          .ToImage <Gray, byte>();

                Image <Gray, byte> img1   = null;
                OpenFileDialog     dialog = new OpenFileDialog();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    img1 = new Image <Gray, byte>(dialog.FileName);
                }

                Mat hist  = new Mat();
                Mat hist1 = new Mat();

                float[] ranges   = new float[] { 0, 256 };
                int[]   channel  = { 0 };
                int[]   histSize = { 256 };

                VectorOfMat ms = new VectorOfMat();
                ms.Push(img);

                VectorOfMat ms1 = new VectorOfMat();
                ms1.Push(img1);


                CvInvoke.CalcHist(ms, channel, null, hist, histSize, ranges, false);
                CvInvoke.CalcHist(ms1, channel, null, hist1, histSize, ranges, false);

                CvInvoke.Normalize(hist, hist);
                CvInvoke.Normalize(hist1, hist1);

                HistogramViewer viewer = new HistogramViewer();
                viewer.Text     = "Image Histogram";
                viewer.ShowIcon = false;
                viewer.HistogramCtrl.AddHistogram("Image1 Histogram", Color.Blue, hist, 256, ranges);
                viewer.HistogramCtrl.Refresh();
                viewer.Show();

                HistogramViewer viewer1 = new HistogramViewer();
                viewer1.Text     = "Image Histogram";
                viewer1.ShowIcon = false;
                viewer1.HistogramCtrl.AddHistogram("Image2 Histogram", Color.Blue, hist1, 256, ranges);
                viewer1.HistogramCtrl.Refresh();
                viewer1.Show();


                var result1 = CvInvoke.CompareHist(hist, hist, Emgu.CV.CvEnum.HistogramCompMethod.Correl);
                var result2 = CvInvoke.CompareHist(hist1, hist1, Emgu.CV.CvEnum.HistogramCompMethod.Correl);
                var result3 = CvInvoke.CompareHist(hist, hist1, Emgu.CV.CvEnum.HistogramCompMethod.Correl);

                lblBGR.Text = "Hist vs Hist = " + result1.ToString() + "\n" +
                              "Hist1 vs Hist1 = " + result2.ToString() + "\n" +
                              "Hist vs Hist1 = " + result3.ToString() + "\n";

                //pictureBox1.Image = CreateGraph(hist).GetImage();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }