为什么断言失败

问题描述:

为什么当我创建CvMat *时断言失败?它不会发生与我使用指针加载在cv :: Mat中的图像。为什么断言失败

struct RGB { unsigned char b, g, r; }; 
    cv::Point p; 
    RGB *data; 
    CvMat* mat = cvCreateMat(300,300,CV_32FC1); 
    for(row = 0; row < mat->rows; ++row) 
    { 
      for (col = 0; col < mat->cols; ++col) 
      { 
       p.x=row,p.y=col; 
     ERROR ----->>> assert((mat->step/mat->cols) == sizeof(RGB)); 
       data = (RGB*)&mat->data; 
       data += p.y * mat->cols + p.x; 
      } 
    } 

对于这个代码的断言不会失败:

IplImage * img=cvLoadImage("blah.jpg"); 
    int row=0,col=0; 
    cv::Mat in(img); 
    cv::Mat *mat=&in; 
    cv::Point p; 
    struct RGB { unsigned char b, g, r; }; 
    RGB *data; 
    for(row = 0; row < mat->rows; ++row) 
    { 
      for (col = 0; col < mat->cols; ++col) 
      { 
       p.x=row,p.y=col; 
       assert((mat->step/mat->cols) == sizeof(RGB)); 
       data = (RGB*)&mat->data; 
       data += p.y * mat->cols + p.x; 
       printf("Row=%dxCol=%d  b=%u g=%u r=%u\n",row,col,data->b,data->g,data->r); 
       wait_for_frame(1); 
      } 
    } 

因为sizeof(RGB) != sizeof(float),这就是你充满了这里的矩阵:

CvMat* mat = cvCreateMat(300,300,CV_32FC1); 

CV_32FC1意味着1个组件,32位浮点。你可能想要CV_8UC3。请参阅here或其他OpenCV参考。

如果使用 cv::Mat img = cv::loadImage("blah.jpg"); 也最好是使用行PTR通过所有像素要去你可以跳过整个IplImage痛苦。
它知道跳跃,所以你不必担心!

从refman:

如果您需要处理一个二维数组,一整排的,最有效的 方法是首先得到的指针行,然后只需用 纯C运算符[]

请注意,如果您要加载的数据中包含“跳转”的较大图像,则代码将无法工作。 在你的情况

cv::Mat img = cv::loadImage("blah.jpg"); 
const cv::Mat& M = img; 
for(int i = 0; i < rows; i++) 
{ 
    const Vec3b* Mi = M.ptr<Vec3b>(i); 
    for(int j = 0; j < cols; j++) 
    { 
     const Vec3b& Mij = Mi[j]; 
     std::cout<<"Row="<<i<<"Col="<<j<<"\t"; 
     std::cout<<"b="<<Mij[0]<<" g="<<Mij[1]<<" r="<<Mij[2]<<std::endl; 
    } 
} 

是最快的正确途径。否则,您可以使用M.at<Vec3b>(i,j)

+0

也许你的意思是const Vec3b&Mij = Mi [j]; – iNFINITEi

+0

是的,我确实,thx! –