繁体   English   中英

从位图图像文件读取像素数据值

[英]Reading pixels data values from a bitmap image file

这是我用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表示的每个像素值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显示像素数据后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它也提供了内联函数,所以我很沮丧,有人可以解释这个错误(异常)并帮助我让代码运行直到数据像素在位图中并执行之前nice.plz

您在这里混淆行和列。

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

色彩格式

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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