QQ登录

只需要一步,快速开始

 注册地址  找回密码

tag 标签: practice

相关帖子

版块 作者 回复/查看 最后发表

相关日志

分享 practice
sdccumcm 2012-7-13 13:10
/* P01_showImage Function 1 cvLoadImage (char* filename, int flags = CV_LOAD_IMAGE_COLOR) 1) filename: "E:\\OPENCV_PROJECT\\lena.jpg" 2) flags: Unchanged: #define CV_LOAD_IMAGE_UNCHANGED -1 Grayscale: #define CV_LOAD_IMAGE_GRAYSCALE 0 Colorful: #define CV_LOAD_IMAge_COLOR 1 *** If you want the ORIGINAL FORM: CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR Function 2 cvShowImage(char* name, IplImage* dst) To show image 'dst' in the window 'name'. Function 3 cvWaitKey(a) if a=0, wait for keyying to stop; if a0, wait for a ms to stop. Function 4 cvReleaseImage(src); cvDestroyWindow("window's_name") */ /* #includehighgui.h #includecv.h #includestdio.h #includecxcore.h int main(int argc, char* argv ) { cvNamedWindow("readVedio"); CvCapture* capture = cvCreateFileCapture("E:\\OPENCV_PROJECT\\machine.avi"); //CvCapture* capture = cvCreateCameraCapture(-1);// read the camera (-1: random) IplImage* frame; while(1)// show one frame of the vedio in a loop { frame = cvQueryFrame(capture);// if (!frame)// if the current image is empty (probably at the end), break { break; } cvShowImage("readVedio",frame);// use 'cvShowImage' to show the current image char c = cvWaitKey(33); // adjust the vedio frequency if (c == 27)// 27 is the ASC of key 'Esc': if keying 'Esc', break { break; } } cvReleaseCapture(capture); cvDestroyWindow("readVedio"); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P03_Controlling vedio 1 Creating the trackbar (to control): FUNCTION: int cvCreateTrackbar( const char* trackbar_name, const char* window_name, int* value, int count, CvTrackbarCallback on_change ) -----NOTING parameters: name of the trackbar;------ the window it belongs to; current place; total frame number; the callback function. FORM of the callback function: void on_changed(int pos) // name of the callback function is random */ /* #includehighgui.h #includecv.h CvCapture* g_capture = NULL; int g_slider_pos = 0; int frame_count = 0;// record which frame is being shown void onTrackbarSlider(int pos)// The callback function { cvSetCaptureProperty( g_capture, CV_CAP_PROP_POS_FRAMES, pos ); frame_count = pos;// ensure 'frame_count' is where we place the trackbar printf("g_slider_pos is %d \n", g_slider_pos); } int main(int argc, char* argv ) { IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); int height, width, step, channels; uchar* data; int i,j,k; // get the information of the image height= src-height; width= src-width; step= src-widthStep; channels= src-nChannels; data= (uchar*)src-imageData; printf("Processing a %dx% d image with %d channels\n", height, width, channels); // create a window cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); cvMoveWindow("mainWin", 100, 100); // REVERSE the image for( i = 0; i height; i++ ) for( j = 0; j width; j++ ) for( k = 0; k channels; k++ ) data = 255 - data ; // show the image cvShowImage("mainWin", src); cvWaitKey(0); cvReleaseImage(src); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P05_Image FORMAT CONVERTION 直接运行的时候,默认的argc是为1,而argv =该.exe文件的物理地址 argc表示参数的总个数,argv是参数的指针列表的指针。 例如你的程序编译后的exe是A.exe,那么当你在控制台敲命令 A.exe a b c d 的时候,arcg的值为5,argr 为指向字符串"A.exe"的指针,argr 为指向"a"的指针,后面依次类推。 这两个参数主要是用于你在控制台调用时传递参数时使用的 */ /* #includecv.h #includehighgui.h #includestdio.h int main(int argc, char** argv) { IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); if( argc != 3) { printf("CONV: Image format convertion, support JPG, ......\n"); printf("Usage: conv srcImage dstImage\n"); return 0; } if( ( strstr(argv ,".jpg") == NULL // strstr(char *str1, char *str2): find the place where str2 first appears in str1 strstr(argv ,".bmp") == NULL strstr(argv ,".tif") == NULL strstr(argv ,".png") == NULL strstr(argv ,".ppm") == NULL ) || ( strstr(argv ,".jpg") == NULL strstr(argv ,".bmp") == NULL strstr(argv ,".tif") == NULL strstr(argv ,".png") == NULL strstr(argv ,".ppm") == NULL) ) { printf( "WARNING: CONV only support JPG, BMP, TIF, PPM, TGA and PPM\n" ); } else{ if( ( src = cvLoadImage(argv , -1) ) != 0) { cvSaveImage(argv , src); cvReleaseImage(src); printf("\n Convert successfully. \n"); } else { printf("\n*** Read or write image fails *** \n"); } } return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P05_Read vedio from .avi/camera taking Edge Detection 1 #define cvCvtPixToPlane cvSplit void cvCvtPixToPlane( const CvArr* src, CvArr* dst0, CvArr* dst1, CvArr* dst2, CvArr* dst3 ); 第一个参数: 源图像,后面是: 分离出来每个通道的目标图像 example: 如果原图像是3通道的,可以把最后一个参数设置为空: cvCvtPixToPlane(IplImage * src, IplImage * dst1, IplImage *dst2, IplImage * dst3,NULL) 2 void cvLaplace( const CvArr* src, CvArr* dst, int aperture_size=3 ); --- function in "cv.h" INPUT Image, OUTPUT Image, SIZE 3 cvConvertScaleAbs: transform the INPUT into 8 unsigned integer input, output, 1: scale factor , 0: add number */ /* # includecv.h # includehighgui.h # includectype.h # includestdio.h int main(int arct, char** argv = {0,0,0};// multi image plane IplImage* frame = 0; CvCapture* capture = cvCaptureFromFile("E:\\OPENCV_PROJECT\\T-Mac_MagicIntroduction.avi"); //CvCapture* capture = cvCaptureFromCAM(0) ; cvNamedWindow("Laplacian",0); // loop to capture, until pushing the key for( ; ; ) { int i; frame = cvQueryFrame(capture);// function: capture a frame from the vedio if(!frame) break; if(!laplace) { for( i = 0; i 3; i++ ) { planes = cvCreateImage( cvSize( frame-width, frame-height), 8, 1 ); } laplace = cvCreateImage( cvSize( frame-width, frame-height ), IPL_DEPTH_16S, 1 ); colorlaplace = cvCreateImage( cvSize( frame-width, frame-height ), 8, 3 ); } cvCvtPixToPlane( frame, planes , planes , planes , 0);// detach the 3 planes for( i = 0; i 3; i++ ) { cvLaplace( planes , laplace, 3);// 3: aperture_size cvConvertScaleAbs( laplace, planes , 1,0 );// planes , planes , planes , 0, colorlaplace ); colorlaplace-origin = frame-origin; cvShowImage("Laplacian", colorlaplace); if(cvWaitKey(10) = 0) break; } cvReleaseCapture(capture); cvDestroyWindow("Laplacian"); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P06_searching the OUTLINE of an image (ERROR)---------------------------------------- */ /* #include "cv.h" #include "highgui.h" int main( int argc, char** argv ) { IplImage* src; // 第一条命令行参数确定了图像的文件名。 if( argc == 2 (src=cvLoadImage(argv , 0))!= 0) { IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 ); CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = 0; cvThreshold( src, src, 1, 255, CV_THRESH_BINARY ); cvNamedWindow( "Source", 1 ); cvShowImage( "Source", src ); cvFindContours( src, storage, contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); cvZero( dst ); for( ; contour != 0; contour = contour-h_next ) { CvScalar color = CV_RGB( rand()255, rand()255, rand()255 ); // 用1替代 CV_FILLED 所指示的轮廓外形 cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8 ); } cvNamedWindow( "Components", 1 ); cvShowImage( "Components", dst ); cvWaitKey(0); } } */ //***************************************************** //***************************************************** //***************************************************** /* P07_Edge Detection using Canny Algorithm #include "cv.h" #include "highgui.h" char wndname = "Threshold"; int edge_thresh = 1; IplImage* cedge = 0, *gray = 0, *edge = 0; IplImage* image = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); // 定义跟踪条的 callback 函数 void on_trackbar(int h) { cvSmooth( gray, edge, CV_BLUR, 3, 3, 0 ); cvNot( gray, edge ); // 对灰度图像进行边缘检测 cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 3); cvZero( cedge ); // copy edge points cvCopy( image, cedge, edge ); // 显示图像 cvShowImage(wndname, cedge); } int main( int argc, char** argv ) { //char* filename = argc == 2 ? argv : (char*)"fruits.jpg"; // Create the output image cedge = cvCreateImage(cvSize(image-width,image-height), IPL_DEPTH_8U, 3); // 将彩色图像转换为灰度图像 gray = cvCreateImage(cvSize(image-width,image-height), IPL_DEPTH_8U, 1); edge = cvCreateImage(cvSize(image-width,image-height), IPL_DEPTH_8U, 1); cvCvtColor(image, gray, CV_BGR2GRAY); // Create a window cvNamedWindow(wndname, 1); // create a toolbar cvCreateTrackbar(tbarname, wndname, edge_thresh, 100, on_trackbar); // Show the image on_trackbar(0); // Wait for a key stroke; the same function arranges events processing cvWaitKey(0); cvReleaseImage(image); cvReleaseImage(gray); cvReleaseImage(edge); cvDestroyWindow(wndname); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P08_Corner Detection */ /* #include stdio.h #include "cv.h" #include "highgui.h" #define max_corners 100 int main( int argc, char** argv ) { int cornerCount=max_corners; int i; CvPoint2D32f corners ; IplImage *grayImage = 0, *corners1 = 0, *corners2 = 0; CvScalar color = CV_RGB(255,0,0); IplImage *srcImage = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); cvNamedWindow( "image", 1 ); // create HighGUI window with name "image" grayImage = cvCreateImage(cvGetSize(srcImage), IPL_DEPTH_8U, 1); //copy the source image to copy image after converting the format cvCvtColor(srcImage, grayImage, CV_BGR2GRAY); //create empty images of same size as the copied images corners1= cvCreateImage(cvGetSize(srcImage), IPL_DEPTH_32F, 1); corners2= cvCreateImage(cvGetSize(srcImage),IPL_DEPTH_32F, 1); cvGoodFeaturesToTrack (grayImage, corners1, corners2, corners, cornerCount, 0.05, 5, 0, 3, // block size 0, // not use harris 0.4 ); printf("num corners found: %d\n", cornerCount); // draw circles at each corner location in the gray image and //print out a list the corners if(cornerCount0) { for (i=0; icornerCount; i++) { cvCircle(srcImage, cvPoint((int)(corners .x), (int)(corners .y)), 6, color, 2, CV_AA, 0); } } cvShowImage( "image", srcImage ); cvReleaseImage(srcImage); cvReleaseImage(grayImage); cvReleaseImage(corners1); cvReleaseImage(corners2); cvWaitKey(0); // wait for key. The function has return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P09_Rotation Zoom */ /* #include "cv.h" #include "highgui.h" #include "math.h" int main( int argc, char** argv ) { IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); // the first command line parameter must be image file name IplImage* dst = cvCloneImage( src ); int delta = 1; int angle = 0; int opt = 1; // 1: 旋转加缩放 // 0: 仅仅旋转 double factor; cvNamedWindow( "src", 1 ); cvShowImage( "src", src ); for(;;) { float m ; // Matrix m looks like: // // === // // CvMat M = cvMat( 2, 3, CV_32F, m ); int w = src-width; int h = src-height; if(opt) // 旋转加缩放 factor = (cos(angle*CV_PI/180.) + 1.05)*2; else // 仅仅旋转 factor = 1; m = (float)(factor*cos(-angle*2*CV_PI/180.)); m = (float)(factor*sin(-angle*2*CV_PI/180.)); m = -m ; m = m ; // 将旋转中心移至图像中间 m = w*0.5f; m = h*0.5f; // dst(x,y) = A * src(x,y) + b cvGetQuadrangleSubPix( src, dst, M); cvNamedWindow( "dst", 1 ); cvShowImage( "dst", dst ); if( cvWaitKey(5) == 27 ) break; angle =(int) (angle + delta) % 360; } // for-loop return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P10_Log-Polar transform */ /* #include cv.h #include highgui.h int main(int argc, char** argv) { IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\fruits.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); IplImage* dst = cvCreateImage( cvSize(256,256), 8, 3 ); IplImage* src2 = cvCreateImage( cvGetSize(src), 8, 3 ); cvLogPolar( src, dst, cvPoint2D32f(src-width/2,src-height/2), 40, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS ); cvLogPolar( dst, src2, cvPoint2D32f(src-width/2,src-height/2), 40, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS+CV_WARP_INVERSE_MAP ); cvNamedWindow( "log-polar", 1 ); cvShowImage( "log-polar", dst ); cvNamedWindow( "inverse log-polar", 1 ); cvShowImage( "inverse log-polar", src2 ); cvWaitKey(); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P11_Morphological Operation */ /* #include cv.h #include highgui.h #include stdlib.h #include stdio.h IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\baboon.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); IplImage* dst = 0; IplConvKernel* element = 0; int element_shape = CV_SHAPE_RECT; //the address of variable which receives trackbar position update int max_iters = 10; int open_close_pos = 0; int erode_dilate_pos = 0; // callback function for open/close trackbar void OpenClose(int pos) { int n = open_close_pos - max_iters; int an = n 0 ? n : -n; element = cvCreateStructuringElementEx( an*2+1, an*2+1, an, an, element_shape, 0 ); if( n 0 ) { cvErode(src,dst,element,1); cvDilate(dst,dst,element,1); } else { cvDilate(src,dst,element,1); cvErode(dst,dst,element,1); } cvReleaseStructuringElement(element); cvShowImage("Open/Close",dst); } // callback function for erode/dilate trackbar void ErodeDilate(int pos) { int n = erode_dilate_pos - max_iters; int an = n 0 ? n : -n; element = cvCreateStructuringElementEx( an*2+1, an*2+1, an, an, element_shape, 0 ); if( n 0 ) { cvErode(src,dst,element,1); } else { cvDilate(src,dst,element,1); } cvReleaseStructuringElement(element); cvShowImage("Erode/Dilate",dst); } int main( int argc, char** argv ) { //char* filename = argc == 2 ? argv : (char*)"baboon.jpg"; //if( (src = cvLoadImage(filename,1)) == 0 ) //6 return -1; printf( "Hot keys: \n" "\tESC - quit the program\n" "\tr - use rectangle structuring element\n" "\te - use elliptic structuring element\n" "\tc - use cross-shaped structuring element\n" "\tENTER - loop through all the options\n" ); dst = cvCloneImage(src); //create windows for output images cvNamedWindow("Open/Close",1); cvNamedWindow("Erode/Dilate",1); open_close_pos = erode_dilate_pos = max_iters; cvCreateTrackbar("iterations", "Open/Close",open_close_pos,max_iters*2+1,OpenClose); cvCreateTrackbar("iterations", "Erode/Dilate",erode_dilate_pos,max_iters*2+1,ErodeDilate); for(;;) { int c; OpenClose(open_close_pos); ErodeDilate(erode_dilate_pos); c = cvWaitKey(0); if( (char)c == 27 ) break; if( (char)c == 'e' ) element_shape = CV_SHAPE_ELLIPSE; else if( (char)c == 'r' ) element_shape = CV_SHAPE_RECT; else if( (char)c == 'c' ) element_shape = CV_SHAPE_CROSS; else if( (char)c == '\n' ) element_shape = (element_shape + 1) % 3; } //release images cvReleaseImage(src); cvReleaseImage(dst); //destroy windows cvDestroyWindow("Open/Close"); cvDestroyWindow("Erode/Dilate"); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P12_Filtering for Image with variaty filtering kernel (page270) */ /* #include cv.h #include highgui.h #include stdio.h int main( int argc, char** argv ) { IplImage *dst = 0, *dst2 = 0; //float k = { 0, 1, 0, // 1,-4, 1, // 0, 1, 0}; float k = { 1.f/16, 2.f/16, 1.f/16, 2.f/16, 4.f/16, 2.f/16, 1.f/16, 2.f/16, 1.f/16}; // 这里高斯核滤波器归一化 CvMat Km; //cvInitMatHeader( Km, 3, 3, CV_32FC1, k, CV_AUTOSTEP ); Km = cvMat( 3, 3, CV_32F, k ); // 0: force to gray image IplImage *src = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); dst = cvCloneImage( src ); cvNamedWindow("src", 0); cvShowImage("src",src); cvNamedWindow("filtering", 0); cvFilter2D( src, dst, Km, cvPoint(-1,-1)); cvShowImage("filtering",dst); cvWaitKey(0); cvReleaseImage( src ); cvReleaseImage( dst ); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P13_Moving Object Detection by searching for the outline (page288) */ /* #include "cv.h" #include "highgui.h" #include time.h #include math.h #include ctype.h #include stdio.h #include string.h // various tracking parameters (in seconds) const double MHI_DURATION = 0.5; const double MAX_TIME_DELTA = 0.5; const double MIN_TIME_DELTA = 0.05; const int N = 3; // const int CONTOUR_MAX_AERA = 16; // ring image buffer IplImage **buf = 0; int last = 0; // temporary images IplImage *mhi = 0; // MHI: motion history image int filter = CV_GAUSSIAN_5x5; CvConnectedComp *cur_comp, min_comp; CvConnectedComp comp; CvMemStorage *storage; CvPoint pt ; // 参数: // img – 输入视频帧 // dst – 检测结果 void update_mhi( IplImage* img, IplImage* dst, int diff_threshold ) { double timestamp = clock()/100.; // get current time in seconds CvSize size = cvSize(img-width,img-height); // get current frame size int i, j, idx1, idx2; IplImage* silh; uchar val; float temp; IplImage* pyr = cvCreateImage( cvSize((size.width -2)/2, (size.height -2)/2), 8, 1 ); CvMemStorage *stor; CvSeq *cont, *result, *squares; CvSeqReader reader; if( !mhi || mhi-width != size.width || mhi-height != size.height ) { if( buf == 0 ) { buf = (IplImage**)malloc(N*sizeof(buf )); memset( buf, 0, N*sizeof(buf )); } for( i = 0; i N; i++ ) { cvReleaseImage( buf ); buf = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvZero( buf ); } cvReleaseImage( mhi ); mhi = cvCreateImage( size, IPL_DEPTH_32F, 1 ); cvZero( mhi ); // clear MHI at the beginning } // end of if(mhi) cvCvtColor( img, buf , CV_BGR2GRAY ); // convert frame to grayscale idx1 = last; idx2 = (last + 1) % N; // index of (last - (N-1))th frame last = idx2; // 做帧差 silh = buf ; cvAbsDiff( buf , buf , silh ); // get difference between frames // 对差图像做二值化 cvThreshold( silh, silh, 30, 255, CV_THRESH_BINARY ); // and threshold it cvUpdateMotionHistory( silh, mhi, timestamp, MHI_DURATION ); // update MHI cvCvtScale( mhi, dst, 255./MHI_DURATION, (MHI_DURATION - timestamp)*255./MHI_DURATION ); cvCvtScale( mhi, dst, 255./MHI_DURATION, 0 ); // 中值滤波,消除小的噪声 cvSmooth( dst, dst, CV_MEDIAN, 3, 0, 0, 0 ); // 向下采样,去掉噪声 cvPyrDown( dst, pyr, 7 ); cvDilate( pyr, pyr, 0, 1 ); // 做膨胀操作,消除目标的不连续空洞 cvPyrUp( pyr, dst, 7 ); // // 下面的程序段用来找到轮廓 // // Create dynamic structure and sequence. stor = cvCreateMemStorage(0); cont = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint) , stor); // 找到所有轮廓 cvFindContours( dst, stor, cont, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); //for(;cont;cont = cont-h_next) //{ // Number point must be more than or equal to 6 (for cvFitEllipse_32f). //if( cont-total 6 ) //continue; // Draw current contour. //cvDrawContours(img,cont,CV_RGB(255,0,0),CV_RGB(255,0,0),0,1, 8, cvPoint(0,0)); //} // end of for-loop: "cont" // 直接使用CONTOUR中的矩形来画轮廓 for(;cont;cont = cont-h_next) { CvRect r = ((CvContour*)cont)-rect; if(r.height * r.width CONTOUR_MAX_AERA) // 面积小的方形抛弃掉 { cvRectangle( img, cvPoint(r.x,r.y), cvPoint(r.x + r.width, r.y + r.height), CV_RGB(255,0,0), 1, CV_AA,0); } } // free memory cvReleaseMemStorage(stor); cvReleaseImage( pyr ); } int main (int argc, char** argv) { IplImage* motion = 0; //CvCapture* capture = cvCreateFileCapture("E:\\OPENCV_PROJECT\\machine.avi"); CvCapture* capture = cvCreateCameraCapture(-1);// read the camera (-1: random) // if( argc == 1 || (argc == 2 strlen(argv ) == 1 isdigit(argv ))) // capture = cvCaptureFromCAM( argc == 2 ? argv - '0' : 0 ); //else if( argc == 2 ) // capture = cvCaptureFromAVI( argv ); if( capture ) { cvNamedWindow( "Motion", 1 ); for(;;) { IplImage* image; if( !cvGrabFrame( capture ) ) break; image = cvRetrieveFrame( capture ); if( image ) { if( !motion ) { motion = cvCreateImage( cvSize(image-width,image-height), 8, 1 ); cvZero( motion ); motion-origin = image-origin; } } update_mhi( image, motion, 60 ); cvShowImage( "Motion", image ); if( cvWaitKey(10) = 0 ) break; } cvReleaseCapture( capture ); cvDestroyWindow( "Motion" ); } return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P14_PyrSegmentation (page293) Function: cvPyrSegmentation ( IplImage * src, IplImage * dst, CvMemStorage * storage, CvSeq** comp, int level, double threshold1, double threshold2 ); Parameters src-- INPUT image dst-- OUTPUT image storage -- 存储连通部件的序列结果 comp-- 分割部件的输出序列指针 level-- maximum level of the Pyramid threshold1-- 建立连接 的错误阈值 threshold2-- 分割簇的错误阈值*/ /* #include "cv.h" #include "highgui.h" #include math.h IplImage *image0 = 0, *image1 = 0; IplImage *image ; CvSize size; int w0, h0,i; int threshold1, threshold2; int l,level = 4; int sthreshold1, sthreshold2; int l_comp; int block_size = 1000; float parameter; double threshold; double rezult, min_rezult; int filter = CV_GAUSSIAN_5x5; CvConnectedComp *cur_comp, min_comp; CvSeq *comp; CvMemStorage *storage; CvPoint pt1, pt2; void ON_SEGMENT(int a) { cvPyrSegmentation(image0, image1, storage, comp, level, threshold1+1, threshold2+1); cvShowImage("Segmentation", image1); } int main( int argc, char** argv ) { image = cvLoadImage("E:\\OPENCV_PROJECT\\fruits.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); cvNamedWindow("Source", 0); cvShowImage("Source", image ); cvNamedWindow("Segmentation", 0); storage = cvCreateMemStorage ( block_size ); image -width = -(1level); image -height = -(1level); image0 = cvCloneImage( image ); image1 = cvCloneImage( image ); // 对彩色图像进行分割 l = 1; threshold1 =255; threshold2 =30; ON_SEGMENT(1); sthreshold1 = cvCreateTrackbar("Threshold1", "Segmentation", threshold1, 255, ON_SEGMENT); sthreshold2 = cvCreateTrackbar("Threshold2", "Segmentation", threshold2, 255, ON_SEGMENT); cvShowImage("Segmentation", image1); cvWaitKey(0); cvDestroyWindow("Segmentation"); cvDestroyWindow("Source"); cvReleaseMemStorage(storage ); cvReleaseImage(image ); cvReleaseImage(image0); cvReleaseImage(image1); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P15_Adjust Brightness src and dst are grayscale, 8-bit images; Default input value: = ; X-Direction = ; Y-Direction gamma ; if adjust successfully, return 0, otherwise, return non-zero. */ /* #include "cv.h" #include "highgui.h" // function declaration int ImageAdjust(IplImage* src, IplImage* dst, double low, double high, // X方向:low and high are the intensities of src double bottom, double top, // Y方向:mapped to bottom and top of dst double gamma ); int main( int argc, char** argv ) { IplImage *src = cvLoadImage("E:\\OPENCV_PROJECT\\baboon.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); IplImage *dst = 0; cvNamedWindow( "src", 1 ); cvNamedWindow( "result", 1 ); // Image adjust dst = cvCloneImage(src); // 输入参数 和 , gamma=1 if( ImageAdjust( src, dst, 0, 0.5, 0.5, 1, 1)!=0) return -1; cvShowImage( "src", src ); cvShowImage( "result", dst ); cvWaitKey(0); cvDestroyWindow("src"); cvDestroyWindow("result"); cvReleaseImage( src ); cvReleaseImage( dst ); return 0; } int ImageAdjust(IplImage* src, IplImage* dst, double low, double high, // X方向:low and high are the intensities of src double bottom, double top, // Y方向:mapped to bottom and top of dst double gamma ) { if( low0 low1 high 0 high1 bottom0 bottom1 top0 top1 lowhigh) return -1; double low2 = low*255; double high2 = high*255; double bottom2 = bottom*255; double top2 = top*255; double err_in = high2 - low2; double err_out = top2 - bottom2; int x,y; double val; // intensity transform for( y = 0; y src-height; y++) { for (x = 0; x src-width; x++) { val = ((uchar*)(src-imageData + src-widthStep*y)) ; val = pow((val - low2)/err_in, gamma) * err_out + bottom2; if(val255) val=255; if(val0) val=0; // Make sure src is in the range ((uchar*)(dst-imageData + dst-widthStep*y)) = (uchar) val; } } return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P16_Histogram (page 306) */ /* #include "cv.h" #include "highgui.h" #include stdio.h #include ctype.h int main( int argc, char** argv ) { IplImage *histimg = 0; CvHistogram *hist = 0; int hdims = 50; // 划分HIST的个数,越高越精确 float hranges_arr , 0)) == NULL) // force to gray image // return -1; cvNamedWindow( "Histogram", 0 ); cvNamedWindow( "src", 0); hist = cvCreateHist( 1, hdims, CV_HIST_ARRAY, hranges, 1 ); // 计算直方图 histimg = cvCreateImage( cvSize(320,200), 8, 3 ); cvZero( histimg ); cvCalcHist( src, hist, 0, 0 ); // 计算直方图 cvGetMinMaxHistValue( hist, 0, max_val, 0, 0 ); // 只找最大值 cvConvertScale( hist-bins, hist-bins, max_val ? 255. / max_val : 0., 0 ); // 缩放 bin 到区间 cvZero( histimg ); bin_w = histimg-width / hdims; // hdims: 条的个数,则 bin_w 为条的宽度 // 画直方图 for( i = 0; i hdims; i++ ) { double val = ( cvGetReal1D(hist-bins,i)*histimg-height/255 ); CvScalar color = CV_RGB(255,255,0); //(hsv2rgb(i*180.f/hdims); cvRectangle( histimg, cvPoint(i*bin_w,histimg-height), cvPoint((i+1)*bin_w,(int)(histimg-height - val)), color, 1, 8, 0 ); } cvShowImage( "src", src); cvShowImage( "Histogram", histimg ); cvWaitKey(0); cvDestroyWindow("src"); cvDestroyWindow("Histogram"); cvReleaseImage( src ); cvReleaseImage( histimg ); cvReleaseHist ( hist ); return 0; } */ //***************************************************** //***************************************************** //***************************************************** /* P17_Detect Segment by Hough transform */ /*??????????????? // 这是一个命令行程序,以图像作为文件输入变量 // 编译时选择“#if 1”或“#if 0”,可以使用标准和概率HOUGH变换两种方法 #include cv.h #include highgui.h #include math.h int main(int argc, char** argv) { IplImage* src = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_GRAYSCALE); if( argc == 2 src != 0) { IplImage* dst = cvCreateImage( cvGetSize(src), 8, 1 ); IplImage* color_dst = cvCreateImage( cvGetSize(src), 8, 3 ); CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* lines = 0; int i; cvCanny( src, dst, 50, 200, 3 ); cvCvtColor( dst, color_dst, CV_GRAY2BGR ); #if 1 lines = cvHoughLines2( dst, storage, CV_HOUGH_STANDARD, 1, CV_PI/180, 150, 0, 0 ); for( i = 0; i lines-total; i++ ) { float* line = (float*)cvGetSeqElem(lines,i); float rho = line ; float theta = line ; CvPoint pt1, pt2; double a = cos(theta), b = sin(theta); if( fabs(a) 0.001 ) { pt1.x = pt2.x = cvRound(rho); pt1.y = 0; pt2.y = color_dst-height; } else if( fabs(b) 0.001 ) { pt1.y = pt2.y = cvRound(rho); pt1.x = 0; pt2.x = color_dst-width; } else { pt1.x = 0; pt1.y = cvRound(rho/b); pt2.x = cvRound(rho/a); pt2.y = 0; } cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 3, 8 ); } #else lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 80, 30, 10 ); for( i = 0; i lines-total; i++ ) { CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i); cvLine( color_dst, line , line , CV_RGB(255,0,0), 3, 8 ); } #endif cvNamedWindow( "Source", 1 ); cvShowImage( "Source", src ); cvNamedWindow( "Hough", 1 ); cvShowImage( "Hough", color_dst ); cvWaitKey(0); } } */ //***************************************************** //***************************************************** //***************************************************** /* P18_Detect Circle by Hough transform */ #include cv.h #include highgui.h #include math.h int main(int argc, char** argv) { IplImage* img = cvLoadImage("E:\\OPENCV_PROJECT\\lena.jpg", CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 ); CvMemStorage* storage = cvCreateMemStorage(0); cvCvtColor( img, gray, CV_BGR2GRAY ); cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9 ); // smooth it, otherwise a lot of false circles may be detected CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, gray-height/4, 200, 100 ); int i; for( i = 0; i circles-total; i++ ) { float* p = (float*)cvGetSeqElem( circles, i ); cvCircle( img, cvPoint(cvRound(p ),cvRound(p )), 3, CV_RGB(0,255,0), -1, 8, 0 ); cvCircle( img, cvPoint(cvRound(p ),cvRound(p )), cvRound(p ), CV_RGB(255,0,0), 3, 8, 0 ); } cvNamedWindow( "circles", 1 ); cvShowImage( "circles", img ); cvWaitKey(0); return 0; } // P88_DFT showing the power spectrum of the image /* #include cxcore.h #include cv.h #include highgui.h // 以图像中心为原点,调整傅立叶变换图像的四个象限区,即第一和第三象限交换 // 第二和第四象限交换 void cvShiftDFT(CvArr * src_arr, CvArr * dst_arr ) { CvMat * tmp; CvMat q1stub, q2stub; CvMat q3stub, q4stub; CvMat d1stub, d2stub; CvMat d3stub, d4stub; CvMat * q1, * q2, * q3, * q4; CvMat * d1, * d2, * d3, * d4; CvSize size = cvGetSize(src_arr); CvSize dst_size = cvGetSize(dst_arr); int cx, cy; if(dst_size.width != size.width || dst_size.height != size.height){ cvError( CV_StsUnmatchedSizes, "cvShiftDFT", "Source and Destination arrays must have equal sizes", __FILE__, __LINE__ ); } if(src_arr==dst_arr){ tmp = cvCreateMat(size.height/2, size.width/2, cvGetElemType(src_arr)); } cx = size.width/2; cy = size.height/2; // image center q1 = cvGetSubRect( src_arr, q1stub, cvRect(0,0,cx, cy) ); q2 = cvGetSubRect( src_arr, q2stub, cvRect(cx,0,cx,cy) ); q3 = cvGetSubRect( src_arr, q3stub, cvRect(cx,cy,cx,cy) ); q4 = cvGetSubRect( src_arr, q4stub, cvRect(0,cy,cx,cy) ); d1 = cvGetSubRect( src_arr, d1stub, cvRect(0,0,cx,cy) ); d2 = cvGetSubRect( src_arr, d2stub, cvRect(cx,0,cx,cy) ); d3 = cvGetSubRect( src_arr, d3stub, cvRect(cx,cy,cx,cy) ); d4 = cvGetSubRect( src_arr, d4stub, cvRect(0,cy,cx,cy) ); if(src_arr!=dst_arr){ if( !CV_ARE_TYPES_EQ( q1, d1 )){ cvError( CV_StsUnmatchedFormats, "cvShiftDFT", "Source and Destination arrays must have the same format", __FILE__, __LINE__ ); } cvCopy(q3, d1, 0); cvCopy(q4, d2, 0); cvCopy(q1, d3, 0); cvCopy(q2, d4, 0); } else{ cvCopy(q3, tmp, 0); cvCopy(q1, q3, 0); cvCopy(tmp, q1, 0); cvCopy(q4, tmp, 0); cvCopy(q2, q4, 0); cvCopy(tmp, q2, 0); } } int main(int argc, char ** argv) { //const char* filename = argc =2 ? argv : "lena.jpg"; IplImage * im; IplImage * realInput; IplImage * imaginaryInput; IplImage * complexInput; int dft_M, dft_N; CvMat* dft_A, tmp; IplImage * image_Re; IplImage * image_Im; double m, M; im = cvLoadImage( "E:\\OPENCV_PROJECT\\person.jpg", CV_LOAD_IMAGE_GRAYSCALE ); if( !im ) return -1; realInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1); imaginaryInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 1); complexInput = cvCreateImage( cvGetSize(im), IPL_DEPTH_64F, 2); cvScale(im, realInput, 1.0, 0.0); cvZero(imaginaryInput); cvMerge(realInput, imaginaryInput, NULL, NULL, complexInput); dft_M = cvGetOptimalDFTSize( im-height - 1 ); dft_N = cvGetOptimalDFTSize( im-width - 1 ); dft_A = cvCreateMat( dft_M, dft_N, CV_64FC2 ); image_Re = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1); image_Im = cvCreateImage( cvSize(dft_N, dft_M), IPL_DEPTH_64F, 1); // copy A to dft_A and pad dft_A with zeros cvGetSubRect( dft_A, tmp, cvRect(0,0, im-width, im-height)); cvCopy( complexInput, tmp, NULL ); cvGetSubRect( dft_A, tmp, cvRect(im-width,0, dft_A-cols - im-width, im-height)); //cvZero( tmp ); // no need to pad bottom part of dft_A with zeros because of // use nonzero_rows parameter in cvDFT() call below cvDFT( dft_A, dft_A, CV_DXT_FORWARD, complexInput-height ); cvNamedWindow("win", 0); cvNamedWindow("magnitude", 0); cvShowImage("win", im); // Split Fourier in real and imaginary parts cvSplit( dft_A, image_Re, image_Im, 0, 0 ); // 计算功率谱 Mag = sqrt(Re^2 + Im^2) cvPow( image_Re, image_Re, 2.0); cvPow( image_Im, image_Im, 2.0); cvAdd( image_Re, image_Im, image_Re, NULL); cvPow( image_Re, image_Re, 0.5 ); // 计算 log(1 + Mag) cvAddS( image_Re, cvScalarAll(1.0), image_Re, NULL ); // 1 + Mag cvLog( image_Re, image_Re ); // log(1 + Mag) // 重新安排四个象限,使得原点在图像中心 cvShiftDFT( image_Re, image_Re ); // 调整显示象素的区间,保证最大值为白色,最小值为黑色 cvMinMaxLoc(image_Re, m, M, NULL, NULL, NULL); cvScale(image_Re, image_Re, 1.0/(M-m), 1.0*(-m)/(M-m)); cvShowImage("magnitude", image_Re); cvWaitKey(-1); return 0; } */ /* P99_read vedio with CVCAM (not use) widthStep表示存储一行像素需要的字节数。 widthStep必须是4的倍数,如果8U图像宽度为3,那么widthStep是4,加一个字节补齐。这个图像的一行需要4个字节,只使用前3个,最后一个空在那儿不用。 也就是一个宽3高3的图像的imageData数据大小为4*3=12字节。 如果32F的图像,那么widthStep=width*4 */ /* # includecvcam.h void callback(IplImage* image);// declaration of the Callback Funcion int main() { int ncams = cvcamGetCamerasCount();// return the number of cameras available HWND MyWin; // set the System Properties cvcamSetProperty( 0, CVCAM_PROP_ENABLE, CVCAMTRUE );// choose Camera 1 // camera cvcamSetProperty( 0, CVCAM_PROP_RENDER, CVCAMTRUE );// We' ll render stream // In this program, we suppose to create a window "ID", which is defined in MyWin // "MyWin" is of type "HWND" MyWin = (HWND) cvGetWindowHandle("cvcam window"); // Select a window for vedio rendering cvcamSetProperty( 0, CVCAM_PROP_WINDOW, MyWin ); // use the Callback Function "callback" to process every frame cvcamSetProperty( 0, CVCAM_PROP_CALLBACK, callback ); cvcamInit(); cvcamStart(); // ***** Now the program starts ***** cvWaitKey(0); cvcamStop(); cvcamExit(); return 0; } // Callback Function: drawing Blue Horizontal Line in the image void callback( IplImage* image) { IplImage* image1 = image; int i,j; assert ( image ); for ( i = 0; i image1-height; i += 10 ) { for ( j = (image1-widthStep) * i; j (image1-widthStep) * (i+1); j += image1-nChannels ) { image1-imageData = (char)255; image1-imageData = 0; image1-imageData = 0; } } } */
0 个评论
qq
收缩
  • 电话咨询

  • 04714969085

关于我们| 联系我们| 诚征英才| 对外合作| 产品服务| QQ

手机版|Archiver| |繁體中文 手机客户端  

蒙公网安备 15010502000194号

Powered by Discuz! X2.5   © 2001-2013 数学建模网-数学中国 ( 蒙ICP备14002410号-3 蒙BBS备-0002号 )     论坛法律顾问:王兆丰

GMT+8, 2025-8-4 07:51 , Processed in 0.526806 second(s), 24 queries .

回顶部