Tuesday, September 19, 2017

[C#] OpenCvSharp Draw Histogram | OpenCvSharp 畫直方圖

最近我使用OpenCv做研究,發現C#在這領域蠻缺乏資源的,在找怎麼畫出直方圖時花了一些時間,所以現在來分享一下結果。
Recently I was using OpenCV to do research, found C# in this field was quite lack of resources, looking for how to draw the histogram took me some time, so now to share the results.

首先,使用nuget安裝OpenCvSharp,目前C#比較好用的OpenCv Wrapper。
First, use nuget to install OpenCvSharp, the current better OpenCv Wrapper for C#.

HistExample1


然後參考下列程式碼
Then refer to the following code

using System;
using OpenCvSharp;

namespace GetHistogramExample
{
    class Program
    {
        static void Main()
        {
            string file = "Lenna.png";
            Mat src = new Mat(file);
            Mat gray = new Mat(file, ImreadModes.GrayScale);
            Mat hist = GetHistogram(gray);
            using (new Window("src image", src))
            using (new Window("gray image", gray))
            using (new Window("hist", hist))
            {
                Cv2.WaitKey();
            }
        }

        // Draw Histogram from source image - for gray
        public static Mat GetHistogram(Mat source)
        {
            Mat hist = new Mat();
            int width = source.Cols, height = source.Rows;      // 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);

            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);
            // 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([email protected]"j:{j} P1: {j * binW},{render.Rows} P2:{(j + 1) * binW},{render.Rows - (int)hist.Get(j)}");  //for Debug
                render.Rectangle(
                    new Point(j * binW, render.Rows - (int)hist.Get(j)),
                    new Point((j + 1) * binW, render.Rows),
                    color,
                    -1);
            }
            return render;
        }
    }
}



其執行結果如下
The results are as follows
HistExample2


Hope you enjoy it.

6 comments:

  1. My boyfriend likes copying watches.replica rolex watches When you buy it back, this gorgeous replica watch is amazing. The watch design and features are very fresh and elegant. replica omega aquaterra watches The quality is relatively perfect. This replica watch is very special, good quality and very cheap

    ReplyDelete
  2. cheap walker zimmerman Jerseys for Huge Savings on Soccer Replica Clothing. cheap Soccer Jerseys & Soccer Clothing with Next Day shipping!

    ReplyDelete
  3. International Watch Company, or IWC, was first introduced to the world in 1868 when an American Engineer,replica watches sale Florentine Ariosto Jones, decided to open his own factory in Switzerland. replica IWC watches has earned its reputation as one of the world's finest manufacturers of Swiss luxury watches. IWC only manufactures automatic and manual timepieces which include features such as the chronograph and GMT dual time zone. IWC has definitely made its mark in the world of watches with its dedication to excellence in form and function. Using a range of supplies a large selection of IWC watches at the best sale prices online so buy yours today!

    ReplyDelete
  4. Louis Vuitton himself was born the son of a miller in 1821 in Anchay, a hamlet in the Jura Mountains, not far from the Swiss border. Replica bagsThe region was a poor one - serfdom had only been abolished less than 40 years previously, so Louis left to seek his fortune when he was a teenager, arriving in the French capital aged 16. This was the Paris of Victor Hugo's Les Misérables, with nearly one million inhabitants. As the composer Chopin said in a letter to a friend at the time, "Here you find the greatest luxury and the greatest filth, the greatest virtue and the greatest vice."replica Louis Vuiton bags

    ReplyDelete
  5. Montblanc MeisterstückClassique black ballpoint pen with gold accessories replica mont blanc uk is one of the most famous Montblanc fountain pens replica mont blanc donation pens and is considered one of the writing instruments. The design icon has a white snow cap insignia and has its own personal serial number, which means that the pen you own will be unique. Montblanc ballpoint pens are a must-have Montblanc ballpoint pens, popular with gift buyers, corporate customers and serious pen collectors. The smoothness of the ballpoint pen mechanism makes writing luxurious and enjoyable.

    ReplyDelete
  6. Le magasin a résolu des problèmes pour moi,pas cher air max le service est très patient, c'est une expérience de magasinage parfaite. Quand j'ai reçu les chaussures, pas cher nike air max 2011 homme je pensais que c'était une bonne copie des chaussures. J'aime cette boutique en ligne, les chaussures sont simples et élégantes. Très satisfait de cet achat.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...