CV :: Mat导致运行时错误 - OpenCV错误 - 断言失败

时间:2015-11-19 06:25:03

标签: c++ opencv

我正在处理图像处理项目,我遇到了系统崩溃。这是一个不断弹出的错误:

  

OpenCV错误:断言失败(dims< = 2&& data&&(unsigned)i0<(unsigned)si   ze.p [0]&& (无符号)(i1 * DataType< _Tp> :: channels)< (无符号)(size.p [1] *信道   s())&& ((((sizeof(size_t)<< 28)| 0x8442211)>>((DataType< _Tp> :: depth)&((1<<<   ) - 1))* 4)& 15)== elemSize1())在cv :: Mat :: at中,文件d:\ libs \ opencv-249 \ build \ i   nclude \ opencv2 \ core \ mat.hpp,第537行

我能够发现以下一些代码正在解决问题

samples = (src.size(), src.type());
imshow ("source" , src);
for( int y = 0; y < src.rows; y++ )
for( int x = 0; x < src.cols; x++ )
  for( int z = 0; z < 3; z++){

      samples.at<float>((y + (x*src.rows)), z) = src.at<Vec3b>(y,x)[z];}

samples是在此类的头文件中声明的Mat对象。

我也提到了这个link,但即使错误相同,导致崩溃的代码也与我的不一样。但尴尬的是,这段确切的代码在另一个函数中工作正常,但是当我尝试在属于类的方法中包含相同的代码时,它就会产生这个错误。

我很无能为力。谁能帮我吗?

2 个答案:

答案 0 :(得分:0)

在通话samples.at<float>((y + (x*src.rows)), z)中,您可以在x = zy = (y + (x*src.rows)的位置访问该图片。

你可以得到的最高值是(y + (x*src.rows)) = (src.rows-1 + ((src.cols-1)*src.rows)) = src.rows*src.cols-1。这远远高于src.cols-1的最大允许值,因此OpenCV会抛出一个断言,告诉您这超出了图像的范围。

我不知道为什么它在代码的一部分中起作用而在另一部分中起作用,但这显然是一个问题。

另外,什么是src.type()?当它们具有相同的类型时,为什么将样本作为“浮点数”和src作为“Vec3b”访问?这似乎也很危险。

答案 1 :(得分:0)

您希望samples成为一个矩阵:

# rows     : src.rows * src.cols
# cols     : src.channels() // it's probably 3,
type       : CV_32F (float)
# channels : 1 (single channel matrix)

您使用samples中位置(r,c)的索引访问src行:

int index = r * src.cols + c;

例如,如果src2x4 3频道图片(具有随机值):

enter image description here

您希望samples成为8x3单通道浮点矩阵:

enter image description here

代码:

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
    // Init src image
    Mat src(2, 4, CV_8UC3);
    randu(src, Scalar(0, 0, 0), Scalar(255, 255, 255));

    // Init samples image
    // # rows = src.rows * src.cols
    // # cols = src.channels()
    // type   =  CV_32FC1 (single channel float, while src type is 3 channel CV_8U)
    Mat samples(src.rows * src.cols, src.channels(), CV_32FC1);

    for (int r = 0; r < src.rows; ++r)
    {
        for (int c = 0; c < src.cols; ++c)
        {
            int index = r * src.cols + c;
            for (int channel = 0; channel < src.channels(); ++channel)
            {
                samples.at<float>(index, channel) = src.at<Vec3b>(r, c)[channel];
            }
        }
    }

    cout << "SRC: " << endl << src << endl << endl;
    cout << "SAMPLES: " << endl << samples << endl << endl;


    return 0;
}
相关问题