運用opencv 讀取BMP影象畫素資訊 程式碼及實現
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.參考資料: