简体   繁体   中英

Reading pixels data values from a bitmap image file

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 im 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

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";
}

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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM