473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

how to simulate a mouse click using opencv (c/c++)

I'm working a project. It's about screen control. I write the program using c/c++ in visual studio 2008. I just use my hand to replace mouse to control screen. The code is given below:
Expand|Select|Wrap|Line Numbers
  1. //Must have the following line for console mode
  2. #include "stdafx.h"
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <math.h>
  6. #include <conio.h>
  7.  
  8. #include <cv.h>
  9. #include <cxcore.h>
  10. #include <highgui.h>
  11.  
  12.  
  13. CvPoint2D32f srcpoints[4];
  14. CvPoint temppoints[4];
  15. CvPoint2D32f dstpoints[4];
  16.  
  17. int n = 0;
  18. IplImage* src=0;
  19. CvScalar color = CV_RGB(0,0,255);
  20. CvScalar color1 = CV_RGB(255,255,255);
  21.  
  22. bool PointsCaptured = false;
  23.  
  24. //4-times mouse click
  25. void on_mouse( int event, int x, int y, int flags,void* param )
  26. {
  27.     switch( event )
  28.     {
  29.     case CV_EVENT_LBUTTONDOWN:
  30.  
  31.         if (n<4) 
  32.         {
  33.             temppoints[n] =cvPoint(x,y);
  34.  
  35.             srcpoints[n] =cvPointTo32f(temppoints[n]);
  36.  
  37.             n++;
  38.             printf("Mouse Clicked, n = %d, (x,y) = (%d,%d) \n",n,x,y);
  39.  
  40.             if (n == 4)  
  41.             { 
  42.                 PointsCaptured = true;
  43.                 printf("n is now equal to 4\n");
  44.             }
  45.  
  46.  
  47.         }
  48.     }
  49. }
  50.  
  51. //Find the centroid of the maxpoint
  52. void FindCentroid(const IplImage *src, const IplImage *mask, double maxpt_Threshold, CvPoint2D32f *ptMaxLoc )
  53. {
  54.     int height = src->height;
  55.     int width = src->width;
  56.     if(height == 0 || width == 0) return;
  57.  
  58.     unsigned char *srcdata,*maskdata;
  59.  
  60.     srcdata = (unsigned char*)src->imageData ;
  61.     maskdata = (unsigned char*)mask->imageData ;
  62.     unsigned int srcindex = 0;
  63.     unsigned int maskindex = 0;
  64.     unsigned int maskindexrange = height * width;
  65.     unsigned int val = 0;
  66.     unsigned int max_srcindex = 0;
  67.     unsigned int max_maskindex = 0;
  68.     double sumVal = 0;
  69.     double sumxVal = 0;
  70.     double sumyVal = 0;
  71.  
  72.     int Threshold = (int) maxpt_Threshold  ;
  73.  
  74.     for(maskindex=0; maskindex < maskindexrange;  maskindex++)
  75.     {   
  76.         //val = (0.1140*srcdata[srcindex++] + 0.5870*srcdata[srcindex++] + 0.2989*srcdata[srcindex++]); 
  77.         //val = (srcdata[srcindex++] + srcdata[srcindex++] + srcdata[srcindex++]); 
  78.         val = (float)srcdata[srcindex++] ; // for grayscale image
  79.         if( ( val >= Threshold) && maskdata[maskindex] )
  80.         {    
  81.             // find the centroid of the lightspot - assuming there is only one spot!!
  82.             sumVal += (float)val;
  83.             sumxVal += (float)val*(float)fmod((double)maskindex,(double)width);
  84.             sumyVal += (float)val*(float)floor((double)maskindex/(double)width);
  85.         }
  86.     }
  87.  
  88.     if (sumVal >= Threshold) // i.e. true even if there is only one single pixel brighter than the threshold
  89.     {
  90.         ptMaxLoc->x = sumxVal / sumVal ;    
  91.         ptMaxLoc->y = sumyVal / sumVal ;      
  92.         printf("findcentroid: %f %f %f\n", sumVal, ptMaxLoc->x,ptMaxLoc->y);
  93.         SetCursorPos(ptMaxLoc->x,ptMaxLoc->y);
  94.     } else
  95.     {
  96.         ptMaxLoc->x = -1.0 ;    // i.e. no centroid found
  97.         ptMaxLoc->y = -1.0 ;
  98.         printf("findcentroid: %f %f %f\n", sumVal, ptMaxLoc->x,ptMaxLoc->y);
  99.     }
  100. }
  101.  
  102. //Find the maxpoint
  103. void FindMaxPoint(const IplImage *img, double *maxValR, double *maxXR, double *maxYR  )
  104. {
  105.         CvScalar p;
  106.  
  107.         // Process the image pixel by pixel!
  108.         double maxVal, maxX, maxY, Y;
  109.         int A, B;
  110.  
  111.         int height = img->height;
  112.         int width = img->width;
  113.  
  114.         maxVal=0; maxX=0; maxY=0;
  115.         for(int j=0;j<height;j++) 
  116.         {
  117.             for(int i=0;i<width;i++) 
  118.             {
  119.                 p = cvGet2D(img,j,i);    // get pixel values from input image
  120.                 Y =( p.val[2]+p.val[1]+p.val[0])/3;
  121.  
  122.                 if(Y>maxVal)
  123.                 {    
  124.                     maxVal=Y; maxX=i; maxY=j;
  125.                 }
  126.             }
  127.         }
  128.  
  129.         *maxXR = maxX; 
  130.         *maxYR = maxY;
  131.         *maxValR = maxVal;
  132. }
  133.  
  134. int main(int argc, char *argv[])
  135. {
  136.   /////////////////////////
  137.   // 0. Initialization      
  138.   /////////////////////////
  139.  
  140.   // Variables for holding the images or frames
  141.   IplImage* ImageIn = 0;
  142.   IplImage* ImageOut = 0;
  143.   IplImage* ImageGray = 0;
  144.   IplImage* ImageMask = 0;
  145.  
  146.   // For Input Image Information
  147.   int height, width, size, channels;
  148.   // width
  149.    int cx = GetSystemMetrics(SM_CXSCREEN);
  150.    // height
  151.    int cy = GetSystemMetrics(SM_CYSCREEN);
  152.  
  153.  
  154.  
  155.   CvPoint2D32f ptMaxLoc;
  156.   double  ThresholdLevel;
  157.  
  158.  
  159.   ///////////////////////////////////////////////////////
  160.   // 1. Initialize and Setup the Camera
  161.   ///////////////////////////////////////////////////////
  162.  
  163.   CvCapture* capture = 0;
  164.   capture = cvCaptureFromCAM( 0 ); // capture the first camera found
  165.   if( !capture )
  166.   {
  167.       fprintf(stderr,"Could not initialize capturing...\n");
  168.       return -1;
  169.   }
  170.  
  171.   //Set the camera input width and height 
  172.   cvQueryFrame(capture); // this call is necessary to get correct 
  173.                          // capture properties
  174.   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 320);
  175.   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 240);
  176.   // Read the camera width and height - note: it may not always end up what we wanted.
  177.   height    = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
  178.   width    = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  179.  
  180.  
  181.   /////////////////////////////////////////////////////
  182.   // 2. SETTING UP THE DISPLAY WINDOWS AND IMAGE FRAMES 
  183.   /////////////////////////////////////////////////////
  184.  
  185.   printf("\nProcessing %dx%d video images\n", width, height ); 
  186.   printf("\nPress ESC key to exit program\n"); 
  187.  
  188.   // Initialize Input and Output Frames 
  189.   ImageIn = cvCreateImage( cvSize(width, height), IPL_DEPTH_8U, 3 ); // 3 channels = color
  190.   ImageOut = cvCreateImage( cvSize(width, height), IPL_DEPTH_8U, 3 ); // 3 channels = color
  191.   ImageGray = cvCreateImage( cvSize(width, height), IPL_DEPTH_8U, 1 ); // 3 channels = color
  192.   ImageMask = cvCreateImage( cvSize(width, height), IPL_DEPTH_8U, 1 );
  193.  
  194.   cvSet(ImageMask,cvScalar(255)); //  Set Mask to Entire Frame for now (reserved)
  195.  
  196.   // Create two windows to display the images (input and output)
  197.   cvNamedWindow("Input Image", CV_WINDOW_AUTOSIZE); 
  198.   cvNamedWindow("Output Image", CV_WINDOW_AUTOSIZE); 
  199.  
  200.   cvSetMouseCallback( "Input Image", on_mouse );
  201.  
  202.   ////////////////////////////////////////
  203.   // 2.5 Calibration Loop ...
  204.   ////////////////////////////////////////
  205.   char key = 0;
  206.   while( (key != 27) &&  !PointsCaptured  ) // 27 = 'ESC' 
  207.   {
  208.     // The following lines monitor to see if any key has been pressed 
  209.     key = (char) cvWaitKey(1);  // get key from OpenCV Image Windows
  210.     if (key==-1) if (_kbhit()) key = _getch(); // no key entered, so check the console window also
  211.     //if (key=='c' || key=='C') {VI.showSettingsWindow(device1); }  // key="C" => Show Camera Control 
  212.  
  213.  
  214.     // GRAB THE NEW VIDEO FRAME
  215.      ImageIn = cvQueryFrame( capture );
  216.  
  217.     // show the images before and after processing
  218.     cvShowImage("Input Image", ImageIn );
  219.   }
  220.  
  221.     printf("Points Captured\n The Points Are: \n");
  222.     for (int i = 0; i<4;i++)
  223.     {
  224.     printf("point %d = (%4.1f,%4.1f)\n", i, srcpoints[i].x,srcpoints[i].y);
  225.     }
  226.  
  227.     CvMat mat;
  228.     double data[] = {0,0,0,0,0,0,0,0,0};
  229.  
  230.     cvInitMatHeader(&mat,3,3,CV_64FC1,data );
  231.  
  232.     float mxx = 320;
  233.     float mxy = 240;
  234.  
  235.     dstpoints[0].x=0;
  236.     dstpoints[0].y=0;
  237.     dstpoints[1].x=mxx;
  238.     dstpoints[1].y=0;
  239.     dstpoints[2].x=mxx;
  240.     dstpoints[2].y=mxy;
  241.     dstpoints[3].x=0;
  242.     dstpoints[3].y=mxy;
  243.  
  244.     cvGetPerspectiveTransform(srcpoints,dstpoints,&mat );    //Calculates the perspective transform from 4 corresponding points
  245.  
  246.     printf("H Matrix Obtained: \n");
  247.  
  248.     printf("%13.8f, %13.8f, %13.8f \n", cvmGet(&mat,0,0), cvmGet(&mat,1,0), cvmGet(&mat,2,0));
  249.     printf("%13.8f, %13.8f, %13.8f \n", cvmGet(&mat,0,1), cvmGet(&mat,1,1), cvmGet(&mat,2,1));
  250.     printf("%13.8f, %13.8f, %13.8f \n", cvmGet(&mat,0,2), cvmGet(&mat,1,2), cvmGet(&mat,2,2));
  251.  
  252.     printf("\n");
  253.  
  254.  
  255.   /////////////////////////////////////////////////////
  256.   // 3. THE MAIN LOOP - Continues forever until the ESC key (ASCII = 27) is pressed
  257.   /////////////////////////////////////////////////////
  258.   key = 0;
  259.   while( key != 27 ) // 27 = 'ESC' 
  260.   {
  261.     // The following lines monitor to see if any key has been pressed 
  262.     key = (char) cvWaitKey(1);  // get key from OpenCV Image Windows
  263.     if (key==-1) if (_kbhit()) key = _getch(); // no key entered, so check the console window also
  264.     //if (key=='c' || key=='C') {VI.showSettingsWindow(device1); }  // key="C" => Show Camera Control 
  265.  
  266.     ///////////////////////////////////////////////////////////////////
  267.     // Check if a new video frame is available, if yes then process it. 
  268.     ///////////////////////////////////////////////////////////////////
  269.  
  270.       // GRAB THE NEW VIDEO FRAME
  271.      ImageIn = cvQueryFrame( capture );
  272.  
  273.     //cvFlip(ImageIn, NULL, 1);
  274.  
  275.     if( ImageIn )
  276.     {
  277.       // Process the Video Input (ImageIn) and Save Result in ImageOut
  278.       // In this case we just make a copy, i.e. ImageOut = ImageIn;
  279.       //cvCopy(ImageIn, ImageOut, 0);
  280.  
  281.         CvScalar p, q, r; //s;
  282.  
  283.         double maxval, maxX, maxY;
  284.         maxval = 0;
  285.         maxX = -1;
  286.         maxY = -1;
  287.  
  288.         // Find Centroid in Image Input
  289.         ThresholdLevel = 100;
  290.         cvCvtColor(ImageIn, ImageGray,CV_BGR2GRAY);
  291.         FindMaxPoint(ImageIn,&maxval,&maxX,&maxY);
  292.         FindCentroid(ImageGray, ImageMask, ThresholdLevel, &ptMaxLoc);
  293.         cvLine(ImageIn,cvPoint(maxX,maxY),cvPoint(maxX,maxY),cvScalar(0,0,255),4,8,0);
  294.         cvRectangle(ImageIn, cvPoint(maxX-5,maxY-5), cvPoint(maxX+5,maxY+5), cvScalar(0,0,255), 1, 8, 0);
  295.  
  296.  
  297.         if ((maxX >= 0) && (maxX < 320) && (maxY >= 0) && (maxY < 240))
  298.         {
  299.  
  300.             p = cvGet2D(ImageGray,maxY,maxX);
  301.             maxval = p.val[0]; 
  302.             printf("maxval = %f\n",maxval);
  303.  
  304.             double ti =   maxX * cvmGet(&mat,2,0) + maxY * cvmGet(&mat,2,1) + 1*cvmGet(&mat,2,2) ;
  305.             double xp = ( maxX * cvmGet(&mat,0,0) + maxY * cvmGet(&mat,0,1) + 1*cvmGet(&mat,0,2) ) / ti;
  306.             double yp = ( maxX * cvmGet(&mat,1,0) + maxY * cvmGet(&mat,1,1) + 1*cvmGet(&mat,1,2) ) / ti;
  307.  
  308.             maxX = xp;
  309.             maxY = yp;
  310.  
  311.             if (maxval > 200) 
  312.             {
  313.                 //SetCursorPos(maxX*1440.0/320.0,maxY*800.0/240.0);
  314.                 //SetCursorPos((int)(maxX * 1280/320.0),(int)(maxY * 800/240.0));
  315.                 SetCursorPos((int)(maxX * (double)(cx)/320.0),(int)(maxY * (double)(cy)/240.0));        
  316.             }
  317.         }
  318.         cvWarpPerspective(ImageIn,ImageOut,&mat,CV_INTER_LINEAR,cvScalarAll(0));//applies a perspective transformation to an image
  319.  
  320.         // show the images before and after processing
  321.         cvShowImage("Input Image", ImageIn );
  322.         cvShowImage("Output Image", ImageOut );
  323.  
  324.     } // end if(VI.isFrameNew(device1))
  325.   }   // end while( key != 27 ) // 27 = 'ESC' 
  326.  
  327.   ////////////////////////////////////////////
  328.   // 4. EXIT: clean up before you go ...
  329.   ////////////////////////////////////////////
  330.  
  331.   cvReleaseCapture( &capture );
  332.   // release the image - can't use these - program crashes! weird.
  333.   // Appearantly, wou can't release a image that pointer to a buffer. 
  334.   // Msg from .h file: !!!DO NOT RELEASE or MODIFY the retrieved frame!!! 
  335.  
  336.   // close all windows
  337.   cvDestroyWindow("Input Image"); 
  338.   cvDestroyWindow("Output Image");
  339.  
  340.   return 0;
  341. }
  342.  
for the program, I just can control the mouse already. But I don't know how to simulate a mouse click. Can anybody help me now? thank you
Nov 4 '10 #1
0 3065

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Nick Wedd | last post by:
I have this <DIV id="canopy" onClick="myhandler(event.x,event.y); return false;"> <IMG border=0 height=66 width=292 src="gifs/top.gif"> </DIV> which works in IE. myhandler gets called with the...
3
by: Ryan Liu | last post by:
Can someone give a sample to prevent a row from being deleted in a datatable? I tried e.Row.RejectChanges(); in dt_RowDeleting() but seems does not work. I need verify if there other data...
3
by: Glenn Palomar | last post by:
Hi, Instead of using user32 API for simulating mouse click (left down, left up, etc.), are there any .net function/class that i can use? Public Declare Sub mouse_event Lib "user32" (ByVal...
3
by: madhuri.eerupula | last post by:
Hi. How to simulate(automatic) mouse movements and click operation using c#. Actually, i got pixels in the face (face tracking) right now and i need to move mouse(automatically, without using...
4
by: Abhishek | last post by:
Hi, I have a activex web browser embedded in a windows form and on a click of a form button i need the mouse to go the position for example 100, 100 and click the link that will be there on that...
3
by: Morten Snedker | last post by:
If I have a number of random applications open, move the mouse cursor to a given position and do a click, the application gets the focus. That is what this simple code should illustrate: Dim...
18
by: eliss.carmine | last post by:
Is it possible to simulate a mouse click in the window I made (it's a Form), but not give it focus? I tried using WinAPI's mouseevent and SendMessage of WM_LBUTTONDOWN/WM_LBUTTONUP as suggested...
5
by: nuhfeken | last post by:
We have a C# winform that uses the MVP design pattern for the user interface. For reasons I'd rather not explain we need to simulate a right mouse click on a specific control to deactivate the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.