Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Draw a frequency histogram in C++/OpenCV

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 using OpenCV in C++ based on the array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <opencv2opencv.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:

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...