C ++ OpenCV Mat像素值和Opencv错误

时间:2018-11-24 14:52:29

标签: c++ opencv

我正在使用Visual Studio和opencv编写一个简单的c ++应用程序,该应用程序存储图像中的红色,绿色和蓝色值(在代码中命名为src),并将每个红色,绿色和蓝色像素值分别存储在3个不同的Mat对象中(在代码中命名为RM,BM,GM)。我看到了这个stackOverflow question 并完全按照第一个答案的解释进行。我能够很好地保存所有像素值,但是由于调用了Abort(),因此无法更改其他图像的像素值。运行代码后,这是控制台窗口。 Console Window

#include<opencv2/core.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgproc.hpp>
#include <stdio.h>
using namespace cv;
using namespace std;
int main() {
    String file_name = "C:\\images\\haaand.jpg";
    Mat src;
    Mat RM, BM, GM;
    //RM.create(src.cols, src.rows, CV_8UC(2));
    //BM.create(src.cols, src.rows, CV_8UC(2));
    //GM.create(src.cols, src.rows, CV_8UC(2));
    Vec3b intensity;
    Vec3b To[3];
    src = imread(file_name);
    imshow("src", src);
    printf("cols:%d rows:%d \n", src.cols, src.rows);
    for (int i = 0; i < src.cols; i++) {
        for (int j = 0; j < src.rows; j++) {
            intensity = src.at<Vec3b>(j, i);
            printf("intensity:%d %d %d \n", intensity[0], intensity[1], intensity[2]);
            for (int k = 0; k < 3; k++) {
                //uchar bla;
                //bla = intensity[k];
                for (int p = 0; p < 3; p++) {
                    To[k][p] = intensity[k];
                }
                printf("(k:%d) %d %d %d\n", k, To[k][0], To[k][1], To[k][2]);
            }
            printf("all done\n");
            BM.at<Vec3b>(j, i) = To[0];
            GM.at<Vec3b>(j, i) = To[1];
            RM.at<Vec3b>(j, i) = To[2];
        }
    }
    imshow("RM", RM);
    imshow("BM", BM);
    imshow("GM", GM);
    return 0;
}

谁能告诉我为什么会发生此错误?

1 个答案:

答案 0 :(得分:0)

//RM.create(src.cols, src.rows, CV_8UC(2));
//BM.create(src.cols, src.rows, CV_8UC(2));
//GM.create(src.cols, src.rows, CV_8UC(2));
...
BM.at<Vec3b>(j, i) = To[0];

RM, BM, and GM未设置。尝试设置BM.at<Vec3b>(j, i)时,调试器应显示错误。

请尝试:

int main() 
{
    String file_name = "C:\\images\\haaand.jpg";
    Mat src = imread(file_name);
    Mat RM = Mat(src.size(), CV_8UC3);
    Mat BM = Mat(src.size(), CV_8UC3);
    Mat GM = Mat(src.size(), CV_8UC3);
    Vec3b intensity;
    Vec3b To[3];
    for(int i = 0; i < src.cols; i++) 
    {
        for(int j = 0; j < src.rows; j++) 
        {
            intensity = src.at<Vec3b>(j, i);
            for(int k = 0; k < 3; k++) 
                for(int p = 0; p < 3; p++) 
                    To[k][p] = intensity[k];
            BM.at<Vec3b>(j, i) = To[0];
            GM.at<Vec3b>(j, i) = To[1];
            RM.at<Vec3b>(j, i) = To[2];
        }
    }

    imshow("src", src);
    imshow("RM", RM);
    imshow("BM", BM);
    imshow("GM", GM);
    waitKey(0);
    return 0;
}