Draw a frequency histogram in C++/OpenCV

后端 未结 1 1616
别那么骄傲
别那么骄傲 2020-12-20 06:59

An array of frequency is created.

int arr[10];
arr[0] = 24;
arr[1] = 28;
arr[2] = 23;
arr[3] = 29;
//and so on

How do i draw a histogram us

相关标签:
1条回答
  • 2020-12-20 07:57

    OpenCV is not really suited for plotting. However, for simple histograms, you can draw a rectangle for each column (eventually with alternating colors)

    This is the code:

    #include <opencv2\opencv.hpp>
    #include <algorithm>
    using namespace std;
    using namespace cv;
    
    
    void drawHist(const vector<int>& data, Mat3b& dst, int binSize = 3, int height = 0)
    {
        int max_value = *max_element(data.begin(), data.end());
        int rows = 0;
        int cols = 0;
        if (height == 0) {
            rows = max_value + 10;
        } else { 
            rows = max(max_value + 10, height);
        }
    
        cols = data.size() * binSize;
    
        dst = Mat3b(rows, cols, Vec3b(0,0,0));
    
        for (int i = 0; i < data.size(); ++i)
        {
            int h = rows - data[i];
            rectangle(dst, Point(i*binSize, h), Point((i + 1)*binSize-1, rows), (i%2) ? Scalar(0, 100, 255) : Scalar(0, 0, 255), CV_FILLED);
        }
    
    }
    
    int main()
    {
        vector<int> hist = { 10, 20, 12, 23, 25, 45, 6 };
    
        Mat3b image;
        drawHist(hist, image);
    
        imshow("Histogram", image);
        waitKey();
    
        return 0;
    }
    

    The resulting histogram would be like:

    If you need to convert from static array to vector:

    #define N 3
    int arr[N] = {4, 3, 9};
    vector<int> hist(arr, arr + N);
    

    Update

    For an updated version of this drawing function, have a look at my other post

    0 讨论(0)
提交回复
热议问题