如何计算OpenCV中矩阵的直方图? [英] How to calculate histogram of a matrix in OpenCV?

查看:163
本文介绍了如何计算OpenCV中矩阵的直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由从 0到N 的整数组成的矩阵,我想要获得一个大小 N + 1 其中每个元素都有每个数字的出现次数。

I have a matrix that consists of integers from 0 to N, and I want to obtain a data matrix of size N+1 where each element has the number of occurences of each number.

所以如果输入矩阵是

0 0 0
1 1 0
0 0 2

那么我的输出应该是

// occurences of  0  1  2
hist           = [6, 2, 1]

有一个简单的C ++ OpenCV,像MATLAB中的 hist 函数?

Is there an easy (built-in) way to accomplish this in C++ OpenCV, like the hist function in MATLAB?

谢谢!

推荐答案

此代码从图像中读取所有灰度值,并导致频繁出现的值(发生的值的次数)。即

This code reads all the grayscale values from an image and results in frequent occurring values (Number of times the value as occurred). i.e

出现像素值'0'的次数,

Number of times pixel value '0' as appeared,

像素值'1'出现,...&所以一直到256.

Number of times pixel value '1' as appeared, ... & so on till 256.

#include <opencv\cv.h>
#include <highgui\highgui.hpp>
using namespace std;
using namespace cv;
    int main()
{
cv::Mat img = cv::imread("5.jpg",0);

//for(int j=0;j<img.rows;j++) 
//{
//  for (int i=0;i<img.cols;i++)
//  {
//    int a;
//  a=img.at<uchar>(j,i);
//     cout<<a<<endl; 
//  }
//}
vector<int> values_rgb;
for(int i=0; i<20; i++)
{
    for(int j=0; j<20; j++)
    {
        int value_rgb = img.at<uchar>(i,j);
        values_rgb.push_back(value_rgb);
        //cout << "(" << i << "," << j << ") : " << value_rgb <<endl;
    }
}
// Sorting of values in ascending order 
vector<int> counter_rg_values;
for(int l=0; l<256; l++)

{
    for(int k=0; k<values_rgb.size(); k++)
    {
        if(values_rgb.at(k) == l)
        {
            counter_rg_values.push_back(l);
        }
    }
}
//for(int m=0;m<counter_rg_values.size();m++)
//cout<<m<<" "<< counter_rg_values[m] <<endl;
int m=0;
for(int n=0;n<256;n++)
{
    int c=0;
    for(int q=0;q<counter_rg_values.size();q++)
    {
        if(n==counter_rg_values[q])
        {
            //int c;
        c++;
        m++;
        }
    }

    cout<<n<<"= "<< c<<endl;
}
cout<<"Total number of elements "<< m<<endl;

cv::imshow("After",img);
waitKey(0);
}

链接上述讨论 http://stackoverflow.com/a/32902450/3853072

这篇关于如何计算OpenCV中矩阵的直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆