将上篇读取视频http://blog.csdn.net/zhangjikuan/article/details/39938581
与opencv程序九:轮廓检测均衡化http://blog.csdn.net/zhangjikuan/article/details/39900307
结合实现读取摄像头实时视频轮廓检测
程序如下:
// 21VideoContours.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <cv.h> #include <cxcore.h> #include <highgui.h> int apos=0; void on_trackbar(int pos) { apos=pos; } int _tmain(int argc, _TCHAR* argv[]) { const char *pstrWindowsSrcTitle = "原图"; const char *pstrWindowsGrayTitle = "灰度图"; const char *pstrWindowsErZhiTitle = "二值图"; const char *pstrWindowsContoursTitle = "轮廓图"; const char *pstrWindowsContoursEqualizeTitle = "轮廓均衡图"; IplImage* motion = NULL; CvCapture* capture = NULL; //视频获取结构 CvSeq *g_pcvSeq = NULL; //轮廓最大层数 int _levels = 5; capture = cvCaptureFromCAM( 0 ); // capture = cvCaptureFromAVI( "1344.avi" ); if( capture ) { cvNamedWindow( pstrWindowsSrcTitle, 1 ); cvNamedWindow(pstrWindowsGrayTitle, 1 ); cvNamedWindow( pstrWindowsErZhiTitle, 1 ); cvNamedWindow( pstrWindowsContoursTitle, 1 ); cvGrabFrame( capture ); //从摄像头或者视频文件中抓取帧 IplImage* image = cvRetrieveFrame( capture ); //取回由函数cvGrabFrame抓取的图像,返回由函数cvGrabFrame 抓取的图像的指针 IplImage* image_gray= cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); IplImage* image_erzhi= cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); IplImage* image_qualize= cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); IplImage *image_contours = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 3); // 滑动条 int nThreshold = 0; cvCreateTrackbar("erzhihua", pstrWindowsErZhiTitle, &nThreshold, 254, on_trackbar); CvMemStorage* cvMStorage = cvCreateMemStorage(); for(;;) { if( !cvGrabFrame( capture )) //从摄像头或者视频文件中抓取帧 break; image = cvRetrieveFrame( capture ); //取回由函数cvGrabFrame抓取的图像,返回由函数cvGrabFrame 抓取的图像的指针 cvShowImage( pstrWindowsSrcTitle, image ); // 转为灰度图 cvCvtColor(image, image_gray, CV_BGR2GRAY); cvShowImage( pstrWindowsGrayTitle, image_gray ); // 均衡化 cvEqualizeHist(image_gray, image_qualize); // 转为二值图 cvThreshold(image_qualize, image_erzhi, apos, 255, CV_THRESH_BINARY); cvShowImage(pstrWindowsErZhiTitle, image_erzhi ); // 检索轮廓并返回检测到的轮廓的个数 cvFindContours(image_erzhi,cvMStorage, &g_pcvSeq); cvZero(image_contours); cvDrawContours(image_contours, g_pcvSeq, CV_RGB(255,0,0), CV_RGB(0,255,0), _levels); cvShowImage(pstrWindowsContoursTitle, image_contours); if( cvWaitKey(10) >= 0 ) break; } cvDestroyWindow(pstrWindowsSrcTitle); cvDestroyWindow(pstrWindowsGrayTitle); cvDestroyWindow(pstrWindowsErZhiTitle); cvDestroyWindow(pstrWindowsContoursTitle); cvReleaseCapture( &capture ); cvReleaseImage(&image); cvReleaseImage(&image_gray); cvReleaseImage(&image_erzhi); cvReleaseImage(&image_contours); } return 0; }