C OPENCV:分配值后打印垫时发生错误

C++ Opencv: Error when printing Mat after assigning values

本文关键字:错误 打印 OPENCV 分配      更新时间:2023-10-16

我使用循环说明了一个垫子并将值分配给每个元素。然后,我想打印其值。但是,我的核心转储错误发生了。我的代码如下:

#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <iostream>
#include <time.h>
using namespace std;
using namespace cv;
int main(int argc, char const *argv[])
{
    int n = 4, i, j;
    srand (time(NULL));
    int n_Channel = 1;
    int mySizes[2] = {2, 4};
    Mat M = Mat::zeros(2, mySizes, CV_32FC(n_Channel));
    cout << M.rows << "," << M.cols << "," << M.channels() << endl;
    cout << M << endl;
    for (i = 0; i < M.rows; ++i)
    {
        for (j = 0; j < M.cols; ++j)
        {
            M.at<Vec3f>(i,j)[0] = rand() % n;
            cout << "i=" << i << ", j=" << j << ", M.at<Vec3f>(i,j)[0]=" << M.at<Vec3f>(i,j)[0] << endl;
        }
    }
    cout << "???????" << endl;
    cout << M << endl;
    return 0;
}

cout工作直到完成打印" ???????"。然后发生核心转储错误。屏幕消息如下:

2,4,1
[0, 0, 0, 0;
 0, 0, 0, 0]
i=0, j=0, M.at<Vec3f>(i,j)[0]=3
i=0, j=1, M.at<Vec3f>(i,j)[0]=3
i=0, j=2, M.at<Vec3f>(i,j)[0]=3
i=0, j=3, M.at<Vec3f>(i,j)[0]=1
i=1, j=0, M.at<Vec3f>(i,j)[0]=3
i=1, j=1, M.at<Vec3f>(i,j)[0]=3
i=1, j=2, M.at<Vec3f>(i,j)[0]=0
i=1, j=3, M.at<Vec3f>(i,j)[0]=0
???????
*** Error in `./my_app': malloc(): memory corruption (fast): 0x000000000245dfb0 ***
======= Backtrace: =========

我的代码怎么了?为什么它报告双免费错误?

感谢您帮助我!

第一个评论解决了我的问题。我只是在这里复制他的评论:

将int n_channel = 1更改为const int int n_channel = 1,然后将所有m.at更改为m.at>。您的实际示例只有一个通道,因此使用VEC3F是错误的。使用VEC使您有可能解决任意数量的频道的浮动图像。因此,N_CHANNEL必须为const。

谢谢@hanshirse。