OpenCV的一个实例

上传人:工**** 文档编号:588088832 上传时间:2024-09-07 格式:PPT 页数:138 大小:2.36MB
返回 下载 相关 举报
OpenCV的一个实例_第1页
第1页 / 共138页
OpenCV的一个实例_第2页
第2页 / 共138页
OpenCV的一个实例_第3页
第3页 / 共138页
OpenCV的一个实例_第4页
第4页 / 共138页
OpenCV的一个实例_第5页
第5页 / 共138页
点击查看更多>>
资源描述

《OpenCV的一个实例》由会员分享,可在线阅读,更多相关《OpenCV的一个实例(138页珍藏版)》请在金锄头文库上搜索。

1、OpenCV实例实例OpenCV例程 常用的标准图常用的标准图 图像文件读入和显示图像文件读入和显示 图像创建、保存和复制图像创建、保存和复制 CannyCanny边缘检测边缘检测 CannyCanny边缘检测边缘检测2 2 轮廓轮廓(contour)(contour)检测检测 轮廓轮廓(contour)(contour)检测检测2 2 图像旋转与缩放图像旋转与缩放 读视频文件和运动物体读视频文件和运动物体检测检测 HoughHough线段检测线段检测 鼠标绘图鼠标绘图 snakesnake轮廓例子轮廓例子 离散傅立叶变换(DFT)人脸检测QR分解绘制贝赛尔Bezier曲线使用DirectSh

2、ow采集图像设定跟踪目标图片的改进摄像头标定施密特正交化高斯背景建模图像缩放高级图像处理初步常用的标准图常用的标准图n n(90KB,MIMEtype:image/jpeg)(81KB,MIMEtype:image/jpeg)(176KB,MIMEtype:image/jpeg)(84KB,MIMEtype:image/jpeg)图像文件读入和显示图像文件读入和显示1.1.1.1./*/*/*/*2.2.2.2.* * * * OpenCVOpenCVOpenCVOpenCV example example example example3.3.3.3.* By * By * By * By

3、ShiqiShiqiShiqiShiqi Yu 2006 Yu 2006 Yu 2006 Yu 20064.4.4.4.*/*/*/*/5.5.5.5.6.6.6.6.#include #include #include #include 7.7.7.7.#include #include #include #include 8.8.8.8.9.9.9.9.intintintint main( main( main( main( intintintint argcargcargcargc, char* , char* , char* , char* argvargvargvargv ) ) )

4、 )10.10.10.10. 11.11.11.11.IplImageIplImageIplImageIplImage* * * * pImgpImgpImgpImg; /; /; /; /声明声明声明声明IplImageIplImageIplImageIplImage指针指针指针指针12.12.12.12.13.13.13.13./载入图像载入图像载入图像载入图像14.14.14.14.if( if( if( if( argcargcargcargc = 2 & = 2 & = 2 & = 2 & 15.15.15.15.( ( ( (pImgpImgpImgpImg = = = = cvL

5、oadImagecvLoadImagecvLoadImagecvLoadImage( argv1, 1)!= 0 )( argv1, 1)!= 0 )( argv1, 1)!= 0 )( argv1, 1)!= 0 )16.16.16.16. 17.17.17.17.cvNamedWindowcvNamedWindow( Image, 1 );/( Image, 1 );/创建窗口创建窗口18.18.18.18.cvShowImagecvShowImage( Image, ( Image, pImgpImg );/ );/显示图像显示图像19.19.19.19.20.20.20.20.cvWa

6、itKey(0); /cvWaitKey(0); /等待按键等待按键21.21.21.21.22.22.22.22.cvDestroyWindowcvDestroyWindow( Image );/( Image );/销毁窗口销毁窗口23.23.23.23.cvReleaseImagecvReleaseImage( &( &pImgpImg ); / ); /释放图像释放图像24.24.24.24.return 0;return 0;25.25.25.25. 26.26.26.26.27.27.27.27.return -1;return -1;28.28.28.28. 图像创建、保存和复制

7、图像创建、保存和复制1. 1./*/*2. 2.* *cvLoadImagecvLoadImage, ,cvSaveImagecvSaveImage, ,cvCreateImagecvCreateImage, ,cvCopycvCopy以及图像显示的例子以及图像显示的例子3. 3.*/ /4. 4. 5. 5./*/*6. 6.* *OpenCVOpenCVexampleexample7. 7.*By*ByShiqiShiqiYu2006Yu20068. 8.*/*/9. 9. 10.10.#include#include 11.11.#include#include 12.12. 13.13

8、.intintmain(main(intint argcargc,char*,char*argvargv) )14.14. 15.15.IplImageIplImage* *pImgpImg;/;/声明声明IplImageIplImage指针指针16.16. 17.17./ /载入图像,强制转化为载入图像,强制转化为载入图像,强制转化为载入图像,强制转化为GrayGray18.18.if(if(argcargc=3&=3&19.19.( (pImgpImg=cvLoadImagecvLoadImage(argv1,0)!=0)(argv1,0)!=0)20.20. 21.21. 22.22.I

9、plImageIplImage*pImg2=*pImg2=cvCreateImage(cvGetSize(pImgcvCreateImage(cvGetSize(pImg), ),23.23.pImgpImg-depth,-depth,24.24.pImgpImg-nChannelsnChannels); );25.25.cvCopy(pImgcvCopy(pImg,pImg2,NULL);,pImg2,NULL);26.26. 27.27.cvSaveImage(argv2,pImg2);/cvSaveImage(argv2,pImg2);/把图像写入文件把图像写入文件把图像写入文件把图像写

10、入文件28.28. 29.29.cvNamedWindowcvNamedWindow(Image,1);/(Image,1);/创建窗口创建窗口创建窗口创建窗口30.30.cvShowImagecvShowImage(Image,(Image,pImgpImg);/);/显示图像显示图像显示图像显示图像31.31. 32.32.cvWaitKey(0);/cvWaitKey(0);/等待按键等待按键等待按键等待按键33.33. 34.34.cvDestroyWindowcvDestroyWindow(Image);/(Image);/销毁窗口销毁窗口销毁窗口销毁窗口17.17.cvReleas

11、eImagecvReleaseImage(&(&pImgpImg);/);/释放图像释放图像释放图像释放图像18.18.cvReleaseImagecvReleaseImage(&pImg2);/(&pImg2);/释放图像释放图像释放图像释放图像19.19.return0;return0;20.20. 21.21. 22.22.return-1;return-1;23.23. Canny边缘检测边缘检测1. 1./*/*2. 2.* *cvCannycvCanny:CannyCanny边缘检测边缘检测边缘检测边缘检测3. 3.*/ /4. 4. 5. 5./*/*6. 6.* *OpenCV

12、OpenCVexampleexample7. 7.*By*ByShiqiShiqiYu2006Yu20068. 8.*/*/9. 9. 10.10.#include#include 11.11.#include#include 12.12.#include#include 13.13. 14.14.intintmain(main(intint argcargc,char*,char*argvargv) )15.15. 16.16./ /声明声明声明声明IplImageIplImage指针指针指针指针17.17.IplImageIplImage* *pImgpImg=NULL;=NULL;18.

13、18.IplImageIplImage* *pCannyImgpCannyImg=NULL;=NULL;1. 1. 2. 2./ /载入图像,强制转化为载入图像,强制转化为载入图像,强制转化为载入图像,强制转化为GrayGray3. 3.if(if(argcargc=2&=2&4. 4.( (pImgpImg=cvLoadImagecvLoadImage(argv1,0)!=0)(argv1,0)!=0)5. 5. 6. 6. 25.25./ /为为为为cannycanny边缘图像申请空间边缘图像申请空间边缘图像申请空间边缘图像申请空间26.26.pCannyImgpCannyImg=cvCr

14、eateImage(cvGetSize(pImgcvCreateImage(cvGetSize(pImg), ),27.27.IPL_DEPTH_8U,IPL_DEPTH_8U,28.28.1);1);29.29./canny/canny边缘检测边缘检测边缘检测边缘检测30.30.cvCanny(pImgcvCanny(pImg, ,pCannyImgpCannyImg,50,150,3);,50,150,3);31.31./创建窗口创建窗口创建窗口创建窗口33.33.cvNamedWindow(srccvNamedWindow(src,1);,1);34.34.cvNamedWindow(c

15、anny,1);cvNamedWindow(canny,1);35.35. 36.36./显示图像显示图像显示图像显示图像38.38.cvShowImagecvShowImage(srcsrc,pImgpImg););39.39.cvShowImagecvShowImage(canny,(canny,pCannyImgpCannyImg););40.40. 41.41.cvWaitKey(0);/cvWaitKey(0);/等待按键等待按键等待按键等待按键42.42. 43.43./ /销毁窗口销毁窗口销毁窗口销毁窗口44.44.cvDestroyWindowcvDestroyWindow(s

16、rcsrc););25.25.cvDestroyWindowcvDestroyWindow(canny);(canny);26.26./ /释放图像释放图像释放图像释放图像27.27.cvReleaseImagecvReleaseImage(&(&pImgpImg););28.28.cvReleaseImagecvReleaseImage(&(&pCannyImgpCannyImg););29.29. 30.30.return0;return0;31.31. 33.33.return-1;return-1;34.34. Canny边缘检测边缘检测2运行结果:代码:代码:n n#ifdef_CH

17、_#ifdef_CH_n n#pragmapackage#pragmapackagen n#endif#endifn n n n#ifndef_EiC#ifndef_EiCn n#include#includen n#include#includen n#endif#endifn n n ncharwndname=Edge;charwndname=Edge;n nchartbarname=Threshold;chartbarname=Threshold;n n n nIplImage*image=0,*cedge=0,*gray=0,*edge=0;IplImage*image=0,*cedg

18、e=0,*gray=0,*edge=0;n n n n/defineatrackbarcallback/defineatrackbarcallbackn nvoidon_trackbar(inth)voidon_trackbar(inth)n n n ncvSmooth(gray,edge,CV_BLUR,3,3,0,0);cvSmooth(gray,edge,CV_BLUR,3,3,0,0);n ncvNot(gray,edge);cvNot(gray,edge);n n n n/Runtheedgedetectorongrayscale/Runtheedgedetectorongraysc

19、alen ncvCanny(gray,edge,(float)h,(float)h*3,3);cvCanny(gray,edge,(float)h,(float)h*3,3);n n n ncvZero(cedge);cvZero(cedge);n n/copyedgepoints/copyedgepointsn ncvCopy(image,cedge,edge);cvCopy(image,cedge,edge);n n n ncvShowImage(wndname,cedge);cvShowImage(wndname,cedge);n n n nintmain(intargc,char*ar

20、gv)intmain(intargc,char*argv)n n n nchar*filename=argc=2?argv1:(char*);char*filename=argc=2?argv1:(char*);n nintedge_thresh=1;intedge_thresh=1;n nif(image=cvLoadImage(filename,1)=0)if(image=cvLoadImage(filename,1)=0)n nreturn-1;return-1;n n n n/Createtheoutputimage/Createtheoutputimagen ncedge=cvCre

21、ateImage(cvSize(image-width,image-height),cedge=cvCreateImage(cvSize(image-width,image-height),IPL_DEPTH_8U,3);IPL_DEPTH_8U,3);n n n n/Converttograyscale/Converttograyscalen ngray=cvCreateImage(cvSize(image-width,image-height),gray=cvCreateImage(cvSize(image-width,image-height),IPL_DEPTH_8U,1);IPL_D

22、EPTH_8U,1);n nedge=cvCreateImage(cvSize(image-width,image-height),edge=cvCreateImage(cvSize(image-width,image-height),IPL_DEPTH_8U,1);IPL_DEPTH_8U,1);n ncvCvtColor(image,gray,CV_BGR2GRAY);cvCvtColor(image,gray,CV_BGR2GRAY);n n n n/Createawindow/Createawindown ncvNamedWindow(wndname,1);cvNamedWindow(

23、wndname,1);n n n n/createatoolbar/createatoolbarn ncvCreateTrackbar(tbarname,wndname,&edge_thresh,100,on_trackbar);cvCreateTrackbar(tbarname,wndname,&edge_thresh,100,on_trackbar);n n n n/Showtheimage/Showtheimagen non_trackbar(0);on_trackbar(0);n n n n/Waitforakeystroke;thesamefunctionarrangesevents

24、processing/Waitforakeystroke;thesamefunctionarrangeseventsprocessingn ncvWaitKey(0);cvWaitKey(0);n ncvReleaseImage(&image);cvReleaseImage(&image);n ncvReleaseImage(&gray);cvReleaseImage(&gray);n ncvReleaseImage(&edge);cvReleaseImage(&edge);n ncvDestroyWindow(wndname);cvDestroyWindow(wndname);n n n n

25、return0;return0;n n n n n n#ifdef_EiC#ifdef_EiCn nmain(1,edge.c);main(1,edge.c);n n#endif#endifn n 轮廓轮廓(contour)检测检测1. 1./*/*2. 2.*轮廓检测轮廓检测轮廓检测轮廓检测3. 3.*主要函数:主要函数:主要函数:主要函数:4. 4.*cvFindContourscvFindContours5. 5.*cvDrawContourscvDrawContours6. 6.*/*/7. 7. 8. 8./*/*9. 9.*OpenCVOpenCVexampleexample10.

26、10.*By*ByShiqiShiqiYu2006Yu200611.11.*/*/12.12. 13.13.#include#include 14.14.#include#include 15.15.#include#include 16.16. 17.17.intintmain(main(intint argcargc,char*,char*argvargv) )18.18. 1. 1./ /声明声明声明声明IplImageIplImage指针指针指针指针2. 2.IplImageIplImage*pImgpImg=NULL;=NULL;3. 3.IplImageIplImage*pCont

27、ourImgpContourImg=NULL=NULLCvMemStorage*storage=cvCreateMemStorage(0);CvSeq*contour=0;intmode=CV_RETR_EXTERNAL;if(argc=3)if(strcmp(argv2,all)=0)mode=CV_RETR_CCOMP;/内外轮廓都检测内外轮廓都检测/创建窗口创建窗口cvNamedWindow(src,1);cvNamedWindow(contour,1);/载入图像,强制转化为载入图像,强制转化为Grayif(argc=2&(pImg=cvLoadImage(argv1,0)!=0)43

28、.43.cvShowImagecvShowImage(srcsrc,pImgpImg););44.44. 45.45./ /为轮廓显示图像申请空间为轮廓显示图像申请空间为轮廓显示图像申请空间为轮廓显示图像申请空间46.46./3/3通道图像,以便用彩色显示通道图像,以便用彩色显示通道图像,以便用彩色显示通道图像,以便用彩色显示47.47.pContourImgpContourImg=cvCreateImage(cvGetSize(pImgcvCreateImage(cvGetSize(pImg), ),48.48.IPL_DEPTH_8U,IPL_DEPTH_8U,49.49.3);3);50

29、.50./copysourceimageandconvertittoBGRimage/copysourceimageandconvertittoBGRimage51.51.cvCvtColor(pImgcvCvtColor(pImg, ,pContourImgpContourImg,CV_GRAY2BGR);,CV_GRAY2BGR);52.52. 53.53./查找查找查找查找contourcontour55.55.cvFindContourscvFindContours( (pImgpImg,storage,&contour,storage,&contour,sizeof(CvContou

30、rsizeof(CvContour),),56.56.mode,CV_CHAIN_APPROX_SIMPLE);mode,CV_CHAIN_APPROX_SIMPLE);57.57. 58.58. 59.59.elseelse60.60. 61.61./ /销毁窗口销毁窗口销毁窗口销毁窗口43.43.cvDestroyWindowcvDestroyWindow(srcsrc););44.44.cvDestroyWindowcvDestroyWindow(contour);(contour);45.45.cvReleaseMemStorage(&storagecvReleaseMemStorag

31、e(&storage); );46.46. 47.47.return-1;return-1;48.48. 72.72./ /将轮廓画出将轮廓画出 73.73.cvDrawContours(pContourImgcvDrawContours(pContourImg,contour,contour,74.74.CV_RGB(0,0,255),CV_RGB(255,0,0),CV_RGB(0,0,255),CV_RGB(255,0,0),75.75.2,2,8);2,2,8);76.76./ /显示图像显示图像77.77.cvShowImagecvShowImage(contour,(contour

32、,pContourImgpContourImg););78.78. 79.79.cvWaitKey(0);cvWaitKey(0);80.80. 81.81. 82.82./ /销毁窗口销毁窗口83.83.cvDestroyWindowcvDestroyWindow(srcsrc););84.84.cvDestroyWindowcvDestroyWindow(contour);(contour);85.85./ /释放图像释放图像86.86.cvReleaseImagecvReleaseImage(&(&pImgpImg););87.87.cvReleaseImage(&pContourImg

33、);cvReleaseImage(&pContourImg);88.88. 89.89.cvReleaseMemStorage(&storage);cvReleaseMemStorage(&storage);72.72. 73.73.return0;return0;74.74. 75.75. 轮廓轮廓(contour)检测检测2运行结果:代码代码n n#ifdef_CH_#ifdef_CH_n n#pragmapackage#pragmapackagen n#endif#endifn n n n#ifndef_EiC#ifndef_EiCn n#include#includen n#inclu

34、de#includen n#include#includen n#endif#endifn n n n#definew500#definew500n nintlevels=3;intlevels=3;n nCvSeq*contours=0;CvSeq*contours=0;n n n nvoidon_trackbar(intpos)voidon_trackbar(intpos)n n n nIplImage*cnt_img=cvCreateImage(cvSize(w,w),8,3);IplImage*cnt_img=cvCreateImage(cvSize(w,w),8,3);n nCvSe

35、q*_contours=contours;CvSeq*_contours=contours;n nint_levels=levels-3;int_levels=levels-3;n nif(_levels=0)/gettothenearestfacetomakeitlookif(_levelsh_next-h_next-h_next;_contours=_contours-h_next-h_next-h_next;n ncvZero(cnt_img);cvZero(cnt_img);n ncvDrawContours(cnt_img,_contours,CV_RGB(255,0,0),cvDr

36、awContours(cnt_img,_contours,CV_RGB(255,0,0),CV_RGB(0,255,0),_levels,3,CV_AA,cvPoint(0,0);CV_RGB(0,255,0),_levels,3,CV_AA,cvPoint(0,0);n ncvShowImage(contours,cnt_img);cvShowImage(contours,cnt_img);n ncvReleaseImage(&cnt_img);cvReleaseImage(&cnt_img);n n n n n nintmain(intargc,char*argv)intmain(inta

37、rgc,char*argv)n n n ninti,j;inti,j;n nCvMemStorage*storage=cvCreateMemStorage(0);CvMemStorage*storage=cvCreateMemStorage(0);n nIplImage*img=cvCreateImage(cvSize(w,w),8,1);IplImage*img=cvCreateImage(cvSize(w,w),8,1);n n n ncvZero(img);cvZero(img);n n n nfor(i=0;i6;i+)for(i=0;i6;i+)n nintdx=(i%2)*250-

38、30;intdx=(i%2)*250-30;n nintdy=(i/2)*150;intdy=(i/2)*150;n nCvScalarwhite=cvRealScalar(255);CvScalarwhite=cvRealScalar(255);n nCvScalarblack=cvRealScalar(0);CvScalarblack=cvRealScalar(0);n n n nif(i=0)if(i=0)n n n nfor(j=0;j=10;j+)for(j=0;jA11A12b1/m0m1m2=A11A12b1n n/m3m4m5A21A22b2/m3m4m5A21A22b2n n

39、/ /n nCvMatM=cvMat(2,3,CV_32F,m);CvMatM=cvMat(2,3,CV_32F,m);n nintw=src-width;intw=src-width;n ninth=src-height;inth=src-height;n nif(opt)/if(opt)/旋转加缩放旋转加缩放n nfactor=(cos(angle*CV_PI/180.)+1.0)*2;factor=(cos(angle*CV_PI/180.)+1.0)*2;n nelseelsen n/仅仅旋转仅仅旋转n nfactor=1;factor=1;n nm0=(float)(factor*c

40、os(-angle*2*CV_PI/180.);m0=(float)(factor*cos(-angle*2*CV_PI/180.);n nm1=(float)(factor*sin(-angle*2*CV_PI/180.);m1=(float)(factor*sin(-angle*2*CV_PI/180.);n nm3=-m1;m3=-m1;n nm4=m0;m4=m0;n n/将旋转中心移至图像中间将旋转中心移至图像中间n nm2=w*0.5f;m2=w*0.5f;n nm5=h*0.5f;m5=h*0.5f;n n/dst(x,y)=A*src(x,y)+b/dst(x,y)=A*src

41、(x,y)+bn ncvZero(dst);cvZero(dst);n ncvGetQuadrangleSubPix(src,dst,&M);cvGetQuadrangleSubPix(src,dst,&M);n ncvNamedWindow(dst,1);cvNamedWindow(dst,1);n ncvShowImage(dst,dst);cvShowImage(dst,dst);n nif(cvWaitKey(1)=27)/ESCif(cvWaitKey(1)=27)/ESCn nbreak;break;n nangle=(int)(angle+delta)%360;angle=(in

42、t)(angle+delta)%360;n n/for-loop/for-loopn n n nreturn0;return0;n n 读视频文件和运动物体检测读视频文件和运动物体检测n n/*/*n n* *背景建模,运动物体检测背景建模,运动物体检测n n* *n n*/*/n n n n/*/*n n*OpenCVexample*OpenCVexamplen n*ByShiqiYu2006*ByShiqiYu2006n n*/*/n n n n n n#include#includen n n n#include#includen n#include#includen n#include

43、#includen nintmain(intargc,char*argv)intmain(intargc,char*argv)n n n n/ /声明声明IplImageIplImage指针指针n nIplImage*pFrame=NULL;IplImage*pFrame=NULL;n nIplImage*pFrImg=NULL;IplImage*pFrImg=NULL;n nIplImage*pBkImg=NULL;IplImage*pBkImg=NULL;n n n nCvMat*pFrameMat=NULL;CvMat*pFrameMat=NULL;n nCvMat*pFrMat=NUL

44、L;CvMat*pFrMat=NULL;n nCvMat*pBkMat=NULL;CvMat*pBkMat=NULL;n n n nCvCapture*pCapture=NULL;CvCapture*pCapture=NULL;n n n nintnFrmNum=0;intnFrmNum=0;n n n n/创建窗口n ncvNamedWindow(video,1);n ncvNamedWindow(background,1);n ncvNamedWindow(foreground,1);n n/使窗口有序排列n ncvMoveWindow(video,30,0);n ncvMoveWindo

45、w(background,360,0);n ncvMoveWindow(foreground,690,0);n nif(argc2)if(argc2)n n n nfprintf(stderr,Usage:bkgrdvideo_file_namen);fprintf(stderr,Usage:bkgrdvideo_file_namen);n nreturn-1;return-1;n n n n n n/ /打开摄像头打开摄像头n nif(argc=1)if(argc=1)n nif(!(pCapture=cvCaptureFromCAM(-1)if(!(pCapture=cvCaptureFr

46、omCAM(-1)n n n nfprintf(stderr,Cannotopencamera.n);fprintf(stderr,Cannotopencamera.n);n nreturn-2;return-2;n n n n n n/ /打开视频文件打开视频文件n nif(argc=2)if(argc=2)n nif(!(pCapture=cvCaptureFromFile(argv1)if(!(pCapture=cvCaptureFromFile(argv1)n n n nfprintf(stderr,Cannotopenvideofile%sn,argv1);fprintf(stder

47、r,Cannotopenvideofile%sn,argv1);n nreturn-2;return-2;n n n n/ /逐帧读取视频逐帧读取视频n nwhile(pFrame=cvQueryFrame(pCapture)while(pFrame=cvQueryFrame(pCapture)n n n nnFrmNum+;nFrmNum+;n n n n/ /如果是第一帧,需要申请内存,并初始化如果是第一帧,需要申请内存,并初始化n nif(nFrmNum=1)if(nFrmNum=1)n n n npBkImg=cvCreateImage(cvSize(pFrame-width,pFra

48、me-pBkImg=cvCreateImage(cvSize(pFrame-width,pFrame-height),IPL_DEPTH_8U,1);height),IPL_DEPTH_8U,1);n npFrImg=cvCreateImage(cvSize(pFrame-width,pFrame-height),pFrImg=cvCreateImage(cvSize(pFrame-width,pFrame-height),IPL_DEPTH_8U,1);IPL_DEPTH_8U,1);n n n npBkMat=cvCreateMat(pFrame-height,pFrame-width,p

49、BkMat=cvCreateMat(pFrame-height,pFrame-width,CV_32FC1);CV_32FC1);n npFrMat=cvCreateMat(pFrame-height,pFrame-width,pFrMat=cvCreateMat(pFrame-height,pFrame-width,CV_32FC1);CV_32FC1);n npFrameMat=cvCreateMat(pFrame-height,pFrame-width,pFrameMat=cvCreateMat(pFrame-height,pFrame-width,CV_32FC1);CV_32FC1)

50、;n n n n/ /转化成单通道图像再处理转化成单通道图像再处理n ncvCvtColor(pFrame,pBkImg,CV_BGR2GRAY);cvCvtColor(pFrame,pBkImg,CV_BGR2GRAY);n ncvCvtColor(pFrame,pFrImg,CV_BGR2GRAY);cvCvtColor(pFrame,pFrImg,CV_BGR2GRAY);n n n ncvConvert(pFrImg,pFrameMat);cvConvert(pFrImg,pFrameMat);n ncvConvert(pFrImg,pFrMat);cvConvert(pFrImg,p

51、FrMat);n ncvConvert(pFrImg,pBkMat);cvConvert(pFrImg,pBkMat);n n n nelseelsen n n ncvCvtColor(pFrame,pFrImg,CV_BGR2GRAY);cvCvtColor(pFrame,pFrImg,CV_BGR2GRAY);n ncvConvert(pFrImg,pFrameMat);cvConvert(pFrImg,pFrameMat);n n/ /高斯滤波先,以平滑图像高斯滤波先,以平滑图像n n/cvSmooth(pFrameMat,pFrameMat,CV_GAUSSIAN,3,0,0);/cv

52、Smooth(pFrameMat,pFrameMat,CV_GAUSSIAN,3,0,0);n n n n/ /当前帧跟背景图相减当前帧跟背景图相减n ncvAbsDiff(pFrameMat,pBkMat,pFrMat);cvAbsDiff(pFrameMat,pBkMat,pFrMat);n n/二值化前景图n ncvThreshold(pFrMat,pFrImg,60,255.0,CV_THRESH_BINARY);n nn n/进行形态学滤波,去掉噪音n n/cvErode(pFrImg,pFrImg,0,1);n n/cvDilate(pFrImg,pFrImg,0,1);n nn

53、n/更新背景n ncvRunningAvg(pFrameMat,pBkMat,0.003,0);n n/将背景转化为图像格式,用以显示n ncvConvert(pBkMat,pBkImg);n nn nn n/ /显示图像显示图像n ncvShowImage(video,pFrame);cvShowImage(video,pFrame);n ncvShowImage(background,pBkImg);cvShowImage(background,pBkImg);n ncvShowImage(foreground,pFrImg);cvShowImage(foreground,pFrImg);

54、n n n n/ /如果有按键事件,则跳出循环如果有按键事件,则跳出循环n n/ /此等待也为此等待也为cvShowImagecvShowImage函数提供时间完成显示函数提供时间完成显示n n/ /等待时间可以根据等待时间可以根据CPUCPU速度调整速度调整n nif(cvWaitKey(2)=0)if(cvWaitKey(2)=0)n nbreak;break;n n n n n n n n n n n n n n/ /销毁窗口销毁窗口n ncvDestroyWindow(video);cvDestroyWindow(video);n ncvDestroyWindow(background

55、);cvDestroyWindow(background);n ncvDestroyWindow(foreground);cvDestroyWindow(foreground);n n n n/ /释放图像和矩阵释放图像和矩阵n ncvReleaseImage(&pFrImg);cvReleaseImage(&pFrImg);n ncvReleaseImage(&pBkImg);cvReleaseImage(&pBkImg);n n n ncvReleaseMat(&pFrameMat);cvReleaseMat(&pFrameMat);n ncvReleaseMat(&pFrMat);cvR

56、eleaseMat(&pFrMat);n ncvReleaseMat(&pBkMat);cvReleaseMat(&pBkMat);n n n ncvReleaseCapture(&pCapture);cvReleaseCapture(&pCapture);n n n nreturn0;return0;n n n n Hough线段检测线段检测n n检测结果:n n/*Thisisastandaloneprogram.Passanimagenameasafirst/*Thisisastandaloneprogram.Passanimagenameasafirstparameterofthepr

57、ogram.parameteroftheprogram.n nSwitchbetweenstandardandprobabilisticHoughtransformSwitchbetweenstandardandprobabilisticHoughtransformbychanging#if1to#if0andback*/bychanging#if1to#if0andback*/n n#include#includen n#include#includen n#include#includen n n nintmain(intargc,char*argv)intmain(intargc,cha

58、r*argv)n n n nconstchar*filename=argc=2?argv1:pic1.png;constchar*filename=argc=2?argv1:pic1.png;n nIplImage*src=cvLoadImage(filename,0);IplImage*src=cvLoadImage(filename,0);n nIplImage*dst;IplImage*dst;n nIplImage*color_dst;IplImage*color_dst;n nCvMemStorage*storage=cvCreateMemStorage(0);CvMemStorag

59、e*storage=cvCreateMemStorage(0);n nCvSeq*lines=0;CvSeq*lines=0;n ninti;inti;n n n nif(!src)if(!src)n nreturn-1;return-1;n n n ndst=cvCreateImage(cvGetSize(src),8,1);dst=cvCreateImage(cvGetSize(src),8,1);n ncolor_dst=cvCreateImage(cvGetSize(src),8,3);color_dst=cvCreateImage(cvGetSize(src),8,3);n n n

60、ncvCanny(src,dst,50,200,3);cvCanny(src,dst,50,200,3);n ncvCvtColor(dst,color_dst,CV_GRAY2BGR);cvCvtColor(dst,color_dst,CV_GRAY2BGR);n n#if0#if0n nlines=cvHoughLines2(dst,storage,CV_HOUGH_STANDARD,1,lines=cvHoughLines2(dst,storage,CV_HOUGH_STANDARD,1,n nCV_PI/180,100,0,0);CV_PI/180,100,0,0);n n n nfo

61、r(i=0;itotal,100);i+)for(i=0;itotal,100);i+)n n n nfloat*line=(float*)cvGetSeqElem(lines,i);float*line=(float*)cvGetSeqElem(lines,i);n nfloatrho=line0;floatrho=line0;n nfloattheta=line1;floattheta=line1;n nCvPointpt1,pt2;CvPointpt1,pt2;n ndoublea=cos(theta),b=sin(theta);doublea=cos(theta),b=sin(thet

62、a);n ndoublex0=a*rho,y0=b*rho;doublex0=a*rho,y0=b*rho;n npt1.x=cvRound(x0+1000*(-b);pt1.x=cvRound(x0+1000*(-b);n npt1.y=cvRound(y0+1000*(a);pt1.y=cvRound(y0+1000*(a);n npt2.x=cvRound(x0-1000*(-b);pt2.x=cvRound(x0-1000*(-b);n npt2.y=cvRound(y0-1000*(a);pt2.y=cvRound(y0-1000*(a);n ncvLine(color_dst,pt

63、1,pt2,CV_RGB(255,0,0),3,CV_AA,0);cvLine(color_dst,pt1,pt2,CV_RGB(255,0,0),3,CV_AA,0);n n n n#else#elsen nlines=cvHoughLines2(dst,storage,CV_HOUGH_PROBABILISTIC,1,lines=cvHoughLines2(dst,storage,CV_HOUGH_PROBABILISTIC,1,CV_PI/180,50,50,10);CV_PI/180,50,50,10);n nfor(i=0;itotal;i+)for(i=0;itotal;i+)n

64、nCvPoint*line=(CvPoint*)cvGetSeqElem(lines,i);CvPoint*line=(CvPoint*)cvGetSeqElem(lines,i);n ncvLine(color_dst,line0,line1,CV_RGB(255,0,0),3,CV_AA,0);cvLine(color_dst,line0,line1,CV_RGB(255,0,0),3,CV_AA,0);n n#endif#endifn ncvNamedWindow(Source,1);cvNamedWindow(Source,1);n ncvShowImage(Source,src);c

65、vShowImage(Source,src);n n n ncvNamedWindow(Hough,1);cvNamedWindow(Hough,1);n ncvShowImage(Hough,color_dst);cvShowImage(Hough,color_dst);n n n ncvWaitKey(0);cvWaitKey(0);n n n nreturn0;return0;n n 鼠标绘图鼠标绘图n n#ifdef_CH_n n#pragmapackagen n#endifn nn n#includen n#includen n#includen n#includen nn nIpl

66、Image*inpaint_mask=0;n nIplImage*img0=0,*img=0,*inpainted=0;n nCvPointprev_pt=-1,-1;n nvoidon_mouse(intevent,intx,inty,intflags,void*zhang)voidon_mouse(intevent,intx,inty,intflags,void*zhang)n n n nif(!img)if(!img)n nreturn;return;n n n nif(event=CV_EVENT_LBUTTONUP|!(flags&if(event=CV_EVENT_LBUTTONU

67、P|!(flags&CV_EVENT_FLAG_LBUTTON)CV_EVENT_FLAG_LBUTTON)n nprev_pt=cvPoint(-1,-1);prev_pt=cvPoint(-1,-1);n nelseif(event=CV_EVENT_LBUTTONDOWN)elseif(event=CV_EVENT_LBUTTONDOWN)n nprev_pt=cvPoint(x,y);prev_pt=cvPoint(x,y);n nelseif(event=CV_EVENT_MOUSEMOVE&(flags&elseif(event=CV_EVENT_MOUSEMOVE&(flags&

68、CV_EVENT_FLAG_LBUTTON)CV_EVENT_FLAG_LBUTTON)n n n nCvPointpt=cvPoint(x,y);CvPointpt=cvPoint(x,y);n nif(0)if(=2?argv1:(char*);char*filename=argc=2?argv1:(char*);n n n nif(img0=cvLoadImage(filename,-1)=0)if(img0=cvLoadImage(filename,-1)=0)n nreturn0;return0;n n n nprintfprintf(Hotkeys:n(Hotkeys:nn ntE

69、SC-quittheprogramntESC-quittheprogramnn ntr-restoretheoriginalimagentr-restoretheoriginalimagenn ntiorENTER-runinpaintingalgorithmntiorENTER-runinpaintingalgorithmnn ntt(beforerunningit,paintsomethingontheimage)n);tt(beforerunningit,paintsomethingontheimage)n);n n n ncvNamedWindow(image,1);cvNamedWi

70、ndow(image,1);n n n nimg=cvCloneImage(img0);img=cvCloneImage(img0);n ninpainted=cvCloneImage(img0);inpainted=cvCloneImage(img0);n ninpaint_mask=cvCreateImage(cvGetSize(img),8,1);inpaint_mask=cvCreateImage(cvGetSize(img),8,1);n n n ncvZero(inpaint_mask);cvZero(inpaint_mask);n ncvZero(inpainted);cvZer

71、o(inpainted);n ncvShowImage(image,img);cvShowImage(image,img);n ncvShowImage(watershedtransform,inpainted);cvShowImage(watershedtransform,inpainted);n ncvSetMouseCallback(image,on_mouse,0);cvSetMouseCallback(image,on_mouse,0);n nfor(;)for(;)n n n nintc=cvWaitKey(0);intc=cvWaitKey(0);n nif(char)c=27)

72、if(char)c=27)n nbreak;break;n n n nif(char)c=r)if(char)c=r)n n n ncvZero(inpaint_mask);cvZero(inpaint_mask);n ncvCopy(img0,img,0);cvCopy(img0,img,0);n ncvShowImage(image,img);cvShowImage(image,img);n n n n n nif(char)c=i|(char)c=n)if(char)c=i|(char)c=n)n n n ncvNamedWindow(inpaintedimage,1);cvNamedW

73、indow(inpaintedimage,1);n ncvInpaint(img,inpaint_mask,inpainted,3,CV_INPAINT_TELEA);cvInpaint(img,inpaint_mask,inpainted,3,CV_INPAINT_TELEA);n ncvShowImage(inpaintedimage,inpainted);cvShowImage(inpaintedimage,inpainted);n n n n n nreturn1;return1;n n n n Snake轮廓例子n nopencvopencv例子里没有提供例子里没有提供cvsnake

74、imagecvsnakeimage的使用的使用方法,在此整理一个例子,可以形象的看看方法,在此整理一个例子,可以形象的看看snakesnake算法的结果,大致做法是:算法的结果,大致做法是: n n首先设定域值分割,把基本的轮廓找出来,首先设定域值分割,把基本的轮廓找出来,见图中蓝色轮廓线,再将轮廓点传入见图中蓝色轮廓线,再将轮廓点传入cvSnakeImagecvSnakeImage函数,计算出绿色的函数,计算出绿色的snakesnake轮廓轮廓线。线。 n n其中参数其中参数alphaalpha代表点相互靠拢的权值代表点相互靠拢的权值(0-1.0)(0-1.0),betabeta表示弯曲能量

75、(越小越容易弯曲)表示弯曲能量(越小越容易弯曲)(0-(0-1.0)1.0),gammagamma表示整体能量表示整体能量(0-1.0)(0-1.0)。其中参。其中参数我自己也不确定具体的范围,最好自己更数我自己也不确定具体的范围,最好自己更改不同的范围试试改不同的范围试试. .程序运行结果/:/:定义控制台应用程序的入口点。定义控制台应用程序的入口点。/#include/#include#include#include#include#include#include#include#include#include#include#include#include#includeIplImage

76、*image=0;/IplImage*image=0;/原始图像原始图像 IplImage*image2=0;/IplImage*image2=0;/原始图像原始图像copyusingnamespacestd;copyusingnamespacestd;intThresholdness=141;intThresholdness=141;intialpha=20;intialpha=20;intibeta=20;intibeta=20;intigamma=20;intigamma=20; voidonChange(intpos)voidonChange(intpos)if(image2)if(i

77、mage2)cvReleaseImage(&image2);cvReleaseImage(&image2);if(image)if(image)cvReleaseImage(&image);cvReleaseImage(&image);image2=cvLoadImage(“grey.bmp”,1);/image2=cvLoadImage(“grey.bmp”,1);/显示图片显示图片image=cvLoadImage(“grey.bmp”,0);image=cvLoadImage(“grey.bmp”,0);cvThreshold(image,image,Thresholdness,255,

78、CV_THREScvThreshold(image,image,Thresholdness,255,CV_THRESH_BINARY);/H_BINARY);/分割域值分割域值CvMemStorage*storage=cvCreateMemStorage(0);CvMemStorage*storage=cvCreateMemStorage(0);CvSeq*contours=0;CvSeq*contours=0;cvFindContours(image,storage,&contours,cvFindContours(image,storage,&contours,sizeof(CvConto

79、ur),/sizeof(CvContour),/寻找初始化轮廓寻找初始化轮廓 CV_RETR_EXTERNAL,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);CV_CHAIN_APPROX_SIMPLE);cvFindContours(image,storage,&contours,sizeof(CvContour),cvFindContours(image,storage,&contours,sizeof(CvContour),/ /寻找初始化轮廓寻找初始化轮廓 CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);CV_RET

80、R_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);if(!contours)if(!contours)return;return;intlength=contours-total;intlength=contours-total;if(length10)return;if(length10)return;CvPoint*point=newCvPointlength;/CvPoint*point=newCvPointlength;/分配轮廓点分配轮廓点CCvSeqReaderreader;vSeqReaderreader;CvPointpt=cvPoint(0,0);CvPo

81、intpt=cvPoint(0,0);CvSeq*contour2=contours;CvSeq*contour2=contours;cvStartReadSeq(contour2,&reader);cvStartReadSeq(contour2,&reader);for(inti=0;ilength;i+)for(inti=0;ilength;i+)CV_READ_SEQ_ELEM(pt,reader);CV_READ_SEQ_ELEM(pt,reader);pointi=pt;pointi=pt;cvReleaseMemStorage(&storage);cvReleaseMemStora

82、ge(&storage);/ /显示轮廓曲线显示轮廓曲线 for(inti=0;ilength;i+)for(inti=0;ilength;i+)intj=(i+1)%length;intj=(i+1)%length;cvLine(image2,pointi,pointj,CV_RGB(0,0,255),1,8,0);cvLine(image2,pointi,pointj,CV_RGB(0,0,255),1,8,0);floatalpha=ialpha/100.0f;floatalpha=ialpha/100.0f;floatbeta=ibeta/100.0f;floatgamma=igamm

83、a/100.0f;CvSizesize;floatbeta=ibeta/100.0f;floatgamma=igamma/100.0f;CvSizesize;=3;=3;=3;=3;CvTermCriteriacriteria;=CV_TERMCRIT_ITER;=1000;CvTermCriteriacriteria;=CV_TERMCRIT_ITER;=1000;=0.1;=0.1;cvSnakeImage(image,cvSnakeImage(image,point,length,&alpha,&beta,&gamma,CV_VALUE,size,criteria,0);point,le

84、ngth,&alpha,&beta,&gamma,CV_VALUE,size,criteria,0);/ /显示曲线显示曲线for(inti=0;ilength;i+)for(inti=0;ilength;i+)intj=(i+1)%length;intj=(i+1)%length;cvLine(image2,pointi,pointj,CV_RGB(0,255,0),1,8,0);cvLine(image2,pointi,pointj,CV_RGB(0,255,0),1,8,0);deletepoint;deletepoint;intmain(intargc,char*argv)intmai

85、n(intargc,char*argv)cvNamedWindow(win1,0);cvNamedWindow(win1,0);cvCreateTrackbar(Thd,win1,&Thresholdness,255,onChange);cvCreateTrackbar(Thd,win1,&Thresholdness,255,onChange);cvCreateTrackbar(alpha,win1,&ialpha,100,onChange);cvCreateTrackbar(alpha,win1,&ialpha,100,onChange);cvCreateTrackbar(beta,win1

86、,&ibeta,100,onChange);cvCreateTrackbar(beta,win1,&ibeta,100,onChange);cvCreateTrackbar(gamma,win1,&igamma,100,onChange);cvCreateTrackbar(gamma,win1,&igamma,100,onChange);cvResizeWindow(win1,300,500);cvResizeWindow(win1,300,500);onChange(0);onChange(0);for(;)for(;) if(cvWaitKey(40)=27)break;cvShowIma

87、ge(win1,image2);if(cvWaitKey(40)=27)break;cvShowImage(win1,image2); return0;return0; 离散傅立叶变换(DFT)Lena灰度图像的结果:n n#include#includen n#include#includen n#include#includen n n n/RearrangethequadrantsofFourierimagesothattheoriginisat/RearrangethequadrantsofFourierimagesothattheoriginisatn n/theimagecente

88、r/theimagecentern n/src&dstarraysofequalsize&type/src&dstarraysofequalsize&typen nvoidcvShiftDFT(CvArr*src_arr,CvArr*dst_arr)voidcvShiftDFT(CvArr*src_arr,CvArr*dst_arr)n n n nCvMat*tmp;CvMat*tmp;n nCvMatq1stub,q2stub;CvMatq1stub,q2stub;n nCvMatq3stub,q4stub;CvMatq3stub,q4stub;n nCvMatd1stub,d2stub;C

89、vMatd1stub,d2stub;n nCvMatd3stub,d4stub;CvMatd3stub,d4stub;n nCvMat*q1,*q2,*q3,*q4;CvMat*q1,*q2,*q3,*q4;n nCvMat*d1,*d2,*d3,*d4;CvMat*d1,*d2,*d3,*d4;n n n nCvSizesize=cvGetSize(src_arr);CvSizesize=cvGetSize(src_arr);n nCvSizedst_size=cvGetSize(dst_arr);CvSizedst_size=cvGetSize(dst_arr);n nintcx,cy;i

90、ntcx,cy;n n!=|!=|n n!=)!=)n ncvError(CV_StsUnmatchedSizes,cvShiftDFT,SourceandDestinationcvError(CV_StsUnmatchedSizes,cvShiftDFT,SourceandDestinationn narraysmusthaveequalsizes,_FILE_,_LINE_);arraysmusthaveequalsizes,_FILE_,_LINE_);n n n n n nif(src_arr=dst_arr)if(src_arr=dst_arr)n ntmp=cvCreateMat(

91、size.height/2,size.width/2,cvGetElemType(src_arr);tmp=cvCreateMat(size.height/2,size.width/2,cvGetElemType(src_arr);n n n n n ncx=size.width/2;cx=size.width/2;n ncy=size.height/2;/imagecentercy=size.height/2;/imagecentern n n nq1=cvGetSubRect(src_arr,&q1stub,cvRect(0,0,cx,cy);q1=cvGetSubRect(src_arr

92、,&q1stub,cvRect(0,0,cx,cy);n nq2=cvGetSubRect(src_arr,&q2stub,cvRect(cx,0,cx,cy);q2=cvGetSubRect(src_arr,&q2stub,cvRect(cx,0,cx,cy);n nq3=cvGetSubRect(src_arr,&q3stub,cvRect(cx,cy,cx,cy);q3=cvGetSubRect(src_arr,&q3stub,cvRect(cx,cy,cx,cy);n nq4=cvGetSubRect(src_arr,&q4stub,cvRect(0,cy,cx,cy);q4=cvGe

93、tSubRect(src_arr,&q4stub,cvRect(0,cy,cx,cy);n nd1=cvGetSubRect(src_arr,&d1stub,cvRect(0,0,cx,cy);d1=cvGetSubRect(src_arr,&d1stub,cvRect(0,0,cx,cy);n nd2=cvGetSubRect(src_arr,&d2stub,cvRect(cx,0,cx,cy);d2=cvGetSubRect(src_arr,&d2stub,cvRect(cx,0,cx,cy);n nd3=cvGetSubRect(src_arr,&d3stub,cvRect(cx,cy,

94、cx,cy);d3=cvGetSubRect(src_arr,&d3stub,cvRect(cx,cy,cx,cy);n nd4=cvGetSubRect(src_arr,&d4stub,cvRect(0,cy,cx,cy);d4=cvGetSubRect(src_arr,&d4stub,cvRect(0,cy,cx,cy);n nif(src_arr!=dst_arr)if(src_arr!=dst_arr)n nif(!CV_ARE_TYPES_EQ(q1,d1)if(!CV_ARE_TYPES_EQ(q1,d1)n ncvError(CV_StsUnmatchedFormats,cvSh

95、iftDFT,SourceandDestinationarrayscvError(CV_StsUnmatchedFormats,cvShiftDFT,SourceandDestinationarraysmusthavethesameformat,_FILE_,_LINE_);musthavethesameformat,_FILE_,_LINE_);n n n ncvCopy(q3,d1,0);cvCopy(q3,d1,0);n ncvCopy(q4,d2,0);cvCopy(q4,d2,0);n ncvCopy(q1,d3,0);cvCopy(q1,d3,0);n ncvCopy(q2,d4,

96、0);cvCopy(q2,d4,0);n n n nelseelsen ncvCopy(q3,tmp,0);cvCopy(q3,tmp,0);n ncvCopy(q1,q3,0);cvCopy(q1,q3,0);n ncvCopy(tmp,q1,0);cvCopy(tmp,q1,0);n ncvCopy(q4,tmp,0);cvCopy(q4,tmp,0);n ncvCopy(q2,q4,0);cvCopy(q2,q4,0);n ncvCopy(tmp,q2,0);cvCopy(tmp,q2,0);n n n n n nintmain(intargc,char*argv)intmain(int

97、argc,char*argv)n n n nconstchar*filename=argc=2?argv1:;constchar*filename=argc=2?argv1:;n nIplImage*im;IplImage*im;n n n nIplImage*realInput;IplImage*realInput;n nIplImage*imaginaryInput;IplImage*imaginaryInput;n nIplImage*complexInput;IplImage*complexInput;n nintdft_M,dft_N;intdft_M,dft_N;n nCvMat*

98、dft_A,tmp;CvMat*dft_A,tmp;n nIplImage*image_Re;IplImage*image_Re;n nIplImage*image_Im;IplImage*image_Im;n ndoublem,M;doublem,M;n n n nim=cvLoadImage(filename,CV_LOAD_IMAGE_GRAYSCALE);im=cvLoadImage(filename,CV_LOAD_IMAGE_GRAYSCALE);n nif(!im)if(!im)n nreturn-1;return-1;n nrealInput=cvCreateImage(cvG

99、etSize(im),IPL_DEPTH_64F,1);realInput=cvCreateImage(cvGetSize(im),IPL_DEPTH_64F,1);n nimaginaryInput=cvCreateImage(cvGetSize(im),IPL_DEPTH_64F,imaginaryInput=cvCreateImage(cvGetSize(im),IPL_DEPTH_64F,1);1);n ncomplexInput=cvCreateImage(cvGetSize(im),IPL_DEPTH_64F,complexInput=cvCreateImage(cvGetSize

100、(im),IPL_DEPTH_64F,2);2);n n n ncvScale(im,realInput,1.0,0.0);cvScale(im,realInput,1.0,0.0);n ncvZero(imaginaryInput);cvZero(imaginaryInput);n ncvMerge(realInput,imaginaryInput,NULL,NULL,complexInput);cvMerge(realInput,imaginaryInput,NULL,NULL,complexInput);n n n ndft_M=cvGetOptimalDFTSize(im-height

101、-1);dft_M=cvGetOptimalDFTSize(im-height-1);n ndft_N=cvGetOptimalDFTSize(im-width-1);dft_N=cvGetOptimalDFTSize(im-width-1);n n n ndft_A=cvCreateMat(dft_M,dft_N,CV_64FC2);dft_A=cvCreateMat(dft_M,dft_N,CV_64FC2);n nimage_Re=cvCreateImage(cvSize(dft_N,dft_M),image_Re=cvCreateImage(cvSize(dft_N,dft_M),IP

102、L_DEPTH_64F,1);IPL_DEPTH_64F,1);n nimage_Im=cvCreateImage(cvSize(dft_N,dft_M),image_Im=cvCreateImage(cvSize(dft_N,dft_M),IPL_DEPTH_64F,1);IPL_DEPTH_64F,1);n n/copyAtodft_Aandpaddft_Awithzeros/copyAtodft_Aandpaddft_Awithzerosn ncvGetSubRect(dft_A,&tmp,cvRect(0,0,im-width,im-height);cvGetSubRect(dft_A

103、,&tmp,cvRect(0,0,im-width,im-height);n ncvCopy(complexInput,&tmp,NULL);cvCopy(complexInput,&tmp,NULL);n nif(dft_A-colsim-width)if(dft_A-colsim-width)n n n ncvGetSubRect(dft_A,&tmp,cvRect(im-width,0,dft_A-cols-im-width,im-cvGetSubRect(dft_A,&tmp,cvRect(im-width,0,dft_A-cols-im-width,im-height);height

104、);n ncvZero(&tmp);cvZero(&tmp);n n n n n n/noneedtopadbottompartofdft_Awithzerosbecauseof/noneedtopadbottompartofdft_Awithzerosbecauseofn n/usenonzero_rowsparameterincvDFT()callbelow/usenonzero_rowsparameterincvDFT()callbelown n n ncvDFT(dft_A,dft_A,CV_DXT_FORWARD,complexInput-height);cvDFT(dft_A,df

105、t_A,CV_DXT_FORWARD,complexInput-height);n n n ncvNamedWindow(win,0);cvNamedWindow(win,0);n ncvNamedWindow(magnitude,0);cvNamedWindow(magnitude,0);n ncvShowImage(win,im);cvShowImage(win,im);n n n n/SplitFourierinrealandimaginaryparts/SplitFourierinrealandimaginarypartsn ncvSplit(dft_A,image_Re,image_

106、Im,0,0);cvSplit(dft_A,image_Re,image_Im,0,0);n n n n/ComputethemagnitudeofthespectrumMag=sqrt(Re2+Im2)/ComputethemagnitudeofthespectrumMag=sqrt(Re2+Im2)n ncvPow(image_Re,image_Re,2.0);cvPow(image_Re,image_Re,2.0);n ncvPow(image_Im,image_Im,2.0);cvPow(image_Im,image_Im,2.0);n ncvAdd(image_Re,image_Im

107、,image_Re,NULL);cvAdd(image_Re,image_Im,image_Re,NULL);n ncvPow(image_Re,image_Re,0.5);cvPow(image_Re,image_Re,0.5);n n n n/Computelog(1+Mag)/Computelog(1+Mag)n ncvAddS(image_Re,cvScalarAll(1.0),image_Re,NULL);/1+MagcvAddS(image_Re,cvScalarAll(1.0),image_Re,NULL);/1+Magn ncvLog(image_Re,image_Re);/l

108、og(1+Mag)cvLog(image_Re,image_Re);/log(1+Mag)n n n n n n/RearrangethequadrantsofFourierimagesothattheoriginisat/RearrangethequadrantsofFourierimagesothattheoriginisatn n/theimagecenter/theimagecentern ncvShiftDFT(image_Re,image_Re);cvShiftDFT(image_Re,image_Re);n n n ncvMinMaxLoc(image_Re,&m,&M,NULL

109、,NULL,NULL);cvMinMaxLoc(image_Re,&m,&M,NULL,NULL,NULL);n ncvScale(image_Re,image_Re,1.0/(M-m),1.0*(-m)/(M-m);cvScale(image_Re,image_Re,1.0/(M-m),1.0*(-m)/(M-m);n ncvShowImage(magnitude,image_Re);cvShowImage(magnitude,image_Re);n n n ncvWaitKey(-1);cvWaitKey(-1);n nreturn0;return0;n n 人脸检测人脸检测本程序可以对输

110、入的图像或者视频进行人脸检测,运行结果如下图:本程序可以对输入的图像或者视频进行人脸检测,运行结果如下图: n n#include#includen n#include#includen n n n#include#includen n#include#includen n#include#includen n#include#includen n#include#includen n#include#includen n#include#includen n#include#includen n#include#includen n n n#ifdef_EiC#ifdef_EiCn n#de

111、fineWIN32#defineWIN32n n#endif#endifn nstaticCvMemStorage*storage=0;staticCvMemStorage*storage=0;n nstaticCvHaarClassifierCascade*cascade=0;staticCvHaarClassifierCascade*cascade=0;n n n nvoiddetect_and_draw(IplImage*image);voiddetect_and_draw(IplImage*image);n n n nconstchar*cascade_name=constchar*c

112、ascade_name=n n;n n/*;*/*;*/n nintmain(intargc,char*argv)intmain(intargc,char*argv)n n n nCvCapture*capture=0;CvCapture*capture=0;n nIplImage*frame,*frame_copy=0;IplImage*frame,*frame_copy=0;n nintoptlen=strlen(-cascade=);intoptlen=strlen(-cascade=);n nconstchar*input_name;constchar*input_name;n n n

113、 nif(argc1&strncmp(argv1,-cascade=,optlen)=0)if(argc1&strncmp(argv1,-cascade=,optlen)=0)n n n ncascade_name=argv1+optlen;cascade_name=argv1+optlen;n ninput_name=argc2?argv2:0;input_name=argc2?argv2:0;n n n nelseelsen n n ncascade_name=././data/haarcascades/haarcascade_frontalface_alt2.xml;cascade_na

114、me=././data/haarcascades/haarcascade_frontalface_alt2.xml;n ninput_name=argc1?argv1:0;input_name=argc1?argv1:0;n n n n n ncascade=(CvHaarClassifierCascade*)cvLoad(cascade_name,0,0,0);cascade=(CvHaarClassifierCascade*)cvLoad(cascade_name,0,0,0);n nif(!cascade)if(!cascade)n n n nfprintf(stderr,ERROR:C

115、ouldnotloadclassifiercascaden);fprintf(stderr,ERROR:Couldnotloadclassifiercascaden);n nfprintf(stderr,fprintf(stderr,n nUsage:facedetect-cascade=Usage:facedetect-cascade=filename|camera_indexn);filename|camera_indexn);n nreturn-1;return-1;n n n nstorage=cvCreateMemStorage(0);storage=cvCreateMemStora

116、ge(0);n n n nif(!input_name|(isdigit(input_name0)&input_name1=0)if(!input_name|(isdigit(input_name0)&input_name1=0)n ncapture=cvCaptureFromCAM(!input_name?0:input_name0-0capture=cvCaptureFromCAM(!input_name?0:input_name0-0); );n nelseelsen ncapture=cvCaptureFromAVI(input_name);capture=cvCaptureFromA

117、VI(input_name);n n n ncvNamedWindow(result,1);cvNamedWindow(result,1);n nif(capture)if(capture)n nfor(;)for(;)n nif(!cvGrabFrame(capture)if(!cvGrabFrame(capture)n nbreak;break;n nframe=cvRetrieveFrame(capture);frame=cvRetrieveFrame(capture);n nif(!frame)if(!frame)n nbreak;break;n nif(!frame_copy)if(

118、!frame_copy)n nframe_copy=cvCreateImage(cvSize(frame-width,frame-height),frame_copy=cvCreateImage(cvSize(frame-width,frame-height),n nIPL_DEPTH_8U,frame-nChannels);IPL_DEPTH_8U,frame-nChannels);n nif(frame-origin=IPL_ORIGIN_TL)if(frame-origin=IPL_ORIGIN_TL)n ncvCopy(frame,frame_copy,0);cvCopy(frame,

119、frame_copy,0);n nelseelsen ncvFlip(frame,frame_copy,0);cvFlip(frame,frame_copy,0);n n n ndetect_and_draw(frame_copy);detect_and_draw(frame_copy);n n n nif(cvWaitKey(10)=0)if(cvWaitKey(10)=0)n nbreak;break;n n n ncvReleaseImage(&frame_copy);cvReleaseImage(&frame_copy);n ncvReleaseCapture(&capture);cv

120、ReleaseCapture(&capture);n n n nelseelsen n n nconstchar*filename=input_name?input_name:(char*);constchar*filename=input_name?input_name:(char*);n nIplImage*image=cvLoadImage(filename,1);IplImage*image=cvLoadImage(filename,1);n n n nif(image)detect_and_draw(image);if(image)detect_and_draw(image);n n

121、cvWaitKey(0);cvWaitKey(0);n ncvReleaseImage(&image);cvReleaseImage(&image);n n n nElseElsen n n n/*assumeitisatextfilecontainingthe/*assumeitisatextfilecontainingthen nlistoftheimagefilenamestobeprocessed-oneperline*/listoftheimagefilenamestobeprocessed-oneperline*/n nFILE*f=fopen(filename,rt);FILE*

122、f=fopen(filename,rt);n nif(f)if(f)n ncharbuf1000+1;charbuf1000+1;n nwhile(fgets(buf,1000,f)while(fgets(buf,1000,f)n nintlen=(int)strlen(buf);intlen=(int)strlen(buf);n nwhile(len0&isspace(buflen-1)while(len0&isspace(buflen-1)n nlen-;len-;n nbuflen=0;buflen=0;n nimage=cvLoadImage(buf,1);image=cvLoadIm

123、age(buf,1);n nif(image)if(image)n ndetect_and_draw(image);detect_and_draw(image);n ncvWaitKey(0);cvWaitKey(0);n ncvReleaseImage(&image);cvReleaseImage(&image);n nn nn nfclose(f);fclose(f);n nn nn n n ncvDestroyWindow(result);cvDestroyWindow(result);n n n nreturn0;return0;n n n nvoiddetect_and_draw(I

124、plImage*img)voiddetect_and_draw(IplImage*img)n n n nstaticCvScalarcolors=staticCvScalarcolors=n n n n0,0,255,0,0,255,n n0,128,255,0,128,255,n n0,255,255,0,255,255,n n0,255,0,0,255,0,n n255,128,0,255,128,0,n n255,255,0,255,255,0,n n255,0,0,255,0,0,n n255,0,255255,0,255n n; ;n n n ndoublescale=1.3;dou

125、blescale=1.3;n nIplImage*gray=cvCreateImage(cvSize(img-width,img-IplImage*gray=cvCreateImage(cvSize(img-width,img-height),8,1);height),8,1);n nIplImage*small_img=cvCreateImage(cvSize(cvRoundIplImage*small_img=cvCreateImage(cvSize(cvRound(img-width/scale),(img-width/scale),n ncvRound(img-height/scale

126、),cvRound(img-height/scale),n n8,1);8,1);n ninti;inti;n n n ncvCvtColor(img,gray,CV_BGR2GRAY);cvCvtColor(img,gray,CV_BGR2GRAY);n ncvResize(gray,small_img,CV_INTER_LINEAR);cvResize(gray,small_img,CV_INTER_LINEAR);n ncvEqualizeHist(small_img,small_img);cvEqualizeHist(small_img,small_img);n ncvClearMem

127、Storage(storage);cvClearMemStorage(storage);n nif(cascade)if(cascade)n n n ndoublet=(double)cvGetTickCount();doublet=(double)cvGetTickCount();n nCvSeq*faces=cvHaarDetectObjects(small_img,cascade,storage,CvSeq*faces=cvHaarDetectObjects(small_img,cascade,storage,n n1.1,2,0/*CV_HAAR_DO_CANNY_PRUNING*/,

128、1.1,2,0/*CV_HAAR_DO_CANNY_PRUNING*/,n ncvSize(30,30);cvSize(30,30);n nt=(double)cvGetTickCount()-t;t=(double)cvGetTickCount()-t;n nprintfprintf(detectiontime=%gmsn,t/(double)cvGetTickFrequency()*1000.);(detectiontime=%gmsn,t/(double)cvGetTickFrequency()*1000.);n nfor(i=0;itotal:0);i+)for(i=0;itotal:

129、0);i+)n n n nCvRect*r=(CvRect*)cvGetSeqElem(faces,i);CvRect*r=(CvRect*)cvGetSeqElem(faces,i);n nCvPointcenter;CvPointcenter;n nintradius;intradius;n n=cvRound(r-x+r-width*0.5)*scale);=cvRound(r-x+r-width*0.5)*scale);n n=cvRound(r-y+r-height*0.5)*scale);=cvRound(r-y+r-height*0.5)*scale);n nradius=cvR

130、ound(r-width+r-height)*0.25*scale);radius=cvRound(r-width+r-height)*0.25*scale);n ncvCircle(img,center,radius,colorsi%8,3,8,0);cvCircle(img,center,radius,colorsi%8,3,8,0);n n n n n n n ncvShowImage(result,img);cvShowImage(result,img);n ncvReleaseImage(&gray);cvReleaseImage(&gray);n ncvReleaseImage(&

131、small_img);cvReleaseImage(&small_img);n n QR分解分解n n#include#includen n#include#includen n#include#includen nusingnamespacestd;usingnamespacestd;n n#pragma)#pragma)n n#pragma)#pragma)n nvoidcvQR(CvMat*inputA,CvMat*q,CvMat*r)voidcvQR(CvMat*inputA,CvMat*q,CvMat*r)n n n n n n n nCvSizeinputSize=cvGetSiz

132、e(inputA);CvSizeinputSize=cvGetSize(inputA);n nintwidth=;intwidth=;n nintheight=;intheight=;n ncvSetIdentity(q);cvSetIdentity(q);n ncvCopy(inputA,r);cvCopy(inputA,r);n nvectormatMem;vectormatMem;n nCvMat*tempH=cvCreateMat(height,height,CV_32FC1);CvMat*tempH=cvCreateMat(height,height,CV_32FC1);n nmat

133、Mem.push_back(&tempH);matMem.push_back(&tempH);n nCvMat*v=cvCreateMat(height,1,CV_32FC1);CvMat*v=cvCreateMat(height,1,CV_32FC1);n nmatMem.push_back(&v);matMem.push_back(&v);n nCvMat*tempCol=cvCreateMat(height,1,CV_32FC1);CvMat*tempCol=cvCreateMat(height,1,CV_32FC1);n nmatMem.push_back(&tempCol);matM

134、em.push_back(&tempCol);n nCvMat*tempCol2=cvCreateMat(height,1,CV_32FC1);CvMat*tempCol2=cvCreateMat(height,1,CV_32FC1);n nmatMem.push_back(&tempCol2);matMem.push_back(&tempCol2);n nCvMat*iMat=cvCreateMat(height,height,CV_32FC1);CvMat*iMat=cvCreateMat(height,height,CV_32FC1);n nmatMem.push_back(&iMat)

135、;matMem.push_back(&iMat);n nCvMat*transV=cvCreateMat(1,height,CV_32FC1);CvMat*transV=cvCreateMat(1,height,CV_32FC1);n nmatMem.push_back(&transV);matMem.push_back(&transV);n nfloatval2=cvNorm(v);floatval2=cvNorm(v);n nif(val2=0)if(val2=0)n n n ncontinue;continue;n n n nval2*=val2;val2*=val2;n nval2=1

136、/val2;val2=1/val2;n ncvTranspose(v,transV);cvTranspose(v,transV);n ncvMatMul(v,transV,tempH);/cvMatMul(v,transV,tempH);/n ncvScale(tempH,tempH,2*val2);cvScale(tempH,tempH,2*val2);n ncvSetIdentity(iMat);/theidentitymatrixcvSetIdentity(iMat);/theidentitymatrixn ncvSub(iMat,tempH,iMat);cvSub(iMat,tempH

137、,iMat);n ncvCopy(iMat,tempH);/gettheHmatrixcvCopy(iMat,tempH);/gettheHmatrixn ncvTranspose(tempH,tempH);/transposecvTranspose(tempH,tempH);/transposen ncvMatMul(q,tempH,q);/q=cvMatMul(q,tempH,q);/q=n ncvGetCol(r,&temp,i);/getthecolagaincvGetCol(r,&temp,i);/getthecolagainn ncvSet2D(&temp,i,0,cvScalar

138、(colNorm,0,0);/setthenormcvSet2D(&temp,i,0,cvScalar(colNorm,0,0);/setthenormn ncvGetSubRect(r,&temp,cvRect(i,i+1,1,height-i-1);cvGetSubRect(r,&temp,cvRect(i,i+1,1,height-i-1);n nif(=0|=0)if(=0|=0)n nmemcpy(temp.data.fl,b,sizeof(float);memcpy(temp.data.fl,b,sizeof(float);n nelseelsen ncvZero(&temp);/

139、zerothesubmatrixcvZero(&temp);/zerothesubmatrixn n n n n nfor(intj=0;j();j+)for(intj=0;j();j+)n n n ncvReleaseMat(matMemj);cvReleaseMat(matMemj);n n n n n n n n n nintmain(intargc,char*argv)intmain(intargc,char*argv)n nfloatmatData=1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7;floatmatData=1,2,3,4,5,6,7,8,9,1,2,3

140、,4,5,6,7;n nfloatrData16;floatrData16;n nfloatqData16;floatqData16;n nCvMataMat=cvMat(4,4,CV_32FC1,matData);CvMataMat=cvMat(4,4,CV_32FC1,matData);n nCvMatrMat=cvMat(4,4,CV_32FC1,rData);CvMatrMat=cvMat(4,4,CV_32FC1,rData);n nCvMatqMat=cvMat(4,4,CV_32FC1,qData);CvMatqMat=cvMat(4,4,CV_32FC1,qData);n nc

141、vQR(&aMat,&qMat,&rMat);cvQR(&aMat,&qMat,&rMat);n nfloatdet=cvDet(&qMat);return0;floatdet=cvDet(&qMat);return0;n n 绘制贝赛尔绘制贝赛尔Bezier曲线曲线在在opencvopencv下实现贝赛尔曲线下实现贝赛尔曲线. .可以修改控制点,连接多条曲线,修改曲线精度等可以修改控制点,连接多条曲线,修改曲线精度等操作。操作。 程序示例如下程序示例如下: : /:定义控制台应用程序的入口点。/#include#include#include#include#include#include#

142、includeusingnamespacestd;constintWW_MAX_MARK_COUNT=40;/最大40个控制点intmark_count=4;intconner_pt_index=-1;CvPoint3D32fControl_ptsWW_MAX_MARK_COUNT;IplImage*image=0;/原始图像boolis_showControlLines=true;/两个向量相加,p=p+qCvPoint3D32fpointAdd(CvPoint3D32fp,CvPoint3D32fq)+=;+=;+=;returnp;/向量和标量相乘p=c*pCvPoint3D32fpoi

143、ntTimes(floatc,CvPoint3D32fp)*=c;*=c;*=c;returnp;/计算贝塞尔方程的值/变量u的范围在0-1之间/P1*t3+P2*3*t2*(1-t)+P3*3*t*(1-t)2+P4*(1-t)3=PnewCvPoint3D32fBernstein(floatu,CvPoint3D32f*p)CvPoint3D32fa,b,c,d,r;a=pointTimes(pow(u,3),p0);b=pointTimes(3*pow(u,2)*(1-u),p1);c=pointTimes(3*u*pow(1-u),2),p2);d=pointTimes(pow(1-u

144、),3),p3);r=pointAdd(pointAdd(a,b),pointAdd(c,d);returnr;/画控制线voidDrawControlLine(CvPoint3D32f*p)CvPointpc4;for(inti=0;i4;i+)pci.x=(int)pi.x;pci.y=(int)pi.y;cvLine(image,pc0,pc1,CV_RGB(0,0,255),1,CV_AA,0);cvLine(image,pc2,pc3,CV_RGB(0,0,255),1,CV_AA,0);/得到最近Control_pts的indexintgetNearPointIndex(CvPoi

145、ntmouse_pt)CvPointpt;for(inti=0;imark_count;i+)=-(int)Control_ptsi.x;=-(int)Control_ptsi.y;floatdistance=sqrt(float)(*+*);if(distance10)returni;return-1;voidon_mouse(intevent,intx,inty,intflags,void*param)if(event=CV_EVENT_LBUTTONDOWN)CvPointpt=cvPoint(x,y);/coutx,y-1)conner_pt_index=-1;elseconner_p

146、t_index=getNearPointIndex(pt);/添加新的控制点if(conner_pt_index=-1)if(mark_count-1)Control_ptsconner_pt_index.x=(float)x;Control_ptsconner_pt_index.y=(float)y;intmain(intargc,char*argv)CvSizeimage_sz=cvSize(1000,1000);image=cvCreateImage(image_sz,8,3);cvNamedWindow(Win,0);cvSetMouseCallback(Win,on_mouse,0)

147、;cvResizeWindow(Win,500,500);cout=BeziercurveDEMO=endl;coutendl;cout1.usemousetoclickcontrolpoint(red)toselectacontrolpointendl;cout2.usemousetomodifycontrolpointendl;cout3.clickmouseonsomewheretoaddacontrolpoint,addthreepointsforaddanewcurveendl;cout4.useW,Stoaddprecisionorreduceprecision.endl;cout

148、5.pressZtoshowcontrolpoints.endl;cout=pressESCtoexit=endl/初始化四个控制点Control_pts0.x=200;Control_pts0.y=200;Control_pts0.z=0;Control_pts1.x=300;Control_pts1.y=500;Control_pts1.z=0;Control_pts2.x=400;Control_pts2.y=560;Control_pts2.z=0;Control_pts3.x=500;Control_pts3.y=100;Control_pts3.z=0;intdivs=50;/控制

149、精细度for(;)CvPointpt_now,pt_pre;cvZero(image);/绘制控制点if(is_showControlLines)for(inti=0;imark_count;i+)CvPointptc;=(int)Control_ptsi.x;=(int)Control_ptsi.y;cvCircle(image,ptc,4,CV_RGB(255,0,0),1,CV_AA,0);/绘制Bezier曲线CvPoint3D32f*pControls=Control_pts;for(intj=0;jmark_count-3;j+=3)for(inti=0;i0)cvLine(ima

150、ge,pt_now,pt_pre,CV_RGB(230,255,0),2,CV_AA,0);pt_pre=pt_now;/画控制线if(is_showControlLines)DrawControlLine(pControls);pControls+=3;cvShowImage(Win,image);intkeyCode=cvWaitKey(20);if(keyCode=27)break;if(keyCode=w|keyCode=W)divs+=2;if(keyCode=s|keyCode=S)divs-=2;if(keyCode=z|keyCode=Z)is_showControlLines

151、=is_showControlLines1;/coutprecision:divsSettings-Settingsfor:(Allconfigurations)-C/C+-Category(Preprocessor)-Additionalincludedirectories/设置为DirectShow/Include/3.菜单Project-Settings-Settingsfor:(Allconfigurations)-Link-Category(Input)-Additionallibrarydirectories/设置为DirectShow/Lib/#include#include#i

152、ncludeintmain()intcam_count;/获取摄像头数目cam_count=CCameraDS:CameraCount();printf(Thereare%dcameras.n,cam_count);if(cam_count=0)return-1;/打开第一个摄像头CCameraDScamera;if(!camera.OpenCamera(1)fprintf(stderr,Cannotopencamera.n);return-1;cvNamedWindow(camera);while(1)/获取一帧IplImage*pFrame=();/显示cvShowImage(camera

153、,pFrame);if(cvWaitKey(20)=q)break;cvDestroyWindow(camera);return0;设定跟踪目标图片的改进设定跟踪目标图片的改进camshift例子例子 n ncamshiftcamshift实现自动化跟踪的小技巧实现自动化跟踪的小技巧 n nopencvopencv提供了使用基于颜色的跟踪算法提供了使用基于颜色的跟踪算法camshift,camshift,很好的很好的算法,可是它是个半自动的算法,它需要用户在跟踪界算法,可是它是个半自动的算法,它需要用户在跟踪界面设定跟踪的目标。怎么预先设定目标再来跟踪呢?面设定跟踪的目标。怎么预先设定目标再来

154、跟踪呢? 本人偷了个懒,加入了用一张图片来设定跟踪的目标,本人偷了个懒,加入了用一张图片来设定跟踪的目标,在启动中加载图片,生成跟踪需要的在启动中加载图片,生成跟踪需要的histogramhistogram。这样实。这样实现了自动化的跟踪吧。现了自动化的跟踪吧。 n n步骤如下:步骤如下:1.1.找到你需要跟踪的物体,拿到摄像头前,找到你需要跟踪的物体,拿到摄像头前,照一张相(照一张相(printscreenprintscreen),这里需要注意的是,由于光),这里需要注意的是,由于光线变化,临近摄像头会亮一些,离远会暗一些,那么最线变化,临近摄像头会亮一些,离远会暗一些,那么最好跟踪的物体的

155、拍摄颜色与实际跟踪中颜色相近。好跟踪的物体的拍摄颜色与实际跟踪中颜色相近。 n n2.2.打开画笔功能,新建一张图片打开画笔功能,新建一张图片(320*240)(320*240),大小与视,大小与视频源图像一致,把物体截取放大,这样跟踪的颜色区域频源图像一致,把物体截取放大,这样跟踪的颜色区域就都在图像中了。就都在图像中了。 例如这是一个跟踪绿色物体的图片3.在代码中加入voidloadTemplateImage()IplImage*tempimage=cvLoadImage(F:/OM_tracking/Testcamshift/ShadowTrack/Debug/green.bmp,1);

156、cvCvtColor(tempimage,hsv,CV_BGR2HSV);int_vmin=vmin,_vmax=vmax;cvInRangeS(hsv,cvScalar(0,smin,MIN(_vmin,_vmax),0),cvScalar(180,256,MAX(_vmin,_vmax),0),mask);cvSplit(hsv,hue,0,0,0);=1;=1;=320-1;=240-1;cvSetImageROI(hue,selection);cvSetImageROI(mask,selection);cvCalcHist(&hue,hist,0,mask);floatmax_val=

157、0.f;cvGetMinMaxHistValue(hist,0,&max_val,0,0);cvConvertScale(hist-bins,hist-bins,max_val?255./max_val:0.,0);cvResetImageROI(hue);cvResetImageROI(mask);track_window=selection;track_object=1;cvReleaseImage(&tempimage);4.去掉原来的生成Hist的代码。在启动时候加入loadTemplateImage5.运行代码,看结果摄像头标定摄像头标定n nOPENCV没有提供完整的示例,自己整理

158、了一下,贴出来记录。n n步骤如下:n n首先自制一张标定图片,用A4纸打印出来,设定距离,再设定标定棋盘的格子数目,如86,以下是我做的图片88然后利用cvFindChessboardCorners找到棋盘在摄像头中的2D位置,这里cvFindChessboardCorners不太稳定,有时不能工作,也许需要图像增强处理。计算实际的距离,应该是3D的距离。我设定为毫米,既在A4纸上为两厘米。再用cvCalibrateCamera2计算内参,最后用cvUndistort2纠正图像的变形。结果如下:#include#include#include#include/OpenCV#include#i

159、nclude#include#includevoidInitCorners3D(CvMat*Corners3D,CvSizeChessBoardSize,intNimages,floatSquareSize);voidmakeChessBoard();intmyFindChessboardCorners(constvoid*image,CvSizepattern_size,CvPoint2D32f*corners,int*corner_count=NULL,intflags=CV_CALIB_CB_ADAPTIVE_THRESH);inlineintdrawCorssMark(IplImage

160、*dst,CvPointpt)/*Function:main_loopDescription:绘制一个十字标记Calls:CalledBy:Input:RGBimage,ptOutput:Return:Others:需要检查坐标是否越界todolist*/constintcross_len=4;CvPointpt1,pt2,pt3,pt4;pt1.x=;pt1.y=-cross_len;pt2.x=;pt2.y=+cross_len;pt3.x=-cross_len;pt3.y=;pt4.x=+cross_len;pt4.y=;cvLine(dst,pt1,pt2,CV_RGB(0,255,0

161、),2,CV_AA,0);cvLine(dst,pt3,pt4,CV_RGB(0,255,0),2,CV_AA,0);return0;/*declarationsforOpenCV*/IplImage*current_frame_rgb,grid;IplImage*current_frame_gray;IplImage*chessBoard_Img;intThresholdness=120;intimage_width=320;intimage_height=240;boolverbose=false;constintChessBoardSize_w=7;constintChessBoardS

162、ize_h=7;/Calibrationstuffboolcalibration_done=false;constCvSizeChessBoardSize=cvSize(ChessBoardSize_w,ChessBoardSize_h);/floatSquareWidth=21.6f;/实际距离毫米单位在A4纸上为两厘米floatSquareWidth=17;/投影实际距离毫米单位200constintNPoints=ChessBoardSize_w*ChessBoardSize_h;constintNImages=20;/NumberofimagestocollectCvPoint2D32

163、fcornersNPoints*NImages;intcorner_countNImages=0;intcaptured_frames=0;CvMat*intrinsics;CvMat*distortion_coeff;CvMat*rotation_vectors;CvMat*translation_vectors;CvMat*object_points;CvMat*point_counts;CvMat*image_points;intfind_corners_result=0;voidon_mouse(intevent,intx,inty,intflags,void*param)if(eve

164、nt=CV_EVENT_LBUTTONDOWN)/calibration_done=true;intmain(intargc,char*argv)CvFontfont;cvInitFont(&font,CV_FONT_VECTOR0,5,5,0,7,8);intrinsics=cvCreateMat(3,3,CV_32FC1);distortion_coeff=cvCreateMat(1,4,CV_32FC1);rotation_vectors=cvCreateMat(NImages,3,CV_32FC1);translation_vectors=cvCreateMat(NImages,3,C

165、V_32FC1);point_counts=cvCreateMat(NImages,1,CV_32SC1);object_points=cvCreateMat(NImages*NPoints,3,CV_32FC1);image_points=cvCreateMat(NImages*NPoints,2,CV_32FC1);/Functiontofillinthereal-worldpointsofthecheckerboardInitCorners3D(object_points,ChessBoardSize,NImages,SquareWidth);CvCapture*capture=0;if

166、(argc=1|(argc=2&strlen(argv1)=1&isdigit(argv10)capture=cvCaptureFromCAM(argc=2?argv10-0:0);elseif(argc=2)capture=cvCaptureFromAVI(argv1);if(!capture)fprintf(stderr,Couldnotinitializecapturing.n);return-1;/InitializealloftheIplImagestructurescurrent_frame_rgb=cvCreateImage(cvSize(image_width,image_he

167、ight),IPL_DEPTH_8U,3);IplImage*current_frame_rgb2=cvCreateImage(cvSize(image_width,image_height),IPL_DEPTH_8U,3);current_frame_gray=cvCreateImage(cvSize(image_width,image_height),IPL_DEPTH_8U,1);chessBoard_Img=cvCreateImage(cvSize(image_width,image_height),IPL_DEPTH_8U,3);current_frame_rgb2-origin=c

168、hessBoard_Img-origin=current_frame_gray-origin=current_frame_rgb-origin=1;makeChessBoard();cvNamedWindow(result,0);cvNamedWindow(Window0,0);cvNamedWindow(grid,0);cvMoveWindow(grid,100,100);cvSetMouseCallback(Window0,on_mouse,0);cvCreateTrackbar(Thresholdness,Window0,&Thresholdness,255,0);while(!cali

169、bration_done)while(captured_framesdata.fl0=256.8093262;/fxintrinsics-data.fl2=160.2826538;/cxintrinsics-data.fl4=254.7511139;/fyintrinsics-data.fl5=127.6264572;/cyintrinsics-data.fl1=0;intrinsics-data.fl3=0;intrinsics-data.fl6=0;intrinsics-data.fl7=0;intrinsics-data.fl8=1;distortion_coeff-data.fl0=-

170、0.193740;/k1distortion_coeff-data.fl1=-0.378588;/k2distortion_coeff-data.fl2=0.028980;/p1distortion_coeff-data.fl3=0.008136;/p2cvWaitKey(40);find_corners_result=0;/if(find_corners_result!=0)printf(n);cvSetData(image_points,corners,sizeof(CvPoint2D32f);cvSetData(point_counts,&corner_count,sizeof(int)

171、;cvCalibrateCamera2(object_points,image_points,point_counts,cvSize(image_width,image_height),intrinsics,distortion_coeff,rotation_vectors,translation_vectors,0);/fx0cx;0fycy;001.cvUndistort2(current_frame_rgb,current_frame_rgb,intrinsics,distortion_coeff);cvShowImage(result,current_frame_rgb);floati

172、ntr33=0.0;floatdist4=0.0;floattranv3=0.0;floatrotv3=0.0;for(inti=0;i3;i+)for(intj=0;j+intrinsics-step*i)j;disti=(float*)(distortion_coeff-data.ptr)i;tranvi=(float*)(translation_vectors-data.ptr)i;rotvi=(float*)(rotation_vectors-data.ptr)i;dist3=(float*)(distortion_coeff-data.ptr)3;printf(-n);printf(

173、INTRINSICMATRIX:n);printf(%6.4fn,intr00,intr01,intr02);printf(%6.4fn,intr10,intr11,intr12);printf(%6.4fn,intr20,intr21,intr22);printf(-n);printf(DISTORTIONVECTOR:n);printf(%6.4fn,dist0,dist1,dist2,dist3);printf(-n);printf(ROTATIONVECTOR:n);printf(%6.4fn,rotv0,rotv1,rotv2);printf(TRANSLATIONVECTOR:n)

174、;printf(%6.4fn,tranv0,tranv1,tranv2);printf(-n);cvWaitKey(0);calibration_done=true;exit(0);cvDestroyAllWindows();voidInitCorners3D(CvMat*Corners3D,CvSizeChessBoardSize,intNImages,floatSquareSize)intCurrentImage=0;intCurrentRow=0;intCurrentColumn=0;intNPoints=*;float*temppoints=newfloatNImages*NPoint

175、s*3;/fornow,assumingwererow-scanningfor(CurrentImage=0;CurrentImageNImages;CurrentImage+)for(CurrentRow=0;CurrentRow;CurrentRow+)for(CurrentColumn=0;CurrentColumn;CurrentColumn+)temppoints(CurrentImage*NPoints*3)+(CurrentRow*+CurrentColumn)*3=(float)CurrentRow*SquareSize;temppoints(CurrentImage*NPoi

176、nts*3)+(CurrentRow*+CurrentColumn)*3+1=(float)CurrentColumn*SquareSize;temppoints(CurrentImage*NPoints*3)+(CurrentRow*+CurrentColumn)*3+2=0.f;(*Corners3D)=cvMat(NImages*NPoints,3,CV_32FC1,temppoints);intmyFindChessboardCorners(constvoid*image,CvSizepattern_size,CvPoint2D32f*corners,int*corner_count,

177、intflags)IplImage*eig=cvCreateImage(cvGetSize(image),32,1);IplImage*temp=cvCreateImage(cvGetSize(image),32,1);doublequality=0.01;doublemin_distance=5;intwin_size=10;intcount=*;cvGoodFeaturesToTrack(image,eig,temp,corners,&count,quality,min_distance,0,3,0,0.04);cvFindCornerSubPix(image,corners,count,

178、cvSize(win_size,win_size),cvSize(-1,-1),cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);cvReleaseImage(&eig);cvReleaseImage(&temp);return1;voidmakeChessBoard()CvScalare;e.val0=255;e.val1=255;e.val2=255;cvSet(chessBoard_Img,e,0);for(inti=0;iChessBoardSize.width+1;i+)for(intj=0;jChessBoardSiz

179、e.height+1;j+)intw=(image_width)/2/(ChessBoardSize.width);inth=w;/(image_height)/2/(ChessBoardSize.height);intii=i+1;intiii=ii+1;intjj=j+1;intjjj=jj+1;ints_x=image_width/6;if(i+j)%2=1)cvRectangle(chessBoard_Img,cvPoint(w*i+s_x,h*j+s_x)cvPoint(w*ii-1+s_x,h*jj-1+s_x),CV_RGB(0,0,0),CV_FILLED,8,0);施密特正交

180、化施密特正交化n n#include#includen n#include#includen n#include#includen n#include#includen n/ /按行操作,要被正交化的向量以行的形式放在按行操作,要被正交化的向量以行的形式放在srcsrc里面,输出正交向量里面,输出正交向量以行以行 n n/ /的形式放的形式放dstdst里面,输出向量没有单位化里面,输出向量没有单位化 n nvoidGramSchmidt(constCvMat*src,CvMat*dst)voidGramSchmidt(constCvMat*src,CvMat*dst)n n n ninti,

181、j;inti,j;n ndoubleparam,param1,param2;doubleparam,param1,param2;n nassert(src!=NULL&dst!=NULL);assert(src!=NULL&dst!=NULL);n nassert(src-cols=dst-cols&src-rows=dst-rows);assert(src-cols=dst-cols&src-rows=dst-rows);n nCvMat*VecSrc=cvCreateMat(1,src-cols,CV_64FC1);CvMat*VecSrc=cvCreateMat(1,src-cols,C

182、V_64FC1);n nCvMat*VecDst=cvCreateMat(1,dst-cols,CV_64FC1);CvMat*VecDst=cvCreateMat(1,dst-cols,CV_64FC1);n nCvMat*VecTmp=cvCreateMat(1,dst-cols,CV_64FC1);CvMat*VecTmp=cvCreateMat(1,dst-cols,CV_64FC1);n ncvZero(VecSrc);cvZero(VecSrc);n ncvZero(VecDst);cvZero(VecDst);for(i=0;irows;i+)cvGetRow(src,VecDs

183、t,i);cvGetRow(src,VecSrc,i);for(j=0;jdata.db+i*dst-cols,VecDst-data.db,dst-cols*sizeof(double);cvReleaseMat(&VecSrc);cvReleaseMat(&VecDst);cvReleaseMat(&VecTmp);intmain(intargc,char*argv)inti,j;CvMat*Ma,*Mb;Ma=cvCreateMatHeader(3,4,CV_64FC1);Mb=NULL;constdoublea=1,0,1,1,0,1,1,0,0,0,1,1,;cvInitMatHea

184、der(Ma,3,4,CV_64FC1,(void*)a);Mb=cvCreateMat(Ma-rows,Ma-cols,CV_64FC1);GramSchmidt(Ma,Mb);/printfoutfor(i=0;irows;i+)for(j=0;jcols;j+)coutCV_MAT_ELEM(*Mb,double,i,j);coutendl;coutcols,CV_64FC1);CvMat*M2=cvCreateMat(1,Ma-cols,CV_64FC1);doubles;for(i=0;irows;i+)cvGetRow(Mb,M1,i);for(j=0;jrows;j+)cvGet

185、Row(Mb,M2,j);s=cvDotProduct(M2,M1);couts;coutendl;cvReleaseMat(&Ma);cvReleaseMat(&Mb);return0;分形fractal演示分形之美分形之美看到有的网站搞分形艺术,才知道这个Z=Z*Z+C如此的奇妙。于是干脆在opencv下写出来,看看。效果还不错。呵呵。这个小例子只能修改C的值,有兴趣的朋友可以自己改改代码,看能不能做出些美妙的图形。代码提示:要获得高质量的图像,可以增加image_w.运行结果:#include#include#includeconstintimage_w=100;constdoublea

186、=0.0;constdoubleb=0.0;constlongNmax=255;/Z值衰减(趋向于零)的临界constdoubleRmax=20;/Z值没有界限地增加(趋向无穷)的临界IplImage*image=0;intc_r_value=60;intc_i_value=40;/返回迭代的次数intgetnum(inti,intj)doubleC_RealPart=(double)(c_r_value-50)/100*2*2;/-2到+2/Julia集合常数CdoubleC_ImagPart=(double)(c_i_value-50)/100*2*2;/-2到+2/Julia集合常数Cd

187、oubleRealPart=(double)i/image_w+a;doubleImagPart=(double)j/image_w+b;intn=0;while(nRmax)break;doubletemp_RealPart=RealPart*RealPart-ImagPart*ImagPart+C_RealPart;doubletemp_ImagPart=2*ImagPart*RealPart+C_ImagPart;RealPart=temp_RealPart;ImagPart=temp_ImagPart;n+;returnn;voidonChangeimg(intpos)cvZero(i

188、mage);for(inti=0;iimage_w;i+)for(intj=0;jNmax-2)n1=0;if(n2Nmax-2)n2=0;if(n3Nmax-2)n3=0;sc1.val0=(int)abs(255*(float)n1/Nmax);sc1.val1=(int)abs(255*(float)n2/Nmax);sc1.val2=(int)abs(255*(float)n3/Nmax);cvSet2D(image,i,j,sc1);doublenvalue=cvNorm(image,0,CV_C);for(inti=0;iimage_w;i+)for(intj=0;jimage_w

189、;j+)CvScalarsc1;CvScalarsc2=cvGet2D(image,i,j);sc1.val0=(int)abs(255*sc2.val0/nvalue);sc1.val1=(int)abs(255*sc2.val1/nvalue);sc1.val2=(int)abs(255*sc2.val2/nvalue);cvSet2D(image,i,j,sc1);intmain(intargc,char*argv)cvNamedWindow(WIN,0);cvCreateTrackbar(Creal,WIN,&c_r_value,100,onChangeimg);cvCreateTra

190、ckbar(Cimag,WIN,&c_i_value,100,onChangeimg);image=cvCreateImage(cvSize(image_w,image_w),8,3);onChangeimg(0);for(;)cvShowImage(WIN,image);if(cvWaitKey(40)=27)break;return0;高斯背景建模高斯背景建模#include#include#include#include#include/必须引此头文件intmain(intargc,char*argv)IplImage*pFrame=NULL;IplImage*pFrImg=NULL;I

191、plImage*pBkImg=NULL;CvCapture*pCapture=NULL;intnFrmNum=0;cvNamedWindow(video,1);cvNamedWindow(background,1);cvNamedWindow(foreground,1);cvMoveWindow(video,30,0);cvMoveWindow(background,360,0);cvMoveWindow(foreground,690,0);if(argc2)fprintf(stderr,Usage:bkgrdvideo_file_namen);return-1;/初始化高斯混合模型参数CvG

192、aussBGModel*bg_model=NULL;while(pFrame=cvQueryFrame(pCapture)nFrmNum+;if(nFrmNum=1)pBkImg=cvCreateImage(cvSize(pFrame-width,pFrame-height),IPL_DEPTH_8U,3);pFrImg=cvCreateImage(cvSize(pFrame-width,pFrame-height),IPL_DEPTH_8U,1);/高斯背景建模,pFrame可以是多通道图像也可以是单通道图像/cvCreateGaussianBGModel函数返回值为CvBGStatMode

193、l*,/需要强制转换成CvGaussBGModel*bg_model=(CvGaussBGModel*)cvCreateGaussianBGModel(pFrame,0);else/更新高斯模型cvUpdateBGStatModel(pFrame,(CvBGStatModel*)bg_model);/pFrImg为前景图像,只能为单通道/pBkImg为背景图像,可以为单通道或与pFrame通道数相同cvCopy(bg_model-foreground,pFrImg,0);cvCopy(bg_model-background,pBkImg,0);/把图像正过来pBkImg-origin=1;pF

194、rImg-origin=1;cvShowImage(video,pFrame);cvShowImage(background,pBkImg);cvShowImage(foreground,pFrImg);if(cvWaitKey(2)=0)break;/释放高斯模型参数占用内存cvReleaseBGStatModel(CvBGStatModel*)&bg_model);cvDestroyWindow(video);cvDestroyWindow(background);cvDestroyWindow(foreground);cvReleaseImage(&pFrImg);cvReleaseIm

195、age(&pBkImg);cvReleaseCapture(&pCapture);return0;图像缩放本例子演示函数cvResize的使用。#include#include#includeintmain(intargc,char*argv)IplImage*src=0;/源图像指针IplImage*dst=0;/目标图像指针floatscale=0.618;/缩放倍数为倍CvSizedst_cvsize;/目标图像尺寸/*thefirstcommandlineparametermustbeimagefilename*/if(argc=2&(src=cvLoadImage(argv1,-1)

196、!=0)/如果命令行传递了需要打开的图片就无须退出,所以注释掉下面一行!/return-1;elsesrc=);/载入工作目录下文件名为“”的图片。=src-width*scale;/目标图像的宽为源图象宽的scale倍=src-height*scale;/目标图像的高为源图象高的scale倍dst=cvCreateImage(dst_cvsize,src-depth,src-nChannels);/构造目标图象cvResize(src,dst,CV_INTER_LINEAR);/缩放源图像到目标图像cvNamedWindow(src,CV_WINDOW_AUTOSIZE);/创建用于显示源图

197、像的窗口cvNamedWindow(dst,CV_WINDOW_AUTOSIZE);/创建用于显示目标图像的窗口cvShowImage(src,src);/显示源图像cvShowImage(dst,dst);/显示目标图像cvWaitKey(-1);/等待用户响应cvReleaseImage(&src);/释放源图像占用的内存cvReleaseImage(&dst);/释放目标图像占用的内存cvDestroyWindow(src);/销毁窗口“src”cvDestroyWindow(dst);/销毁窗口“dst”/voidcvDestroyAllWindows(void);return0;高级

198、图像处理初步高级图像处理初步本代码主要是对一幅灰度图像进行一些处理,消除图像中的亮度不一致的背景,并使用阀值分割将修改后的图像转换为二值图像,使用轮廓检测返回图像中目标对象的个数以及统计属性。#include#include#include/#include/#includeintmain(intargc,char*argv)IplImage*src=0;/定义源图像指IplImage*tmp=0;/定义临时图像指针IplImage*src_back=0;/定义源图像背景指针IplImage*dst_gray=0;/定义源文件去掉背景后的目标灰度图像指针IplImage*dst_bw=0;/定

199、义源文件去掉背景后的目标二值图像指针IplImage*dst_contours=0;/定义轮廓图像指针IplConvKernel*element=0;/定义形态学结构指针intNumber_Object=0;/定义目标对象数量intcontour_area_tmp=0;/定义目标对象面积临时寄存器intcontour_area_sum=0;/定义目标所有对象面积的和intcontour_area_ave=0;/定义目标对象面积平均值intcontour_area_max=0;/定义目标对象面积最大值CvMemStorage*stor=0;CvSeq*cont=0;CvContourScanne

200、rcontour_scanner;CvSeq*a_contour=0;/1.读取和显示图像/*thefirstcommandlineparametermustbeimagefilename*/if(argc=2&(src=cvLoadImage(argv1,0)!=0);elsesrc=,0);cvNamedWindow(src,CV_WINDOW_AUTOSIZE);cvShowImage(src,src);/cvSmooth(src,src,CV_MEDIAN,3,0,0,0);/中值滤波,消除小的噪声;/2.估计图像背景tmp=cvCreateImage(cvGetSize(src),s

201、rc-depth,src-nChannels);src_back=cvCreateImage(cvGetSize(src),src-depth,src-nChannels);/创建结构元素element=cvCreateStructuringElementEx(4,4,1,1,CV_SHAPE_ELLIPSE,0);/用该结构对源图象进行数学形态学的开操作后,估计背景亮度cvErode(src,tmp,element,10);cvDilate(tmp,src_back,element,10);cvNamedWindow(src_back,CV_WINDOW_AUTOSIZE);cvShowIm

202、age(src_back,src_back);/3.从源图象中减区背景图像dst_gray=cvCreateImage(cvGetSize(src),src-depth,src-nChannels);cvSub(src,src_back,dst_gray,0);cvNamedWindow(dst_gray,CV_WINDOW_AUTOSIZE);cvShowImage(dst_gray,dst_gray);/4.使用阀值操作将图像转换为二值图像dst_bw=cvCreateImage(cvGetSize(src),src-depth,src-nChannels);cvThreshold(dst

203、_gray,dst_bw,50,255,CV_THRESH_BINARY);/取阀值为50把图像转为二值图像/cvAdaptiveThreshold(dst_gray,dst_bw,255,CV_ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,3,5);cvNamedWindow(dst_bw,CV_WINDOW_AUTOSIZE);cvShowImage(dst_bw,dst_bw);/5.检查图像中的目标对象数量stor=cvCreateMemStorage(0);cont=cvCreateSeq(CV_SEQ_ELTYPE_POINT,sizeof(CvS

204、eq),sizeof(CvPoint),stor);Number_Object=cvFindContours(dst_bw,stor,&cont,sizeof(CvContour),CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0);/找到所有轮廓printf(Number_Object:%dn,Number_Object);/6.计算图像中对象的统计属性dst_contours=cvCreateImage(cvGetSize(src),src-depth,src-nChannels);cvThreshold(dst_contours,dst_co

205、ntours,0,255,CV_THRESH_BINARY_INV);/在画轮廓前先把图像变成白色for(;cont;cont=cont-h_next)cvDrawContours(dst_contours,cont,CV_RGB(255,0,0),CV_RGB(255,0,0),0,1,8,cvPoint(0,0);/绘制当前轮廓contour_area_tmp=fabs(cvContourArea(cont,CV_WHOLE_SEQ);/获取当前轮廓面积if(contour_area_tmpcontour_area_max)contour_area_max=contour_area_tmp

206、;/找到面积最大的轮廓contour_area_sum+=contour_area_tmp;/求所有轮廓的面积和contour_area_ave=contour_area_sum/Number_Object;/求出所有轮廓的平均值printf(contour_area_ave:%dn,contour_area_ave);printf(contour_area_max:%dn,contour_area_max);cvNamedWindow(dst_contours,CV_WINDOW_AUTOSIZE);cvShowImage(dst_contours,dst_contours);cvWaitK

207、ey(-1);/等待退出cvReleaseImage(&src);cvReleaseImage(&tmp);cvReleaseImage(&src_back);cvReleaseImage(&dst_gray);cvReleaseImage(&dst_bw);cvReleaseImage(&dst_contours);cvReleaseMemStorage(&stor);cvDestroyWindow(src);cvDestroyWindow(src_back);cvDestroyWindow(dst_gray);cvDestroyWindow(dst_bw);cvDestroyWindow(dst_contours);/voidcvDestroyAllWindows(void);return0;

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 医学/心理学 > 基础医学

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号