這個程序類似於淘寶購物時,在商品圖像上移動鼠標,會出現一個放大鼠標周圍矩形區域內的局部圖像的窗口。話不多說,直接貼代碼。
- #include <cv.h>
- #include <highgui.h>
- #include <stdio.h>
- #pragma comment( lib, "cv.lib" )
- #pragma comment( lib, "cxcore.lib" )
- #pragma comment( lib, "highgui.lib" )
- IplImage* org = 0;
- IplImage* img = 0;
- IplImage* dst = 0;
- int foo=60;
- void on_mouse( int event, int x, int y, int flags, void* ustc)
- {
- if( event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))
- {
- cvCopy(org,img);
- CvPoint p0;
- CvPoint p1;
- if(x<foo)
- {
- if(y<foo)
- {
- p0=cvPoint(0,0);
- p1=cvPoint(2*foo,2*foo);
- }
- else if(y>img->height-foo)
- {
- p0=cvPoint(0,img->height-2*foo);
- p1=cvPoint(2*foo,img->height);
- }
- else
- {
- p0=cvPoint(0,y-foo);
- p1=cvPoint(2*foo,y+foo);
- }
- }
- else if(x>img->width-foo)
- {
- if(y<foo)
- {
- p0=cvPoint(img->width-2*foo,0);
- p1=cvPoint(img->width,2*foo);
- }
- else if(y>img->height-foo)
- {
- p0=cvPoint(img->width-2*foo,img->height-2*foo);
- p1=cvPoint(img->width,img->height);
- }
- else
- {
- p0=cvPoint(img->width-2*foo,y-foo);
- p1=cvPoint(img->width,y+foo);
- }
- }
- else
- {
- if(y<foo)
- {
- p0=cvPoint(x-foo,0);
- p1=cvPoint(x+foo,2*foo);
- }
- else if(y>img->height-foo)
- {
- p0=cvPoint(x-foo,img->height-2*foo);
- p1=cvPoint(x+foo,img->height);
- }
- else
- {
- p0=cvPoint(x-foo,y-foo);
- p1=cvPoint(x+foo,y+foo);
- }
- }
- cvRectangle(img,p0,p1,CV_RGB(0,255,0));
- cvSetImageROI(org,cvRect(p0.x,p0.y,p1.x-p0.x,p1.y-p0.y));
- cvResize(org,dst);
- cvResetImageROI(org);
- cvShowImage( "img", img );
- cvShowImage("dst",dst);
- }
- }
- int main()
- {
- org=cvLoadImage("lena.jpg",1);
- img=cvCloneImage(org);
- dst=cvCreateImage(cvSize(foo*4,foo*4),org->depth,org->nChannels);
- cvNamedWindow("img",1);
- cvSetMouseCallback( "img", on_mouse, 0 );
- cvShowImage("img",img);
- cvNamedWindow("dst",1);
- cvWaitKey(0);
- cvDestroyAllWindows();
- cvReleaseImage(&org);
- cvReleaseImage(&img);
- cvReleaseImage(&dst);
- return 0;
- }
效果圖如下