Ejemplo n.º 1
0
        /// <summary>
        /// Creates a histogram for each of the 6 combinations of piece color (white, black, no piece) on square color (white, black), differenced with the background model.
        /// </summary>
        /// <param name="frame"></param>
        /// <returns></returns>
        private Mat[,] CreateXOnYHistograms(Mat frame)
        {
            using (var xOnYWin = new Window("X On Y"))
            {
                Mat[,] xOnYHist = new Mat[3, 2];

                var histSize = new[] { 16, 16, 16 };
                var ranges   = new[] { new Rangef(0f, 256f), new Rangef(0f, 256f), new Rangef(0f, 256f) };

                for (int pieceColor = 0; pieceColor < 3; pieceColor++)
                {
                    for (int squareColor = 0; squareColor < 2; squareColor++)
                    {
                        //Cv2.MinMaxIdx(difference, out double minVal, out double maxVal);
                        //Console.WriteLine($"min = {minVal}; max = {maxVal}");

                        Mat xOnYMask = CreateXOnYMaskForInitialPositions(frame, pieceColor, squareColor);

                        xOnYWin.ShowImage(xOnYMask);
                        Cv2.WaitKey();
                        xOnYHist[pieceColor, squareColor] = new Mat();
                        Cv2.CalcHist(
                            images: new[] { frame },
                            channels: new int[] { 0, 1, 2 },
                            mask: xOnYMask,
                            hist: xOnYHist[pieceColor, squareColor],
                            dims: 3,
                            histSize: histSize,
                            ranges: ranges);
                    }
                }
                return(xOnYHist);
            }
        }
Ejemplo n.º 2
0
        public void cuda_calcHist()
        {
            Mat  src  = Image("lenna.png", ImreadModes.Grayscale);
            Size size = src.Size();

            using (GpuMat g_src = new GpuMat(size, src.Type()))
                using (GpuMat hist = new GpuMat()) {
                    g_src.Upload(src);
                    Cuda.cuda.calcHist(g_src, hist);

                    Mat hist_gold = new Mat();

                    Mat[]     r_src    = { src };
                    int       hbins    = 256;
                    float[]   hranges  = { 0.0f, 256.0f };
                    int[]     histSize = { hbins };
                    float[][] ranges   = { hranges };
                    int[]     channels = { 0 };

                    Cv2.CalcHist(r_src, channels, new Mat(), hist_gold, 1, histSize, ranges);
                    hist_gold = hist_gold.Reshape(1, 1);
                    hist_gold.ConvertTo(hist_gold, MatType.CV_32S);

                    ImageEquals(hist_gold, hist);
                }
        }
Ejemplo n.º 3
0
        private void button5_Click(object sender, EventArgs e)
        {
            Mat    src = new Mat(fileName);
            int    Width = 260, Height = pictureBox5.Height;
            double minVal, maxVal;
            Mat    hist = new Mat();

            int[]    hdims  = { 256 };
            Rangef[] ranges = { new Rangef(0, 256), };

            src = src.CvtColor(ColorConversionCodes.BGR2GRAY);
            Cv2.EqualizeHist(src, src);
            Mat render = new Mat(new OpenCvSharp.Size(Width, Height), MatType.CV_8UC3, Scalar.All(255));

            Cv2.CalcHist(new Mat[] { src }, new int[] { 0 }, null, hist, 1, hdims, ranges);
            Scalar color = Scalar.All(2);

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            hist = hist * (maxVal != 0 ? Height / maxVal : 0.0);
            for (int j = 0; j < hdims[0]; ++j)
            {
                render.Rectangle(
                    new OpenCvSharp.Point(j * (int)((double)Width / hdims[0]), render.Rows - (int)(hist.Get <float>(j))),
                    new OpenCvSharp.Point((j + 1) * (int)((double)Width / hdims[0]), render.Rows),
                    color,
                    -1);
            }

            src = src.CvtColor(ColorConversionCodes.GRAY2BGR);
            Bitmap bp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(render);

            pictureBox5.Image = bp;
            showFilter(src, "gray equalize");
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sets handHist Mat which is nornalized histogram computed from ROI
        /// </summary>
        /// <param name="mat"></param>
        /// TODO: add multi-step calibration (front hand, back hand, fist with visible fingernails) / or take multiple frames for creatig histogram
        private void calibrate(Mat cameraOutputMat)
        {
            Debug.Log("Calibration");

            Cv2.CvtColor(cameraOutputMat, handHist, ColorConversionCodes.BGR2HSV);

            int roisCount = 0;

            Mat[] ROIs = null;

            switch (roiAreaType)
            {
            case ROIAreaType.Single:
                roisCount = 1;
                ROIs      = new Mat[roisCount];
                ROIs[0]   = handHist.GetRectSubPix(cameraOutput.targetArea.Size, cameraOutput.targetArea.Center);
                break;

            case ROIAreaType.Multi:
                roisCount = cameraOutput.subTargetAreasCount;
                ROIs      = new Mat[roisCount];
                for (int i = 0; i < cameraOutput.subTargetAreasCount; i++)
                {
                    ROIs[i] = handHist.GetRectSubPix(cameraOutput.subTargetAreas[i].Size, cameraOutput.subTargetAreas[i].Center);
                }

                break;
            }


            Cv2.CalcHist(ROIs, new[] { 0, 1 }, new Mat(), handHist, 2, new[] { 180, 255 }, new[] { new Rangef(0, 180), new Rangef(0, 255) });
            Cv2.Normalize(handHist, handHist, 0, 255, NormTypes.MinMax);

            calibrated = true;
        }
Ejemplo n.º 5
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Mat      panda    = new Mat(textBox6.Text.ToString(), ImreadModes.Grayscale); //读取为灰度图
                Mat[]    mats     = new Mat[] { panda };                                      //一张图片,初始化为panda
                Mat      hist     = new Mat();                                                //用来接收直方图
                int[]    channels = new int[] { 0 };                                          //一个通道,初始化为通道0
                int[]    histsize = new int[] { 256 };                                        //一个通道,初始化为256箱子
                Rangef[] range    = new Rangef[1];                                            //一个通道,值范围
                range[0].Start = 0.0F;                                                        //从0开始(含)
                range[0].End   = 256.0F;                                                      //到256结束(不含)
                Mat mask = new Mat();                                                         //不做掩码
                Cv2.CalcHist(mats, channels, mask, hist, 1, histsize, range);                 //计算灰度图,dim为1 1维

                Console.WriteLine(hist.Rows + "行" + hist.Cols + "列");                         //把输出的行列打印出来


                Cv2.ImShow("直方图", panda);
                Cv2.ImWrite("ZFT.jpg", panda);
                curBitmap     = (Bitmap)Image.FromFile("ZFT.jpg");
                this.pB.Image = curBitmap;
                pB.Refresh();
                this.groupBox3.Visible = false;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "信息提示"); }
        }
Ejemplo n.º 6
0
        static void drawhis(Mat src0, string windowname)
        {
            Mat[] src     = { src0 };
            Mat   dstHist = new Mat();   // 在cv中用CvHistogram *hist = cvCreateHist
            int   dims    = 1;

            Rangef[] ranges = { new Rangef(0, 256) }; // 这里需要为const类型

            int[] histsize = { 256 };                 //每个维度的直方图尺寸
            int[] channels = { 0 };
            Mat   mask     = new Mat();

            //【3】计算图像的直方图
            Cv2.CalcHist(src, channels, mask, dstHist, dims, histsize, ranges);    // cv 中是cvCalcHist
            int scale = 8;

            Mat dstImage = new Mat(histsize[0] * scale, 256, MatType.CV_8U, new Scalar(0));

            // Cv2.Normalize(dstHist, dstHist, 0, 255, NormTypes.MinMax);



            //【5】绘制出直方图
            //int hpt = saturate_cast<int>(0.9 * size);
            for (int i = 0; i < histsize[0]; i++)
            {
                float binValue = dstHist.At <float>(i); //   注意hist中是float类型
                Cv2.Rectangle(dstImage, new Point(i * scale, 255 - binValue), new Point((i + 1) * scale - 1, 255), new Scalar(255));
            }
            using (var window = new Window("直方图", WindowMode.Normal, dstImage))
            {
                Cv2.WaitKey();
            }
        }
Ejemplo n.º 7
0
        public void cuda_calcHist_mask()
        {
            Mat src  = Image("lenna.png", ImreadModes.Grayscale);
            Mat mask = new Mat(src.Size(), MatType.CV_8UC1, Scalar.White);

            mask.Rectangle(new Rect(0, 0, mask.Width / 2, mask.Height / 2), Scalar.Black, -1);
            Size size = src.Size();

            using (GpuMat g_src = new GpuMat(size, src.Type()))
                using (GpuMat hist = new GpuMat()) {
                    g_src.Upload(src);
                    GpuMat g_mask = new GpuMat();
                    g_mask.Upload(mask);

                    Cuda.cuda.calcHist(g_src, g_mask, hist);

                    Mat hist_gold = new Mat();

                    Mat[]     r_src    = { src };
                    int       hbins    = 256;
                    float[]   hranges  = { 0.0f, 256.0f };
                    int[]     histSize = { hbins };
                    float[][] ranges   = { hranges };
                    int[]     channels = { 0 };

                    Cv2.CalcHist(r_src, channels, mask, hist_gold, 1, histSize, ranges);
                    hist_gold = hist_gold.Reshape(1, 1);
                    hist_gold.ConvertTo(hist_gold, MatType.CV_32S);

                    ImageEquals(hist_gold, hist);
                }
        }
        //private void decodematrix()
        //{

        //    Image img = Image.FromFile(filepath1);
        //    Bitmap bmap1;
        //    try
        //    {
        //        bmap1 = new Bitmap(img);
        //    }
        //    catch (System.IO.IOException ioe)
        //    {
        //        MessageBox.Show(ioe.ToString());
        //        return;
        //    }
        //    if (bmap1 == null)
        //    {
        //        MessageBox.Show("Could not decode image");
        //        return;
        //    }


        //    LuminanceSource source = new RGBLuminanceSource(bmap, bmap.Width, bmap.Height);
        //    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        //    Result result;
        //    try
        //    {
        //        result = new MultiFormatReader().decode(bitmap);
        //    }
        //    catch (ReaderException re)
        //    {
        //        MessageBox.Show(re.ToString());
        //        return;
        //    }

        //    MessageBox.Show(result.Text);
        //}

        public void testhist()
        {
            Mat img = new Mat();

            img = Cv2.ImRead("d:/lena1.jpg");
            //Console.WriteLine("hist");
            //using (new Window("histimg", img)) ;
            Cv2.ImShow("hs", img);
            Cv2.WaitKey();
            Rangef[] rangefs = new Rangef[]
            {
                new Rangef(0, 256),
            };
            int[] hsize   = { 255 };
            Mat   histimg = new Mat();
            Mat   output  = new Mat();

            Mat[] mats     = new Mat[] { img };
            int[] channels = new int[] { 1 };
            Cv2.CvtColor(img, output, ColorConversionCodes.RGB2GRAY);
            Cv2.CalcHist(mats, channels, output, histimg, 1, hsize, rangefs, true, false);
            for (int i = 0; i < 256; i++)//画直方图
            {
                // Cv2.Line(HistImage, new Point(binImage.Width/256 * (i - 1), binImage.Height - Math.Round(binImage.At<float>(i - 1))), new Point(binImage.Width/256 * (i - 1), binImage.Height - Math.Round(binImage.At<float>(i))), new Scalar(255, 0, 0), 1, LineTypes.AntiAlias);

                // int len = (int)((binImage.Get<float>(i)) * output.Rows);//单个箱子的长度,
                //
                //Cv2.Line(histimg, new Point(img.Width/256*(i-1), img.Height - Math.Round(img.At<float>(i - 1))), new Point(img.Width / 256 * (i - 1), img.Height - Math.Round(img.At<float>(i))), Scalar.Black, 2);//把线画出来
            }
            // Cv2.ImShow("hist", histimg);
            //Cv2.WaitKey();
        }
Ejemplo n.º 9
0
        public void CalcHist()
        {
            using var src = new Mat(@"_data/image/mandrill.png", ImreadModes.Grayscale);

            using var hist = new Mat();
            Cv2.CalcHist(
                images: new[] { src },
                channels: new[] { 0 },
                mask: null,
                hist: hist,
                dims: 1,
                histSize: new[] { 256 },
                ranges: new[] { new Rangef(0, 256) });

            if (Debugger.IsAttached)
            {
                const int histW = 512;
                const int histH = 400;
                var       binW  = Math.Round((double)histW / 256);
                using var histImage = new Mat(histH, histW, MatType.CV_8UC3, Scalar.All(0));
                Cv2.Normalize(hist, hist, 0, histImage.Rows, NormTypes.MinMax, -1);

                for (int i = 0; i < 256; i++)
                {
                    var pt1 = new Point2d(binW * (i - 1), histH - Math.Round(hist.At <float>(i - 1)));
                    var pt2 = new Point2d(binW * (i), histH - Math.Round(hist.At <float>(i)));
                    Cv2.Line(
                        histImage, (Point)pt1, (Point)pt2,
                        Scalar.Red, 1, LineTypes.Link8);
                }

                Window.ShowImages(src, histImage);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Computes median value for GRAY input image
        /// </summary>
        /// <param name="matGray">Mat with gray image</param>
        /// <param name="max">Max channel value, 256 by default</param>
        /// <returns>Image median</returns>
        public static int Median(this Mat matGray, int max = 256)
        {
            Mat hist = new Mat();

            int[]    hdims  = { max };
            Rangef[] ranges = { new Rangef(0, max), };
            Cv2.CalcHist(
                new Mat[] { matGray },
                new int[] { 0 },
                null,
                hist,
                1,
                hdims,
                ranges);

            int median = 0, sum = 0;
            int thresh = (int)matGray.Total() / 2;

            while (sum < thresh && median < max)
            {
                sum += (int)(hist.Get <float>(median));
                median++;
            }
            return(median);
        }
Ejemplo n.º 11
0
        public Mat Test(byte[] file, string tipo)
        {
            var src = Mat.FromImageData(file, ImreadModes.Color);
            // Histogram view
            const int Width = 260, Height = 200;
            var       render = new Mat(new Size(Width, Height), MatType.CV_8UC3, Scalar.All(255));

            // Calculate histogram
            var hist = new Mat();

            int[]    hdims  = { 256 };                 // Histogram size for each dimension
            Rangef[] ranges = { new Rangef(0, 256), }; // min/max
            Cv2.CalcHist(
                new Mat[] { src },
                new int[] { 0 },
                null,
                hist,
                1,
                hdims,
                ranges);

            // Get the max value of histogram
            double minVal, maxVal;

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            var color = Scalar.All(100);

            // Scales and draws histogram
            hist = hist * (maxVal != 0 ? Height / maxVal : 0.0);

            var data = new List <Graph>();

            for (int j = 0; j < hdims[0]; ++j)
            {
                int binW = (int)((double)Width / hdims[0]);

                var x = j * binW;
                var y = render.Rows - (int)(hist.Get <float>(j));
                //using (var con = new BaseRepository())
                //    con.Execute($"INSERT INTO Valores  VALUEs ({x}, {y}, '{tipo}')");

                //    CreateTextFile($"{x} - {y}");

                render.Rectangle(
                    new Point(j * binW, render.Rows - (int)(hist.Get <float>(j))),
                    new Point((j + 1) * binW, render.Rows),
                    color, -1);
            }

            //using (new Window("Image", WindowMode.AutoSize | WindowMode.FreeRatio, src))
            //using (new Window("Histogram", WindowMode.AutoSize | WindowMode.FreeRatio, render))
            //{
            //    Cv2.WaitKey();
            //}

            return(hist);
        }
Ejemplo n.º 12
0
        private void ColorHistShow(Mat image)
        {
            Mat[]                planes;
            Mat[]                hist;
            int[]                channels = { 0 };
            int[]                size     = { 256 };
            Rangef[]             range    = { new Rangef(0.0F, 256.0F) };
            OpenCvSharp.Scalar[] color    =
                new[] {
                new OpenCvSharp.Scalar(255, 0, 0),
                new OpenCvSharp.Scalar(0, 255, 0),
                new OpenCvSharp.Scalar(0, 0, 255),
            };

            Cv2.Split(image, out planes);

            hist = new Mat[planes.Length];

            for (int i = 0; i < planes.Length; i++)
            {
                hist[i] = new Mat();
                Cv2.CalcHist(new Mat[] { planes[i] }, channels, null, OutputArray.Create(hist[i]), 1, size, range);
            }

            int hist_width = 512; int hist_height = 400;
            int bin_width = (int)Math.Round((double)hist_width / 256);

            Mat histImage = new Mat(hist_height, hist_width, MatType.CV_8UC3, new OpenCvSharp.Scalar(0, 0, 0));

            for (int i = 0; i < hist.Length; i++)
            {
                Cv2.Normalize(hist[i], hist[i], 0, histImage.Rows, NormTypes.MinMax, -1, null);
            }

            for (int i = 1; i < 256; i++)
            {
                for (int j = 0; j < color.Length; j++)
                {
                    Cv2.Line(histImage,
                             new OpenCvSharp.Point(bin_width * (i - 1), hist_height - (int)Math.Round(hist[j].At <float>(i - 1))),
                             new OpenCvSharp.Point(bin_width * (i), hist_height - (int)Math.Round(hist[j].At <float>(i))),
                             color[j], 2, LineTypes.Link8, 0);
                }
            }

            for (int i = 0; i < planes.Length; i++)
            {
                planes[i].Dispose();
            }

            for (int i = 0; i < hist.Length; i++)
            {
                hist[i].Dispose();
            }

            Cv2.NamedWindow("Color Histogram", WindowFlags.AutoSize);
            Cv2.ImShow("Color Histogram", histImage);
        }
Ejemplo n.º 13
0
        public static void Histogram(Mat img, string name)
        {
            TableLayoutPanel layoutPanel = new TableLayoutPanel
            {
                GrowStyle    = TableLayoutPanelGrowStyle.AddColumns,
                Dock         = DockStyle.Fill,
                AutoSizeMode = AutoSizeMode.GrowOnly,
                ColumnCount  = 1,
                RowCount     = 1,
            };

            //Note: OpenCV uses BGR color order
            Mat[] channels = img.Split();

            for (int i = 0; i < channels.Length; i++)
            {
                Chart chart = new Chart();
                chart.Dock = DockStyle.Fill;
                chart.Titles.Add("channel" + i.ToString());
                chart.Series.Add("series");
                chart.Series[0].ChartType = SeriesChartType.Column;
                chart.ChartAreas.Add(new ChartArea());
                DataPointCollection points = chart.Series[0].Points;

                // Calculate histogram
                Mat      hist   = new Mat();
                int[]    hdims  = { 256 };                 // Histogram size for each dimension
                Rangef[] ranges = { new Rangef(0, 256), }; // min/max
                Cv2.CalcHist(
                    new Mat[] { channels[i] },
                    new int[] { 0 },
                    null,
                    hist,
                    1,
                    hdims,
                    ranges);

                //draw data in chart
                for (int j = 0; j < hdims[0]; ++j)
                {
                    points.AddXY(j, hist.Get <float>(j));
                }

                layoutPanel.ColumnCount = i;
                layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
                layoutPanel.Controls.Add(chart, -1, -1);
            }

            Form form = new Form
            {
                Text         = name,
                Size         = new System.Drawing.Size(300 * channels.Length, 400),
                AutoSizeMode = AutoSizeMode.GrowOnly,
            };

            form.Controls.Add(layoutPanel);
            form.ShowDialog();
        }
Ejemplo n.º 14
0
        private void CalcHistogram(ref Mat src, ref Mat mask, out System.Drawing.Bitmap dst, bool usingGamma = true)
        {
            dst = null;

            Mat hsv = new Mat();

            Cv2.CvtColor(src, hsv, ColorConversionCodes.BGR2HSV);
            Mat[] planes;
            Cv2.Split(hsv, out planes);
            Cv2.ImWrite(@"C:\temp\hhist.png", planes[0]);
            Cv2.ImWrite(@"C:\temp\sHist.png", planes[1]);
            Cv2.ImWrite(@"C:\temp\vHist.png", planes[2]);

            dst = BitmapConverter.ToBitmap(planes[2]);

            Mat hist = new Mat();

            int[]    hdims  = { 180, 256 };                               // Histogram size for each dimension
            Rangef[] ranges = { new Rangef(0, 180), new Rangef(0, 256) }; // min/max
            Cv2.CalcHist(new Mat[] { hsv }, new int[] { 0, 1 }, mask, hist, 2, hdims, ranges);

            double minVal, maxVal;

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            double gamma = App.appSettings.Gamma;

            Mat  histImage = new Mat(new OpenCvSharp.Size(hist.Width, hist.Height), MatType.CV_8UC3, 0);
            byte intensity;

            for (int i = 0; i < hist.Cols; i++)
            {
                for (int j = 0; j < hist.Rows; j++)
                {
                    float value = hist.Get <float>(j, i);
                    Vec3b color = new Vec3b();
                    color.Item0 = (byte)j;
                    color.Item1 = (byte)i;
                    if (usingGamma)
                    {
                        intensity = (byte)(Math.Pow(value / maxVal, gamma) * 255.0);
                    }
                    else
                    {
                        intensity = (byte)(value / maxVal * 255);
                    }
                    color.Item2 = intensity;
                    //histImage.Set<byte>(j, i, intensity);
                    histImage.Set <Vec3b>(j, i, color);
                }
            }
            Mat histColor = new Mat();

            Cv2.CvtColor(histImage, histColor, ColorConversionCodes.HSV2BGR);
            Cv2.ImWrite(@"C:\temp\2dhist" + "_" + name + ".png", histColor);
            dst = BitmapConverter.ToBitmap(histColor);
        }
Ejemplo n.º 15
0
        public Mat CalculateHistogram(Mat imageSource)
        {
            Mat histogram = new Mat();

            int[]    histSize = { 256 };
            Rangef[] rangef   = { new Rangef(0, 256), };

            Cv2.CalcHist(new Mat[] { imageSource }, new int[] { 0 }, null, histogram, 1, histSize, rangef);
            return(histogram);
        }
        /// <summary>
        /// Calculated the histogram of an image <br/>
        ///Image processing algorithm
        /// </summary>
        /// <param name="img">input image, of type OpenCvSharp.Mat</param>
        /// <returns>output histogram image, of type OpenCvSharp.Mat</returns>
        public Mat CalculateHistogram(Mat img)
        {
            Mat histogram = new Mat();

            Cv2.CalcHist(new Mat[] { img }, new int[] { 0 }, new Mat(), histogram, 1, new int[] { TASettings.HIST_BINS_COUNT }, new Rangef[] { new Rangef(0, TASettings.HIST_BINS_COUNT) }, true, false);

            // Create a window and display historgam
            //ShowHistogram(Mat.Zeros(IPP.HIST_HEIGHT, IPP.HIST_BINS_COUNT, MatType.CV_8UC1), histogram, IPP.HIST_HEIGHT, IPP.HIST_BINS_COUNT);

            return(histogram);
        }
Ejemplo n.º 17
0
        private void CalcImageHistogram()
        {
            int histSize = 256;

            int[]    dimensions = { histSize };
            Rangef[] ranges     = { new Rangef(0, histSize) };
            Mat[]    mv;
            Bitmap   img      = new Bitmap(this.imageBox.Image);
            Mat      imageMat = BitmapConverter.ToMat(img);

            Cv2.Split(imageMat, out mv);
            if (IsGrayScale())
            {
                Mat Hist = new Mat();
                Cv2.CalcHist(new Mat[] { mv[2] }, new int[] { 0 }, null, Hist, 1, dimensions, ranges);
                Cv2.Normalize(Hist, Hist, 0, 256, NormTypes.MinMax);
                this.histChart.Series.Clear();
                this.histChart.ChartAreas[0].AxisX.Minimum = 0;
                this.histChart.ChartAreas[0].AxisY.Minimum = 0;
                this.histChart.Legends[0].Enabled          = false;
                RenderHistogram(Hist, "Яркость", Color.Black);
            }
            else
            {
                Mat GrayScaleImage = new Mat();
                Cv2.CvtColor(imageMat, GrayScaleImage, ColorConversionCodes.BGR2GRAY);
                Mat HistR    = new Mat();
                Mat HistG    = new Mat();
                Mat HistB    = new Mat();
                Mat HistGray = new Mat();

                Cv2.CalcHist(new Mat[] { mv[2] }, new int[] { 0 }, null, HistR, 1, dimensions, ranges);
                Cv2.CalcHist(new Mat[] { mv[1] }, new int[] { 0 }, null, HistG, 1, dimensions, ranges);
                Cv2.CalcHist(new Mat[] { mv[0] }, new int[] { 0 }, null, HistB, 1, dimensions, ranges);

                Mat[] gs_mv;
                Cv2.Split(GrayScaleImage, out gs_mv);
                Cv2.CalcHist(new Mat[] { gs_mv[0] }, new int[] { 0 }, null, HistGray, 1, dimensions, ranges);

                Cv2.Normalize(HistR, HistR, 0, 256, NormTypes.MinMax);
                Cv2.Normalize(HistG, HistG, 0, 256, NormTypes.MinMax);
                Cv2.Normalize(HistB, HistB, 0, 256, NormTypes.MinMax);
                Cv2.Normalize(HistB, HistGray, 0, 256, NormTypes.MinMax);

                this.histChart.Series.Clear();
                this.histChart.ChartAreas[0].AxisX.Minimum = 0;
                this.histChart.ChartAreas[0].AxisY.Minimum = 0;
                this.histChart.Legends[0].Enabled          = true;
                RenderHistogram(HistR, "Красный", Color.Red);
                RenderHistogram(HistB, "Синий", Color.Blue);
                RenderHistogram(HistG, "Зеленый", Color.Green);
                RenderHistogram(HistGray, "Яркость", Color.Black);
            }
        }
Ejemplo n.º 18
0
        public void Run()
        {
            Mat src = Cv2.ImRead(FilePath.Image.Lenna, ImreadModes.GrayScale);

            // Histogram view
            const int Width = 260, Height = 200;
            Mat       render = new Mat(new Size(Width, Height), MatType.CV_8UC3, Scalar.All(255));

            // Calculate histogram
            Mat hist = new Mat();

            int[]    hdims  = { 256 };                 // Histogram size for each dimension
            Rangef[] ranges = { new Rangef(0, 256), }; // min/max
            Cv2.CalcHist(
                new Mat[] { src },
                new int[] { 0 },
                null,
                hist,
                1,
                hdims,
                ranges);

            // Get the max value of histogram
            double minVal, maxVal;

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            Scalar color = Scalar.All(100);

            // Scales and draws histogram
            hist = hist * (maxVal != 0 ? Height / maxVal : 0.0);
            for (int j = 0; j < hdims[0]; ++j)
            {
                int binW = (int)((double)Width / hdims[0]);
                render.Rectangle(
                    new Point(j * binW, render.Rows),
                    new Point((j + 1) * binW, render.Rows - (int)(hist.Get <float>(j))),
                    color,
                    -1);


                // render.Rectangle(
                //new Point(j * binW, render.Rows),
                //new Point((j + 1) * binW, render.Rows),
                //color,
                //-1);
            }

            using (new Window("Image", WindowMode.AutoSize | WindowMode.FreeRatio, src))
                using (new Window("Histogram", WindowMode.AutoSize | WindowMode.FreeRatio, render))
                {
                    Cv2.WaitKey();
                }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// ヒストグラムの描画
        /// </summary>
        /// <param name="mat">ヒストグラムを描画するMat</param>
        public void DrawHistogram(Mat mat)
        {
            int c;

            // 画像のチャンネル数
            int channelNum = mat.Channels();

            if (channelNum > 3)
            {
                channelNum = 3;                 // alpha成分は無視する
            }
            // ヒストグラムの初期化
            RefreshHistogramArea(channelNum);

            var matChannel = new Mat[channelNum];

            // ラベル
            string[] axisName = { "B", "G", "R" };

            if (channelNum == 1)
            {
                // モノクロの場合
                axisName[0] = "Gray";
            }

            // 各チャンネルのbin数
            int[] hdims = { 256 };
            OpenCvSharp.CPlusPlus.Rangef[] ranges = { new OpenCvSharp.CPlusPlus.Rangef(0, 256), };

            var histogram = new Mat[channelNum];

            for (c = 0; c < channelNum; c++)
            {
                histogram[c] = new Mat();

                // ヒストグラムの取得
                Cv2.CalcHist(
                    new Mat[] { mat },
                    new int[] { c },
                    null,
                    histogram[c],
                    1,
                    hdims,
                    ranges
                    );

                // ヒストグラムをChartへ描画
                for (int i = 0; i < 256; i++)
                {
                    chtHistogram.Series[axisName[c]].Points.AddXY(i, histogram[c].At <float>(i, 0));
                }
            }
        }
Ejemplo n.º 20
0
        private Mat GetHist()
        {
            var images = new Mat[] { _graySrcImage };

            int[]     channels = new int[] { 0 };
            int[]     histSize = new int[] { 256 };
            float[][] ranges   = new float[][] { new float[] { 0, 256 } };
            Mat       hist     = new Mat();

            Cv2.CalcHist(images, channels, null, hist, 1, histSize, ranges);
            return(hist);
        }
Ejemplo n.º 21
0
        private static Bitmap NormalizeBitmapOpenCv(Bitmap bm)
        {
            using (var full = BitmapConverter.ToMat(bm))
                using (var part = new Mat(full, new OpenCvSharp.Rect(rt.X, rt.Y, rt.Width, rt.Height))) {
                    using (var gray = part.Clone()) {
                        gray.CvtColor(ColorConversionCodes.RGBA2GRAY);
                        Mat      hist   = new Mat();
                        int[]    hdims  = { 256 };                 // Histogram size for each dimension
                        Rangef[] ranges = { new Rangef(0, 256), }; // min/max
                        Cv2.CalcHist(new Mat[] { gray }, new int[] { 0 }, null, hist, 1, hdims, ranges);
                        // calculate cumulative distribution from the histogram
                        var     histSize    = 256;
                        float[] accumulator = new float[histSize];
                        accumulator[0] = hist.At <float>(0);
                        for (int i = 1; i < histSize; i++)
                        {
                            accumulator[i] = accumulator[i - 1] + hist.At <float>(i);
                        }

                        float max             = accumulator.Last();
                        var   clipHistPercent = 5 * (max / 100.0); //make percent as absolute
                        clipHistPercent /= 2.0;                    // left and right wings
                        // locate left cut
                        var minGray = 0;
                        while (accumulator[minGray] < clipHistPercent)
                        {
                            minGray++;
                        }

                        // locate right cut
                        var maxGray = histSize - 1;
                        while (accumulator[maxGray] >= (max - clipHistPercent))
                        {
                            maxGray--;
                        }

                        float inputRange = maxGray - minGray;

                        var alpha = (histSize - 1) / inputRange; // alpha expands current range to histsize range
                        var beta  = -minGray * alpha;            // beta shifts current range so that minGray will go to 0

                        // Apply brightness and contrast normalization
                        // convertTo operates with saurate_cast
                        using (var dest = new Mat()) {
                            gray.ConvertTo(dest, -1, alpha, beta);

                            return(BitmapConverter.ToBitmap(dest));
                        }
                    }
                }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Counts colors in the BGR image
        /// </summary>
        /// <param name="maxCount">Maximum colors to count, the lower this value is the better for performance</param>
        /// <returns>Colors count</returns>
        public static int CountUniqueColors(this Mat img, int maxCount)
        {
            var matGray = img.CvtColor(ColorConversionCodes.BGR2GRAY);

            // calculate histogram
            Mat hist = new Mat();

            int[]    hdims  = { maxCount };
            Rangef[] ranges = { new Rangef(0, 256) };
            Cv2.CalcHist(new Mat[] { matGray }, new int[] { 0 }, null, hist, 1, hdims, ranges);

            // scales and draws histogram
            return(hist.CountNonZero());
        }
Ejemplo n.º 23
0
        // Draw Histogram from source image - for gray
        private static Mat GetHistogram(Mat source)
        {
            Mat       hist = new Mat();
            int       width = source.Cols, height = source.Rows /*+500*/; // set Histogram same size as source image
            const int histogramSize = 256;                                // you can change by urself

            int[]    dimensions = { histogramSize };                      // Histogram size for each dimension
            Rangef[] ranges     = { new Rangef(0, histogramSize) };       // min/max

            Cv2.CalcHist(
                images: new[] { source },
                channels: new[] { 0 }, //The channel (dim) to be measured. In this case it is just the intensity (each array is single-channel) so we just write 0.
                mask: null,
                hist: hist,
                dims: 1, //The histogram dimensionality.
                histSize: dimensions,
                ranges: ranges);

            double minVal, maxVal;

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);

            Mat    render = new Mat(new Size(width, height), MatType.CV_8UC3, Scalar.All(255));
            Scalar color  = Scalar.All(100);

            // Scales and draws histogram
            hist = hist * (maxVal != 0 ? height / maxVal : 0.0);
            int binW = width / dimensions[0];

            for (int j = 0; j < dimensions[0]; ++j)
            {
                //Console.WriteLine($@"j:{j} P1: {j * binW},{render.Rows} P2:{(j + 1) * binW},{render.Rows - (int)hist.Get<float>(j)}");  //for Debug
                var a = (int)hist.Get <float>(j);
                render.Rectangle(
                    new Point(j * binW, render.Rows - (int)hist.Get <float>(j)),
                    new Point((j + 1) * binW, render.Rows),
                    color,
                    -1);
            }

            var b = (int)hist.Get <float>(0);

            if (b < 700)
            {
                //Console.WriteLine($"baito start:{++cnt}");
                //source.SaveImage($@"image\start\{cnt}.bmp");
            }
            return(render);
        }
Ejemplo n.º 24
0
        public Mat histogram(Mat src)
        {
            Mat hist   = new Mat();
            Mat result = Mat.Ones(new OpenCvSharp.Size(256, 300), MatType.CV_8UC1);

            Cv2.CalcHist(new Mat[] { src }, new int[] { 0 }, null, hist, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
            Cv2.Normalize(hist, hist, 0, 255, NormTypes.MinMax);

            for (int i = 0; i < hist.Rows; i++)
            {
                Cv2.Line(result, new OpenCvSharp.Point(i, 300), new OpenCvSharp.Point(i, 300 - hist.Get <float>(i)), Scalar.White);
            }

            return(result);
        }
Ejemplo n.º 25
0
        public override void RunTest()
        {
            using var src = Cv2.ImRead(ImagePath.Lenna, ImreadModes.Grayscale);

            // Histogram view
            const int Width = 260, Height = 200;

            using var render = new Mat(new Size(Width, Height), MatType.CV_8UC3, Scalar.All(255));

            // Calculate histogram
            var hist = new Mat();

            int[]    hdims  = { 256 };                 // Histogram size for each dimension
            Rangef[] ranges = { new Rangef(0, 256), }; // min/max
            Cv2.CalcHist(
                new Mat[] { src },
                new int[] { 0 },
                null,
                hist,
                1,
                hdims,
                ranges);

            // Get the max value of histogram
            Cv2.MinMaxLoc(hist, out _, out double maxVal);

            var color = Scalar.All(100);

            // Scales and draws histogram
            hist = hist * (maxVal != 0 ? Height / maxVal : 0.0);
            for (int j = 0; j < hdims[0]; ++j)
            {
                int binW = (int)((double)Width / hdims[0]);
                render.Rectangle(
                    new Point(j * binW, render.Rows - (int)hist.Get <float>(j)),
                    new Point((j + 1) * binW, render.Rows),
                    color,
                    -1);
            }

            using (new Window("Image", src, WindowFlags.AutoSize | WindowFlags.FreeRatio))
                using (new Window("Histogram", render, WindowFlags.AutoSize | WindowFlags.FreeRatio))
                {
                    Cv2.WaitKey();
                }
        }
Ejemplo n.º 26
0
        public static Mat GetHistogram4Hue(Mat source)
        {
            Mat       hist = new Mat();
            int       width = source.Cols / 2, height = source.Rows / 2; // set Histogram same size as source image
            const int histogramSize = 180;                               // you can change by urself

            int[]    dimensions = { histogramSize };                     // Histogram size for each dimension
            Rangef[] ranges     = { new Rangef(0, histogramSize) };      // min/max

            Cv2.CalcHist(
                images: new[] { source },
                channels: new[] { 0 }, //The channel (dim) to be measured. In this case it is just the intensity (each array is single-channel) so we just write 0.
                mask: null,
                hist: hist,
                dims: 1, //The histogram dimensionality.
                histSize: dimensions,
                ranges: ranges);

            Mat    render = new Mat(new Size(width, height), MatType.CV_8UC3, Scalar.All(255));
            double minVal, maxVal;

            Cv2.MinMaxLoc(hist, out minVal, out maxVal);
            //Scalar color = Scalar.All(100);
            //Scalar color = new Scalar(0, 0, 255);
            // Scales and draws histogram
            hist = hist * (maxVal != 0 ? height / maxVal : 0.0);
            int binW = width / dimensions[0];

            for (int j = 0; j < dimensions[0]; ++j)
            {
                Mat rgb = new Mat();;
                Mat hsv = new Mat(1, 1, MatType.CV_8UC3, new Scalar(j / 2, 255, 255));
                Cv2.CvtColor(hsv, rgb, ColorConversionCodes.HSV2BGR);
                Scalar color = new Scalar((int)rgb.Get <Vec3b>(0, 0)[0], (int)rgb.Get <Vec3b>(0, 0)[1], (int)rgb.Get <Vec3b>(0, 0)[2]);
                Console.WriteLine($"color:{color}");

                //Console.WriteLine($@"j:{j} P1: {j * binW},{render.Rows} P2:{(j + 1) * binW},{render.Rows - (int)hist.Get<float>(j)}");  //for Debug
                render.Rectangle(
                    new Point(j * binW, render.Rows - (int)hist.Get <float>(j)),
                    new Point((j + 1) * binW, render.Rows),
                    color,
                    -1);
            }
            return(render);
        }
Ejemplo n.º 27
0
        public double CompareImageByHist(Mat img, Mat refImg, bool showImage = false)
        {
            Mat imgHsv    = new Mat();
            Mat refImgHsv = new Mat();

            Cv2.CvtColor(img, imgHsv, ColorConversionCodes.RGB2HSV);
            Cv2.CvtColor(refImg, refImgHsv, ColorConversionCodes.RGB2HSV);

            Mat[] imgHsvs    = Cv2.Split(imgHsv);
            Mat[] refImgHsvs = Cv2.Split(refImgHsv);

            int bin1 = 50;
            int bin2 = 60;

            int[] bins = { bin1, bin2 };

            int[] channels = { 0, 1 };

            Rangef[] ranges = new Rangef[]
            {
                new Rangef(0, 180),
                new Rangef(0, 256)
            };

            Mat imgHist    = new Mat(img.Size(), MatType.CV_32FC2);
            Mat refImgHist = new Mat(img.Size(), MatType.CV_32FC2);

            Cv2.CalcHist(imgHsvs, channels, new Mat(), imgHist, 2, bins, ranges, true, false);
            Cv2.Normalize(imgHist, imgHist, 1, 0, NormTypes.MinMax, -1, null);

            Cv2.CalcHist(refImgHsvs, channels, new Mat(), refImgHist, 2, bins, ranges, true, false);
            Cv2.Normalize(refImgHist, refImgHist, 1, 0, NormTypes.MinMax, -1, null);

            double ratio = Cv2.CompareHist(imgHist, refImgHist, HistCompMethods.KLDiv);

            if (showImage == true)
            {
                Mat img1 = img.Clone();
                Cv2.PutText(img1, ratio.ToString(), new Point(50, 50), HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0), 2, LineTypes.AntiAlias);
                Cv2.ImShow("CompareHistTestVSRef", img1);
                Cv2.WaitKey();
                Cv2.DestroyWindow("CompareHistTestVSRef");
            }
            return(ratio);
        }
Ejemplo n.º 28
0
        public int[] AnalyseRect(Rect rect)
        {
            var outerColor = _image.At <Vec3b>(rect.Y, rect.X - 2);

            var middleX     = (int)Math.Round(rect.X + rect.Width / 2.0);
            var middleY     = (int)Math.Round(rect.Y + rect.Height / 2.0);
            var innerLeft   = _image.At <Vec3b>(middleY, rect.X + 3);
            var innerRight  = _image.At <Vec3b>(middleY, rect.X + rect.Width - 3);
            var innerTop    = _image.At <Vec3b>(rect.Y + 3, middleX);
            var innerBottom = _image.At <Vec3b>(rect.Y + rect.Height - 3, middleX);

            // check if rect contains other color than in outer area
            if (outerColor != innerLeft || outerColor != innerRight || outerColor != innerTop || outerColor != innerBottom)
            {
                // calculate histogram
                var roi   = new Mat(_image, rect);
                var split = roi.Split();
                var hist  = new[] { new Mat(), new Mat(), new Mat() };

                for (var i = 0; i < 3; i++)
                {
                    Cv2.CalcHist(new[] { split[i] }, new[] { 0 }, null, hist[i], 1, new[] { 256 }, new[] { new Rangef(0, 256) });
                }

                // find most common value
                var mostCommon = new int[3];
                for (var j = 0; j < 3; j++)
                {
                    // detect min max values and it's positions
                    Cv2.MinMaxLoc(hist[j], out _, out var max, out _, out var maxLoc);
                    mostCommon[j] = maxLoc.Y;
                }

                // check if most common color is not outer color
                if (mostCommon[0] == outerColor.Item0 && mostCommon[1] == outerColor.Item1 && mostCommon[2] == outerColor.Item2)
                {
                    return(null);
                }

                return(new[] { mostCommon[2], mostCommon[1], mostCommon[0] });
            }

            return(new int[] { outerColor.Item2, outerColor.Item1, outerColor.Item0 });
        }
Ejemplo n.º 29
0
        private float[] GetHistogram(Mat matSrc, int channel)
        {
            var        images = new Mat[] { matSrc };
            var        channels = new int[] { channel };
            InputArray mask = null;
            Mat        hist = new Mat();
            int        dims = 1;
            int        width = matSrc.Cols, height = matSrc.Rows;
            const int  histogramSize = 256;

            int[]    histSize = { histogramSize };
            Rangef[] ranges   = { new Rangef(0, histogramSize) };

            Cv2.CalcHist(images, channels, mask, hist, dims, histSize, ranges);
            var histo = new float[256];

            Marshal.Copy(hist.Data, histo, 0, 256);
            return(histo);
        }
Ejemplo n.º 30
0
        private static void calculateHistogram2(Window histogramWindow, Mat src, Mat modifiedSrc)
        {
            const int histogramSize = 64;//from 0 to 63

            using (var histogram = new Mat())
            {
                int[]    dimensions = { histogramSize };                // Histogram size for each dimension
                Rangef[] ranges     = { new Rangef(0, histogramSize) }; // min/max
                Cv2.CalcHist(
                    images: new[] { modifiedSrc },
                    channels: new[] { 0 }, //The channel (dim) to be measured. In this case it is just the intensity (each array is single-channel) so we just write 0.
                    mask: null,
                    hist: histogram,
                    dims: 1,
                    histSize: dimensions,
                    ranges: ranges);

                // Get the max value of histogram
                double minVal, maxVal;
                Cv2.MinMaxLoc(histogram, out minVal, out maxVal);

                var color = Scalar.All(100);

                // Scales and draws histogram
                var scaledHistogram = (Mat)(histogram * (maxVal != 0 ? src.Rows / maxVal : 0.0));

                using (var histogramImage = new Mat(new Size(src.Cols, src.Rows), MatType.CV_8UC3, Scalar.All(255)))
                {
                    var binW = (int)((double)src.Cols / histogramSize);
                    for (var j = 0; j < histogramSize; j++)
                    {
                        histogramImage.Rectangle(
                            new Point(j * binW, histogramImage.Rows),
                            new Point((j + 1) * binW, histogramImage.Rows - (int)(scaledHistogram.Get <float>(j))),
                            color,
                            -1);
                    }

                    histogramWindow.Image = histogramImage;
                }
            }
        }