#include <stdio.h>
#include <cv.h>
#include <highgui.h>
void help() {
printf("\nRead out RGB pixel values and store them to disk\nCall:\n"
"./ch9_ex9_1 avi_file\n"
"\n This will store to files blines.csv, glines.csv and rlines.csv\n\n");
}
int main( int argc, char** argv )
{
if(argc != 2)
{
help();
return -1;
}
cvNamedWindow( "Example9_1", CV_WINDOW_AUTOSIZE );//建立一个窗体Example9_1
CvCapture* capture = cvCreateFileCapture( argv[1] );//创建一个CvCapture结构。函数cvCreateFileCapture()中参数设置确定要读入的AVI文件。
if(!capture)
{
printf("\nCouldn't open %s\n",argv[1]);
help();
return -1;
}
//CvPoint是一个包含integer类型成员变量x,y的简单结构体。有两个变体CvPoint2D32f,CvPoint3D32f。前者同样两个成员变量x,y,但是浮点类型。后者多了一个浮点类型的成员变量z
//pt1,pt2是任意采样直线上的两个端点。
CvPoint pt1 = cvPoint(10,10);
CvPoint pt2 = cvPoint(20,25);
int max_buffer;
IplImage *rawImage;
// int r[10000],g[10000],b[10000];
FILE *fptrb = fopen("blines.csv","w"); //Store the data here
FILE *fptrg = fopen("glines.csv","w"); // for each color channel
FILE *fptrr = fopen("rlines.csv","w");
CvLineIterator iterator;//线采样函数
//MAIN PROCESSING LOOP:
for(;;){
/*
*/
if( !cvGrabFrame( capture ))
break;
rawImage = cvRetrieveFrame( capture );
/*
函数cvInitLineIterator()将返回直线上迭代的个数。迭代器line_iterator说明直线上两个像素之间的移动步长。
每个通道的像素值可同时使用line_iterator.ptr[0,1,2]等依次得到。
*/
max_buffer = cvInitLineIterator(rawImage,pt1,pt2,&iterator,8,0);
cvShowImage( "Example9_1", rawImage );
int c = cvWaitKey(10);
for(int j=0; j<max_buffer; j++){
fprintf(fptrb,"%d,", iterator.ptr[0]); //Write blue value
fprintf(fptrg,"%d,", iterator.ptr[1]); //green
fprintf(fptrr,"%d,", iterator.ptr[2]); //red
iterator.ptr[2] = 255; //Mark this sample in red
//使得迭代器从一个像素到另一个像素。
CV_NEXT_LINE_POINT(iterator); //Step to the next pixel
}
//OUTPUT THE DATA IN ROWS:
fprintf(fptrb,"\n");fprintf(fptrg,"\n");fprintf(fptrr,"\n");
}
//CLEAN UP:
printf("\nData stored to files: blines.csv, glines.csv and rlines.csv\n\n");
fclose(fptrb); fclose(fptrg); fclose(fptrr);
cvReleaseCapture( &capture );
cvDestroyWindow( "Example9_1" );
}
这个代码是简单的对一条线段进行采样。通常这是创建特征和调试都很有用的手段。
/*
写入文件,需要首先创建文件结构File,使用File类型 File *fptrb = fopen(“文件名”, “读写方式r/2”);
具体的写入操作使用fprintf(File, content);
写入结束之后要对文件进行关闭,避免资源浪费。fclose(File *)
*/