通过鼠标和键盘的操作来实现图像的平移,操作方法:用鼠标的话直接拖动图像即可,用键盘的话,使用wsad四个键
来控制图像平移方向,w上,s下,a左,d右。
#include <cv.h> #include <highgui.h> IplImage* org = 0; IplImage* tmp = 0; IplImage* dst = 0; CvRect rect; //保存图像显示区域 void moveImage()//实现移动 { cvCopy(tmp,dst); cvSetImageROI(dst,rect); cvCopy(org,dst); cvResetImageROI(dst); cvShowImage("image",dst); } void on_mouse( int event, int x, int y, int flags, void* ustc) { static CvPoint p={-1,-1}; static int xrect; static int yrect; if(event==CV_EVENT_LBUTTONDOWN) { p=cvPoint(x,y); xrect=rect.x; yrect=rect.y; } else if(event==CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON)) { int dx=x-p.x; int dy=y-p.y; if(x>=rect.x && x<=rect.x+rect.width-1 && y>=rect.y && y<=rect.y+rect.height-1) { rect=cvRect(xrect+dx,yrect+dy,org->width,org->height); if(rect.x<0) { rect.x=0; } if(rect.y<0) { rect.y=0; } if(rect.x > dst->width - org->width-1) { rect.x=dst->width-org->width-1; } if(rect.y > dst->height - org->height-1) { rect.y=dst->height-org->height-1; } moveImage(); } } } int main() { org=cvLoadImage("test.bmp",1); rect=cvRect(0,0,org->width,org->height); tmp=cvCreateImage(cvSize(org->width*2,org->height*1.5),org->depth,org->nChannels); cvSet(tmp,CV_RGB(192,192,192)); dst=cvCreateImage(cvSize(org->width*2,org->height*1.5),org->depth,org->nChannels); cvSet(dst,CV_RGB(192,192,192)); cvSetImageROI(dst,cvRect(0,0,org->width,org->height)); cvCopy(org,dst); cvResetImageROI(dst); cvNamedWindow("image",1); cvShowImage("image",dst); cvSetMouseCallback( "image", on_mouse, 0 ); cvWaitKey(0); while (1) { int key = cvWaitKey (10); switch (key) { case 'w': rect=cvRect(rect.x,rect.y-20,org->width,org->height); if (rect.y <= 0) rect.y = 0; moveImage(); break; case 's': rect=cvRect(rect.x,rect.y+20,org->width,org->height); if (rect.y >= org->height*0.5) rect.y = org->height*0.5; moveImage(); break; case 'a': rect=cvRect(rect.x-20,rect.y,org->width,org->height); if (rect.x <= 0) rect.x = 0; moveImage(); break; case 'd': rect=cvRect(rect.x+20,rect.y,org->width,org->height); if (rect.x >= org->width) rect.x = org->width; moveImage(); break; } } cvDestroyAllWindows(); cvReleaseImage(&org); cvReleaseImage(&tmp); cvReleaseImage(&dst); return 0; }