gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:28:08 26 4
gpt4 key购买 nike

我正在尝试访问 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;
}

输出

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) 访问直方图的各个值.

或者您可以使用文档中描述的迭代器 here .

代码

    // 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;

关于c++ - 如何使用 OpenCV 在 C++ 中访问 3D 直方图值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26421806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com