在C ++ / OpenCV中绘制频率直方图

时间:2015-08-18 17:17:54

标签: c++ arrays opencv histogram

创建一个频率数组。

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

如何在C ++中使用基于数组的OpenCV绘制直方图?

1 个答案:

答案 0 :(得分:2)

OpenCV并不适合绘图。但是,对于简单的直方图,您可以为每列绘制一个矩形(最终使用交替的颜色)

这是代码:

#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;
}

结果直方图如下:

enter image description here

如果您需要从静态数组转换为vector

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

<强>更新

有关此绘图功能的更新版本,请查看my other post