用C++实现OpenCV中矩阵中的多维数据

Multi-Dimensional data in a Matrix in OpenCV with C++

本文关键字:数据 C++ 实现 OpenCV      更新时间:2023-10-16

我想在OpenCV(C++)中声明、填充和访问一个与命名空间cv兼容的多维矩阵。我在上面找不到简单易学的例子。你能帮帮我吗?

以下是NAryMatIterator文档中的一个简短示例;它展示了如何在OpenCV:中创建、填充和处理多维矩阵

void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
{
    const int histSize[] = {N, N, N};
    // make sure that the histogram has a proper size and type
    hist.create(3, histSize, CV_32F);
    // and clear it
    hist = Scalar(0);
    // the loop below assumes that the image
    // is a 8-bit 3-channel. check it.
    CV_Assert(image.type() == CV_8UC3);
    MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
                             it_end = image.end<Vec3b>();
    for( ; it != it_end; ++it )
    {
        const Vec3b& pix = *it;
        hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
    }
    minProb *= image.rows*image.cols;
    Mat plane;
    NAryMatIterator it(&hist, &plane, 1);
    double s = 0;
    // iterate through the matrix. on each iteration
    // it.planes[*] (of type Mat) will be set to the current plane.
    for(int p = 0; p < it.nplanes; p++, ++it)
    {
        threshold(it.planes[0], it.planes[0], minProb, 0, THRESH_TOZERO);
        s += sum(it.planes[0])[0];
    }
    s = 1./s;
    it = NAryMatIterator(&hist, &plane, 1);
    for(int p = 0; p < it.nplanes; p++, ++it)
        it.planes[0] *= s;
}

此外,请查看cv::compareHist函数,了解NAryMatIterator的另一个使用示例。

要创建一个大小为100x100x3的多维矩阵,使用浮点、一个通道,并将所有元素初始化为10,您可以这样写:

int size[3] = { 100, 100, 3 };
cv::Mat M(3, size, CV_32FC1, cv::Scalar(10));

要循环并输出矩阵中的元素,可以执行以下操作:

for (int i = 0; i < 100; i++)
  for (int j = 0; j < 100; j++)
    for (int k = 0; k < 3; k++) 
      std::cout << M.at<cv::Vec3f>(i,j)[k] << ", ";

然而,要注意使用多维矩阵的问题,如本文所述:如何获得多维cv::Mat的大小?(Mat或MatND)