繁体   English   中英

如何使用OpenCV在C ++中访问3D直方图值?

[英]How to access 3D Histogram values in C++ using OpenCV?

我正在尝试访问RGB图像的3D直方图。 但直方图矩阵返回的行数和列数等于-1。 我想迭代直方图并检查3D矩阵中的各个值。 但是,当我检查矩阵中的行数和列数时,我得到-1,如下所示。

int main( int argc, const char** argv ) {
    Mat image = imread("fl.png");
    int histSize[3] = {8, 8, 8};
    float range[2] = {0, 256};
    const float * ranges[3] = {range, range, range};
    int channels[3] = {0, 1, 2};
    Mat hist;
    calcHist(&image, 1, channels, Mat(), hist, 3, histSize, ranges);
    cout << "Hist.rows = "<< hist.rows << endl;
    cout << "Hist.cols = "<< hist.cols << endl;
    return 0;
}

OUTPUT

Hist.rows = -1
Hist.cols = -1

我犯了什么错误? 如何访问各个矩阵值。

Mat的文档:

 //! the number of rows and columns or (-1, -1) when the array has more than 2 dimensions 

但你有3个维度。

您可以使用hist.at<T>(i,j,k)访问直方图的各个值。

或者您可以使用此处文档中描述的迭代器。

    // Build with gcc main.cpp  -lopencv_highgui -lopencv_core -lopencv_imgproc
    #include <iostream>
    #include <opencv2/core/core.hpp>
    #include <opencv2/highgui.hpp>
    #include <opencv2/imgproc.hpp>

    using std::cout;
    using std::endl;
    using namespace cv; # Please, don't include whole namespaces!

    int main( int argc, const char** argv ) {
        Mat image = imread("good.jpg");
        int histSize[3] = {8, 8, 8};
        float range[2] = {0, 256};
        const float * ranges[3] = {range, range, range};
        int channels[3] = {0, 1, 2};
        Mat hist;
        calcHist(&image, 1, channels, Mat(), hist, 3, histSize, ranges);
        cout << "Hist.dims = " << hist.dims << endl;
        cout << "Value: " << hist.at<double>(0,0, 0) << endl;
        cout << "Hist.rows = "<< hist.rows << endl;
        cout << "Hist.cols = "<< hist.cols << endl;
        return 0;
    }

迭代每个值:

        for (MatConstIterator_<double> it = hist.begin<double>(); it != hist.end<double>(); it++) {
            cout << "Value: " << *it << "\n";
        }
        cout << std::flush;

使用索引迭代每个值:

        for (int i=0; i<histSize[0]; i++) {
            for (int j=0; j<histSize[1]; j++) {
                for (int k=0; k<histSize[2]; k++) {
                    cout << "Value(" << i << ", " << j << ", " << k <<"): " << hist.at<double>(i, j, k) << "\n";
                }
            }
        }
        cout << std::flush;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM