这是我用c ++编写的代码
int main()
{
Mat im = imread("C:/santhu/bitmap.bmp");
int rows = im.rows;
int cols = im.cols;
cout<<"rows\n"<<rows;
cout<<"cols"<<cols;
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
cout<<"the output for matrix of pixels";
for (int i = 0; i <cols ; i++)
{
Vec3b *ptr = im.ptr<Vec3b>(i);
for (int j = 0; j < rows; j++)
{
Vec3b pixel = ptr[j];
cout<<pixel<<"\t";
}
cout<<"\n";
}
getchar();
imshow("Image", im);
waitKey(0);
}
代码正常工作,直到它显示每个像素值
Vec3b
,但最后会出现提示窗口要求中断或继续流程的“Unhandled exception at 0x75afb9bc in san.exe: Microsoft C++ exception: cv::Exception at memory location 0x0043f9d0..
”之类的异常
在命令控制台中,我显示像素值,在显示像素数据后显示为opencv error:assertion failed(y==0 ||(data && dims)=1 &&(unsigned) y <(unsigned)size.p[0] in cv::Mat::ptr,file c:\opencv\build\include\opencv2\core\mat.hpp,line 428
。
我检查了整个网络和mat.hpp
也给它了内联函数,所以我很沮丧,任何人都可以解释abt这个错误(异常)并帮助我让代码运行直到数据像素是他们在位图中执行nicely.plz
答案 0 :(得分:2)
你在这里混淆了行和列。
for (int i = 0; i <rows; i++) // rows, not cols
{
Vec3b *ptr = im.ptr<Vec3b>(i);
for (int j = 0; j < cols; j++) // cols, not rows
{
Vec3b pixel = ptr[j];
cout<<pixel<<"\t";
}
cout<<"\n";
}
答案 1 :(得分:1)
颜色格式
for(int j = 0; j < img.rows; j++) {
for(int i = 0; i < img.cols; i++) {
uchar b = img.ptr<cv::Vec3b>(j)[i][0];
ucahr g = img.ptr<cv::Vec3b>(j)[i][1];
uchar r = img.ptr<cv::Vec3b>(j)[i][2];
std::cout << "b = " << (int) b << std::endl
<< "g = " << (int) g << std::endl
<< "r = " << (int) r << std::endl;
}
}
灰色格式
cv::Mat img;
cv::cvtColor(src,img,CV_BGR2RGB);
for(int j = 0; j < img.rows; j++) {
for(int i = 0; i < img.cols; i++) {
std::cout << "gray value = " << img.ptr<uchar>(j)[i] << std::endl;
}
}