简体   繁体   中英

C++ Opencv: Try to print Mat value, but get empty prints

The full source code is shown as follows:

#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char const *argv[])
{
    int n_Channel = 3;
    Mat M(Size(100, 200), CV_32FC(n_Channel));

    cout << M.rows << "," << M.cols << "," << M.channels() << endl;
    for (int i = 0; i < n_Channel; ++i)
    {
        M.at<Vec3b>(4,3)[i] = i+1;
    }
    for (int i = 0; i < n_Channel; ++i)
    {
        cout << "i=" << i << ", " << M.at<Vec3b>(4,3) << endl;
        cout << "i=" << i << ", |" << M.at<Vec3b>(4,3)[i] << "|" << endl;
    }
    return 0;
}

In the last of the print, I expect to see printed lines like "i=0, |2|". However, I get "i=0, ||", with nothing enclosed in the pair of "|". What's wrong with my code?

The complete printed messages are shown as follows:

200,100,3
i=0, [1, 2, 3]
i=0, ||
i=1, [1, 2, 3]
i=1, ||
i=2, [1, 2, 3]
i=2, ||

Thank you all for helping me!

Miki's comment is correct but here is an explanation why the mentioned error occurred:

While initializing Mat M by:

Mat M(Size(100, 200), CV_32FC(n_Channel));

The Matrix type of M is set to 32 bit and each pixel in the 3 channelled Mat M holds float value ranging from 0 to 1.0. Now to print the values of the pixels in Mat M it is necessary to use correct specifier , in case of Mat M , it should be Vec3f , that is Vector with 3 float entries instead of Vec3b , that is Vector with 3 byte entries(would have been suitable for CV_8UC3 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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