简体   繁体   English

C ++ Opencv:分配值后打印Mat时出错

[英]C++ Opencv: Error when printing Mat after assigning values

I declared a Mat and assign values to every element using a for-loop. 我声明了Mat并使用for循环为每个元素分配值。 Then I want to print its values. 然后我要打印其值。 However, I core dump error happens. 但是,我发生核心转储错误。 My code is as follows: 我的代码如下:

#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;
}

The cout works until it finishes printing the "???????". 直到打印完“ ???????”后,指示框才会起作用。 Then the core dump error happens. 然后发生核心转储错误。 The screen message is as follows: 屏幕消息如下:

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: =========

What's wrong with my code? 我的代码出了什么问题? Why does it report double free error? 为什么报告两次免费错误?

Thank you for helping me! 感谢你们对我的帮助!

The first comment solve my problem. 第一条评论解决了我的问题。 I just copy his comment here: 我只在这里复制他的评论:

Change int n_Channel = 1 to const int n_Channel = 1, and then change all M.at to M.at>. 将int n_Channel = 1更改为const int n_Channel = 1,然后将所有M.at更改为M.at>。 Your actual example only has one channel, thus using Vec3f is wrong. 您的实际示例只有一个通道,因此使用Vec3f是错误的。 Using Vec gives you the possibility to address float images of arbitrary number of channels. 使用Vec可以处理任意数量通道的浮动图像。 But therefore, n_Channel must be const. 但是,因此n_Channel必须为const。

Thank you @HansHirse . 谢谢@HansHirse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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