[英]Why does assertion fail here
Why does the assertion fail here when i create a CvMat *
? 为什么创建CvMat *
时断言在这里失败? It does not happen with an image i load in cv::Mat using a pointer. 我使用指针在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;
}
}
For this code the assertion does not fail: 对于此代码,断言不会失败:
IplImage * img=cvLoadImage("blah.jpg");
int row=0,col=0;
cv::Mat in(img);
cv::Mat *mat=∈
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);
}
}
Because sizeof(RGB) != sizeof(float)
, which is what you filled the matrix with here: 因为sizeof(RGB) != sizeof(float)
,这是您在此处用矩阵填充的内容:
CvMat* mat = cvCreateMat(300,300,CV_32FC1);
CV_32FC1
means 1 component, 32-bit floating point. CV_32FC1
表示1个组件,32位浮点。 You probably want CV_8UC3
. 您可能需要CV_8UC3
。 See here or another OpenCV reference. 请参阅此处或其他OpenCV参考。
You can skip the entire IplImage
misery if you use cv::Mat img = cv::loadImage("blah.jpg");
如果使用cv::Mat img = cv::loadImage("blah.jpg");
则可以跳过整个IplImage
痛苦过程cv::Mat img = cv::loadImage("blah.jpg");
Also it is better to use row ptr for going through all the pixels. 另外,最好使用行ptr遍历所有像素。
It knows the jumps, so you don't have to worry! 它知道跳跃,所以您不必担心!
From the refman: 来自refman:
If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to the row first, and then just use the plain C operator [] 如果您需要处理2D数组的整行,最有效的方法是先获取指向该行的指针,然后再使用普通的C运算符[]
Be aware that if you are loading bigger images which have "jumps" in their data, your code will not work. 请注意,如果要加载较大的图像,这些图像的数据中有“跳转”,则代码将无法工作。 In your situation 在你的情况下
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;
}
}
is the fastest correct way. 是最快的正确方法。 Otherwise you could use M.at<Vec3b>(i,j)
. 否则,您可以使用M.at<Vec3b>(i,j)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.