Reputation: 71
here is the code i have written in 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);
}
the code works fine until it shows every pixels values in terms of
Vec3b
,but at last the exception like "Unhandled exception at 0x75afb9bc in san.exe: Microsoft C++ exception: cv::Exception at memory location 0x0043f9d0..
" will come up in prompting windows asks to break or continue the flow
And in command console, where i m getting the pixels values to be displayed, in this it's showing me as 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
, after displaying pixels data.
i checked whole web and the mat.hpp
also it's inline function given, so i'm frustrated, can anyone plz explain abt this error(exception) and help me out to get code run only until the data pixels is their in bitmap and execute nicely.plz
Upvotes: 0
Views: 4536
Reputation: 1575
Color format
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;
}
}
Gray format
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;
}
}
Upvotes: 1
Reputation: 39796
you're confusing rows and cols here.
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";
}
Upvotes: 2