运用opencv 读取BMP图像像素信息 代码及实现

来源:互联网 发布:局域网行为监控软件 编辑:程序博客网 时间:2024/05/06 01:20

1. 环境:Win7(64位),opencv2.3,vs2010

2.代码:

///////////////////////////////////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <string>
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace std;
 
int main(int argc, char *argv[])
{
 
  IplImage* img = 0;
  int height,width,step,channels;
  uchar *data;
  int i,j,k;
 
  if(argc<2){
    printf("Usage: main <image-file-name>\n\7");
    exit(0);
  }
 
  // load an image 
  img=cvLoadImage(argv[1]);
  if(!img){
    printf("Could not load image file: %s\n",argv[1]);
    exit(0);
  }
 
  // get the image data
  height    = img->height;
  width     = img->width;
  //step      = img->widthStep;
  //channels  = img->nChannels;
  //data      = (uchar *)img->imageData;
  printf("Processing a %dx%d image with %d channels\n",height,width,channels);

 

  //build File to save pixel value
  ofstream outFile_B;
  ofstream outFile_G;
  ofstream outFile_R;
  outFile_B.open("out_B.txt");
  outFile_G.open("out_G.txt");
  outFile_R.open("out_R.txt");

 

   //get the pixel value

  CvScalar s;
  for(i=0;i<height;i++) //i 代表 y 轴
  {
     for(j=0;j<width;j++) //j 代表 x轴
     {
        s=cvGet2D(img,i,j); // get the (j,i) pixel value


       outFile_B<<s.val[0]<<" ";
       outFile_G<<s.val[1]<<" ";
       outFile_R<<s.val[2]<<" "; 
      }
      outFile_B<<endl;
      outFile_G<<endl;
      outFile_R<<endl;
  }
  return 0; 

}

3.实现

   用cmd执行:
    例如我的是:D:\\Projects\practice\Lena\x64\Debug〉Lena.exe "D:\\lena.bmp"

    实现截图:

 

4.参考资料:

http://www.opencv.org.cn/index.php/OpenCV_%E7%BC%96%E7%A8%8B%E7%AE%80%E4%BB%8B%EF%BC%88%E7%9F%A9%E9%98%B5/%E5%9B%BE%E5%83%8F/%E8%A7%86%E9%A2%91%E7%9A%84%E5%9F%BA%E6%9C%AC%E8%AF%BB%E5%86%99%E6%93%8D%E4%BD%9C%EF%BC%89#.EF.BC.881.EF.BC.89____.E5.81.87.E8.AE.BE.E4.BD.A0.E8.A6.81.E8.AE.BF.E9.97.AE.E7.AC.ACk.E9.80.9A.E9.81.93.E3.80.81.E7.AC.ACi.E8.A1.8C.E3.80.81.E7.AC.ACj.E5.88.97.E7.9A.84.E5.83.8F.E7.B4.A0.E3.80.82

 

原创粉丝点击