opencv关于摄像头的几个api
/* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */ CVAPI(CvCapture*) cvCreateCameraCapture( int index ); /* grab a frame, return 1 on success, 0 on fail. this function is thought to be fast */ CVAPI(int) cvGrabFrame( CvCapture* capture ); /* get the frame grabbed with cvGrabFrame(..) This function may apply some frame processing like frame decompression, flipping etc. !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) ); /* Just a combination of cvGrabFrame and cvRetrieveFrame !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ CVAPI(IplImage*) cvQueryFrame( CvCapture* capture ); /* stop capturing/reading and free resources */ CVAPI(void) cvReleaseCapture( CvCapture** capture );
很简单一个流程就是
1.cvCreateCameraCapture//获取捕捉器
2.cvQueryFrame//抓取一帧
3.cvReleaseCapture//释放捕捉器
灰度图
将一幅彩色图转换成灰度图 参见说明文档
(1) 字节型图像的灰度-彩色转换: cvConvertImage(src, dst, flags=0); src = float/byte grayscale/color image dst = byte grayscale/color image flags = CV_CVTIMG_FLIP (垂直翻转图像) CV_CVTIMG_SWAP_RB (置换 R 和 B 通道) (2) 彩色图像->灰度图像: // Using the OpenCV conversion: cvCvtColor(cimg,gimg,CV_BGR2GRAY); // cimg -> gimg // Using a direct conversion: for(i=0;i<cimg->height;i++) for(j=0;j<cimg->width;j++) gimgA[i][j]= (uchar)(cimgA[i][j].b*0.114 + cimgA[i][j].g*0.587 + cimgA[i][j].r*0.299); (3) 不同彩色空间之间的转换: cvCvtColor(src,dst,code); // src -> dst code = CV_<X>2<Y> <X>/<Y> = RGB, BGR, GRAY, HSV, YCrCb, XYZ, Lab, Luv, HLS e.g.: CV_BGR2GRAY, CV_BGR2HSV, CV_BGR2Lab
上代码 比较清晰
#include <stdlib.h> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main(int argc, _TCHAR* argv[]) { IplImage * tmpImg = 0; IplImage * grayImg = 0; //初始化一个摄像头捕捉器 CvCapture* capture = cvCreateCameraCapture(1); int num = 0; cvNamedWindow("camera"); cvNamedWindow("gray"); //取背景 while( (tmpImg = cvQueryFrame(capture))!= NULL) { if(tmpImg == NULL) break; // Using the OpenCV conversion: CvSize dst_size; //get the tmpImg's size dst_size.width = tmpImg->width; dst_size.height = tmpImg->height; grayImg = cvCreateImage(dst_size,tmpImg->depth,1);//create gray image cvCvtColor(tmpImg,grayImg,CV_BGR2GRAY); // tmpImg -> grayImg cvShowImage("camera",tmpImg); cvShowImage("gray",grayImg); if(grayImg != NULL) cvShowImage("gray",grayImg); waitKey(1000); // if(num>10) // imwrite(getImageName(num),Mat(tmpImg)); if(++num == 120) break; } if(capture!=NULL) cvReleaseCapture(&capture); //销毁窗口 cvDestroyWindow("camera"); cvDestroyWindow("灰度图"); //此函数等待按键,按键盘任意键就返回 waitKey(); return 0; }