Motion Tracking test using openCV

BlitzMax Forums/BlitzMax Programming/Motion Tracking test using openCV

Ziltch(Posted 2008) [#1]
Here is a test of simple motion tracking for windows.

http://www.members.optusnet.com.au/ziltch/TrackerTest.zip

The zip contains an exe and the needed dll's for running the test. You will just need a webcam.

Included is also the source but you will need to download openCV from sourceforge if you wish to modify the dll I did the c code in. I used Devcpp to write the dll. My c is very rough , so if any one has any improvements, please tell me!

The main problem that i have been tring to improve is the FPS. with a 640x480 webcam the max I get is 3-4 FPS. I spent ages trying to figure out how to change the resolution of the camera but found out the commands in openCV to do this are not working.

When running the programing, after the webcam vid appears, you can use the left mouse button to draw tracking points.


Scaremonger(Posted 2008) [#2]
Does this contain a Blitzmax wrapper for the OpenCV library?


Ziltch(Posted 2008) [#3]
No. It is not needed. The bitzmax code uses the openCV commands from the openCV dll's and I wrote a c dll to keep the tracking code simple.

The program also has a linedraw effect mode option on the webcam input.


Danny(Posted 2015) [#4]
sorry to bump up this old thing, but link is dead.

Does anyone have a copy of that TrackerTest.zip, or the openCV dll Ziltch mentions?!

Cheers,

Danny.


Yahfree(Posted 2015) [#5]
I think if you download openCV (opencv.org) the DLL's will be in the /bin folder.


atv(Posted 2016) [#6]
That wouldn't give his code, just the opencv dll's. I understood he made his own. I'd be interested in the trackertest code as well.


Ziltch(Posted 2016) [#7]
I think this is the code from the zip. I hope it helps. It is a long time ago and I have not used blitzmax in a while just purebasic.

Strict

Import MaxGui.Drivers



Extern "Win32"

Type T_IplImage
'Field nSize:Int'          SizeOf(IplImage) 
Field ID:Int     '          version (=0)
Field nChannels:Int' '      Most of OpenCV functions support 1,2,3 Or 4 channels 
Field alphaChannel:Int''   ignored by OpenCV 
Field depth:Int  '          pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U,IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F And IPL_DEPTH_64F are supported 
Field colorModel'  ignored by OpenCV 
Field channelSeq'  ditto 
Field dataOrder:Int  '      0 - interleaved color channels, 1 - separate color channels.	cvCreateImage can only create interleaved images 
Field origin:Int  '         0 - top-Left origin,	1 - bottom-Left origin (Windows bitmaps style) 
Field  align:Int  '          Alignment of image rows (4 Or 8).	OpenCV ignores it And uses widthStep instead 
Field width:Int  '          image width in pixels 
Field Height:Int  '         image height in pixels 
Field _IplROI:Int Ptr  '   *roi' image ROI. when it is Not Null, this specifies image region To process 
Field _IplImage:Int  '   *maskROI'  must be Null in OpenCV 
Field imageId:Int  '      ditto 
Field _IplTileInfo:Int ' *tileInfo'  ditto 
Field imageSize:Int  '      image data size in bytes 	(=image.height * image.widthStep in Case of interleaved data)
Field imageData:Int Ptr  '   pointer To aligned image data 
Field widthStep:Int  '    size of aligned image row in bytes 
Field BorderMode'  border completion mode, ignored by OpenCV 
Field BorderConst'  ditto 
Field imageDataOrigin:Int Ptr  '  pointer To a very origin of image data	(Not necessarily aligned) -	it is needed For correct image deallocation 
End Type
	
Type CAPDRIVERCAPS
Field wDeviceIndex:Int 
Field fHasOverlay:Byte
Field fHasDlgVideoSource:Byte
Field fHasDlgVideoFormat:Byte
Field fHasDlgVideoDisplay:Byte
Field fCaptureInitialized:Byte
Field fDriverSuppliesPalettes:Byte
Field hVideoIn:Int
Field hVideoOut:Int
Field hVideoExtIn:Int
Field hVideoExtOut:Int
End Type

End Extern


'-----

Local TrackerLib = LoadLibraryA("Tracker.dll")
'Local TrackerLib = LoadLibraryA("Tracker.dll")
Global StartCam (CamIndex)
Global StartAviCap (FileName:String)
Global UpdateCam:T_IplImage (need_to_init) 
Global EndCam  ()
Global AddTrackingPoint( X,  Y)
Global GetTrackingPointer:Byte Ptr()
Global GetTrackingCount:Int()
Global ClearTrackingPoints()
Global SetLineDrawMode(LineDrawMode:Int)
Global GetCaptureFileFramePos()

StartCam = GetProcAddress (TrackerLib,"StartCam")
StartAviCap = GetProcAddress (TrackerLib,"StartAviCap")
UpdateCam = GetProcAddress (TrackerLib,"UpdateCam")
EndCam  = GetProcAddress (TrackerLib,"EndCam")
AddTrackingPoint= GetProcAddress (TrackerLib,"AddTrackingPoint")
GetTrackingPointer= GetProcAddress (TrackerLib,"GetTrackingPointer")
GetTrackingCount = GetProcAddress (TrackerLib,"GetTrackingCount")
ClearTrackingPoints = GetProcAddress (TrackerLib,"ClearTrackingPoints")
SetLineDrawMode = GetProcAddress (TrackerLib,"SetLineDrawMode")
GetCaptureFileFramePos = GetProcAddress (TrackerLib,"GetCaptureFileFramePos")


'
'Local CXCoreLib =  LoadLibraryA("libcxcore200.dll")
'
'Global cvCreateImage:T_IplImage(width,Height , depth, channels )
'cvCreateImage = GetProcAddress (CXCoreLib,"cvCreateImage")



'-----

Type T_CvSize
    Field width
    Field Height
End Type

Type T_Rect
    Field X
    Field Y	
    Field width 
    Field Height
EndType

'-----

'SetGraphicsDriver D3D7Max2DDriver:TD3D7Max2DDriver()
'SetGraphicsDriver D3D9Max2DDriver()
SetGraphicsDriver GLMax2DDriver()

Global CamDispWidth =320
Global CamDispHeight=240
Global CamWidth =640
Global CamHeight=480
Global DispRatioW:Float,DispRatioH:Float
Global Fs:T_CvSize = New T_CvSize

Local HeadFont:TGuiFont  =  LoadGuiFont("Arial",14)
Global Window:TGadget =CreateWindow("Ziltch Tracker Test",0,0,CamDispWidth+40,CamDispHeight+180)

Global PaintCamButton:TGadget = CreateButton("Ziltch Tracker",10,10,CamDispWidth,30,Window,LABEL_CENTER|BUTTON_PUSH)
SetGadgetFont PaintCamButton,HeadFont
Global CamCanvas:TGadget = CreateCanvas(10,50,CamDispWidth,CamDispHeight,Window,GRAPHICS_BACKBUFFER)
Global ExitButton:TGadget = CreateButton("Exit",CamDispWidth-65,CamDispHeight+60,80,24,Window,BUTTON_PUSH)

Global CamCanvashWnd:Int = QueryGadget(CamCanvas,QUERY_HWND)

SetMinWindowSize( Window,64,64 )
SetGadgetLayout(PaintCamButton,EDGE_RELATIVE,EDGE_RELATIVE,EDGE_ALIGNED,0)
SetGadgetLayout(CamCanvas,EDGE_RELATIVE,EDGE_RELATIVE,EDGE_ALIGNED,EDGE_RELATIVE)
SetGadgetLayout(ExitButton,0,EDGE_ALIGNED,0,EDGE_ALIGNED)


'-----

Global G:TGraphics=CanvasGraphics(CamCanvas)
SetGraphics G
Local DisplayCam = True ,NeedToInit
Global FrameTimer:TTimer,UpdateTimer:TTimer
Local WebCamInit,TrackingPointCount=1 ,tp:Byte Ptr 
Local Gadget:tgadget,EvData , EvSource:TGadget
Local Frame:T_IplImage
Local Pixmap:TPixmap
Local Pixmap2:TPixmap
Local TrackPointsBank:TBank
Local Count,tx,ty,mX,mY
Local LineDrawMode




Global CameraID=  1

Const  FrameSpeed = 5, UpdateSpeed = 10


UpdateTimer= CreateTimer(  UpdateSpeed)
FrameTimer= CreateTimer(  FrameSpeed)
EnablePolledInput()
StartCam(CameraID)




While WaitEvent()
    Gadget:tgadget = TGadget(EventSource())
    EvData = EventData()
    
    Select EventID()
        Case EVENT_TIMERTICK
        
            Select TTimer(EventSource())
            
                Case UpdateTimer		
                    'Debuglog  "UpdateCam"
                    Frame:T_IplImage = UpdateCam (0) 
                    DebugLog  "CaptureFileFramePos "+GetCaptureFileFramePos()
                    
                Case FrameTimer 
                    If Frame = Null Then
                        DebugLog "Frame capture Error"
                        'FrameProcesing = False
                        Continue
                    EndIf
                    
                    'DebugLog "FrameA "+FrameA
                    DispRatioW:Float = Frame.width/Float(CamDispWidth )
                    DispRatioH:Float  = Frame.Height / Float(CamDispHeight )
                    
                    
                    If DisplayCam Then
                        'DebugLog "Frame.imageData = "+Int( Frame.imageData)
                        Pixmap:TPixmap = Null
                        If LineDrawMode Then
                            Pixmap:TPixmap = CreateStaticPixmap( Frame.imageData,Frame.width,Frame.Height ,Frame.widthStep,PF_I8)
                        ElseIf Pixmap=Null 'or 	
                        
                            '  DebugLog "Make Pixmap"	
                            Pixmap:TPixmap = CreateStaticPixmap( Frame.imageData,Frame.width,Frame.Height ,Frame.widthStep,PF_BGR888)
                            'Pixmap:Tpixmap = CreatePixmap(Frame.width,Frame.Height,PF_BGR888 ,Frame.widthStep)
                            
                        EndIf	
                        '  Pixmap =  YFlipPixmap(Pixmap)
                        If CamDispWidth<> Frame.width Or CamDispHeight <>Frame.Height 
                            Pixmap2:TPixmap =  ResizePixmap ( Pixmap,CamDispWidth,CamDispHeight  )	
                            'cls
                            DrawPixmap( Pixmap2,0,0) 
                        Else
                            DrawPixmap( Pixmap,0,0) 
                        EndIf
                            
                        ' DrawPixmap( Pixmap,0,0)
                        ' Drawoval      (10,10,5,5)
                        'DebugLog "-------------------------------- "			
                    Else
                        Cls
                    EndIf
                    
                    '                    If KeyHit(KEY_SPACE)
                    '                        ClearTrackingPoints()
                    '                        DebugLog "ClearTrackingPoints 1"
                    '                    EndIf
                    
                    TrackingPointCount=GetTrackingCount()
                    '  DebugLog "TrackingPointCount  = " +TrackingPointCount
                    If TrackingPointCount
                        tp  = GetTrackingPointer()
                        If tp Then
                            '  DebugLog " tp = "+Int(tp)
                            Local TrackingPointCount2 = TrackingPointCount*2-2
                            TrackPointsBank:TBank = CreateStaticBank( tp,TrackingPointCount2*4+8 )
                            For Count  = 0 To TrackingPointCount2 Step 2
                                SetColor(255,50,50)
                                tx:Int = PeekFloat(TrackPointsBank,Count*4)/DispRatioW
                                ' ty:Int = (Frame.Height - PeekFloat(TrackPointsBank,Count*4+4))/DispRatioH
                                ty:Int = (PeekFloat(TrackPointsBank,Count*4+4))/DispRatioH
                                
                                '      DebugLog  Count+"  peek  tp = "+tx+" , "+ty
                                ' DrawOval(tx-3,ty,8,2)
                                DrawRect(tx-1,ty-1,2,2)
                            Next							
                        EndIf
                    EndIf
                    
                    
                    Flip
                    ActivateGadget( CamCanvas)
                    
            EndSelect
            
        Case EVENT_KEYDOWN
            Select EvData
                Case KEY_SPACE
                    ClearTrackingPoints()					
                    TrackingPointCount=GetTrackingCount()
                    '   DebugLog "ClearTrackingPoints 2"
                    
                Case KEY_ENTER
                    LineDrawMode= Not LineDrawMode
                    SetLineDrawMode(LineDrawMode)
                    
                Case KEY_ESCAPE
                
                    DebugLog "exit"
                    '					If FullScreen Then
                    '					'	DoFullScreen(False)
                    '					Else
                    Exit
                    'EndIf
                    
            End Select
            
        Case EVENT_MOUSEDOWN
            Select EvData
                Case 1
                    mX:Int = MouseX()
                    mY:Int = MouseY()
                    'AddTrackingPoint( mX*DispRatioW, (CamDispHeight-mY)*DispRatioH)
                    AddTrackingPoint( mX*DispRatioW, mY*DispRatioH)
                    Frame:T_IplImage = UpdateCam (0) 
                    ' DebugLog "TrackingPointCount="+GetTrackingCount()
                    ' DebugLog "mouse  "+mX+ ","+mY + "   Frame = "+Frame.width+" , "+Frame.Height+ "   DispRatio = "+DispRatioW+" , "+DispRatioH
                    
                Case 2
                    '					For mX = 40 To Frame.width-80 Step 80
                    '						For mY = Frame.Height-80 To 80 Step -80
                    '							AddTrackingPoint( mX*2, mY)
                    '							'Delay 10
                    '							Frame:T_IplImage = UpdateCam ()
                    '						Next	
                    '					Next	
                    
                    ClearTrackingPoints()	
                    Frame:T_IplImage = UpdateCam (1)                     
                    DebugLog  "FindGoodFeaturesToTrack  TrackingPointCount="+GetTrackingCount()
                    'TrackingPointCount=GetTrackingCount()
                    
                Case 3
                    DisplayCam = Not  DisplayCam
                    
            EndSelect
            
            
        Case EVENT_WINDOWSIZE
            Select Gadget
                Case Window
                    CamDispWidth = GadgetWidth(Window)-30
                    CamDispHeight = GadgetHeight(Window)-170
                    FreeGadget(CamCanvas)
                    CamCanvas = CreateCanvas(10,50,CamDispWidth,CamDispHeight,Window,GRAPHICS_BACKBUFFER)
                    'CamCanvashWnd= QueryGadget(CamCanvas,BBQID_WIN32HWND)
                    G=CanvasGraphics(CamCanvas)
                    SetGraphics G
                    ' Frame:T_IplImage = UpdateCam (1)  
                    SetGadgetLayout(CamCanvas,EDGE_RELATIVE,EDGE_RELATIVE,EDGE_ALIGNED,EDGE_RELATIVE)
                    'DebugLog "CamDisp  "+CamDispWidth+ ","+CamDispHeight + "   Frame = "+Frame.width+" , "+Frame.Height
                    Cls
                    Frame:T_IplImage = UpdateCam (0)   
                    Pixmap:TPixmap = CreateStaticPixmap( Frame.imageData,Frame.width,Frame.Height ,Frame.widthStep,PF_I8)
                    
                    DispRatioW:Float =Frame.width/Float(CamDispWidth )
                    DispRatioH:Float  = Frame.Height / Float(CamDispHeight )
            EndSelect	
            
        Case EVENT_GADGETACTION		
            Select Gadget 				
                Case ExitButton 
                    Exit
            EndSelect
            
        Case EVENT_APPTERMINATE
            Exit			
            
        Case EVENT_WINDOWCLOSE
            EvSource:TGadget = TGadget(EventSource())
            Select EvSource
                Case Window
                    Exit
            EndSelect
    EndSelect
    
Wend

EndCam  ()


Tracker.dll c code

//ziltch  tracking.dll  using opencv 2.3rc
#include "dll.h"
#include "E:\Dev-Cpp\include\windows.h"
#include "E:\Dev-Cpp\include\stdio.h"
#include "E:\Dev-Cpp\include\stdlib.h"
#ifdef _CH_
#pragma package <opencv>
#endif

#include "E:\OpenCV2-3rc\include\opencv\cv.h"
#include "E:\OpenCV2-3rc\include\opencv\highgui.h"
IplImage* frame = 0;


IplImage *image = 0,*image2 = 0, *grey = 0, *prev_grey = 0, *pyramid = 0, *prev_pyramid = 0, *swap_temp;
IplImage *edges = 0;

int win_size = 16;
const int MAX_COUNT = 500;
CvPoint2D32f* points[2] = {0,0}, *swap_points;
char* status = 0;
int count = 0 ,PointsTracked =0;

int flags = 0 , linedraw =0;
int add_remove_pt = 0;
CvPoint pt;
CvCapture* capture = 0;

DLLIMPORT CvCapture* GetCaptureHwnd()
{
 return capture;
}


DLLIMPORT AddTrackingPoint(int x, int y)
{
     pt = cvPoint(x,y);
     add_remove_pt = 1; 
     
     fprintf(stdout,"Add pt ... %i , %i \n",x,y); 
}

DLLIMPORT ClearTrackingPoints()
{
     count = 0;
     PointsTracked = 0;      
}

DLLIMPORT CvPoint2D32f* GetTrackingPointer()
{
    if( count > 0 )
    {            
        return points[0];
    }
}

DLLIMPORT int GetTrackingCount()
{
    return PointsTracked;
}

DLLIMPORT int SetLineDrawMode(int LineDrawMode)
{
    linedraw = LineDrawMode;      
    return linedraw;
}

DLLIMPORT int GetCaptureFileFramePos()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_POS_FRAMES);
}
DLLIMPORT int SetCaptureFileFramePos(int Pos)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_POS_FRAMES,Pos);
}

DLLIMPORT int GetCaptureFileFrameCount()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_COUNT);
}

DLLIMPORT int GetCaptureFileFramePosMsec()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_POS_MSEC);
}

DLLIMPORT double GetCaptureFilePosRatio() // 0.0 is start 1.0 is end.
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_POS_AVI_RATIO);
}

DLLIMPORT int GetCaptureFileFPS()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_FPS);
}

DLLIMPORT int GetCaptureFileFOURCC() // Video file codec type
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_FOURCC);
}

DLLIMPORT int GetCaptureFileFrameWidth()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH);
}

DLLIMPORT int GetCaptureFileFrameHeight()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT);
}

/*  These functions currently do not work in OpenCv
DLLIMPORT int GetCamBrightness()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_BRIGHTNESS);
}

DLLIMPORT int GetCamContrast()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_CONTRAST);
}

DLLIMPORT int GetCamSaturation()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_SATURATION);
}

DLLIMPORT int GetCamHue()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_HUE);
}

DLLIMPORT int GetCamGain()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_GAIN);
}

DLLIMPORT int GetCamExposure()
{      
    return cvGetCaptureProperty(capture,CV_CAP_PROP_EXPOSURE);
}


DLLIMPORT int SetCamBrightness(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_BRIGHTNESS,value);
}

DLLIMPORT int SetCamContrast(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_CONTRAST,value);
}

DLLIMPORT int SetCamSaturation(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_SATURATION,value);
}

DLLIMPORT int SetCamHue(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_HUE,value);
}

DLLIMPORT int SetCamGain(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_GAIN,value);
}

DLLIMPORT int SetCamExposure(double value)
{      
    return cvSetCaptureProperty(capture,CV_CAP_PROP_EXPOSURE,value);
}
*/


DLLIMPORT void FreeCamImage()
{
    image =0 ;
}

DLLIMPORT void EndCam ()
{
//  MessageBox (0, "StartCam\n", "Starting Camera", MB_ICONINFORMATION);

cvReleaseCapture( &capture );
capture = 0;
image =0 ;
//  cvDestroyWindow("TRacker");

}

DLLIMPORT StartCam (int CamIndex)
{
          
  //  fprintf(stdout,"Starting Camera %i \n",CamIndex);    
        
    capture = cvCreateCameraCapture(CamIndex);// cvCaptureFromCAM(-1);

  //  MessageBox (0, "StartCam\n", "Start Camera", MB_ICONINFORMATION);

    if( !capture )
    {
        fprintf(stderr,"Could not initialize capturing...\n");
        return -1;
    }
     
}

DLLIMPORT StartAviCap (char** Filename)
{
    fprintf(stdout,"Starting tracking  Filename %s \n",Filename);    
    
    capture = cvCaptureFromFile( Filename );
    // MessageBox (0, "cvCaptureFromAVI\n", "Start cvCaptureFromAVI", MB_ICONINFORMATION);
    if( !capture )
    {
        fprintf(stderr,"Could not initialize capturing...\n");
        return -1;
    }
     
}

DLLIMPORT IplImage* UpdateCam (int FindGoodFeaturesToTrack)
{

    int i, k, c;

   // MessageBox (0, "cvQueryFrame \n", "Update Camera", MB_ICONINFORMATION);
    frame = cvQueryFrame( capture );
  //  fprintf(stdout,"Get Frame %i  image  %i\n",frame,image); 
    if( !frame )
    {
     //   MessageBox (0, "cvQueryFrame FAILED\n", "Update Camera", MB_ICONINFORMATION);
        return;
    }
    if( !image )
    {
     //   fprintf(stdout,"make image files  IplImage ... %i \n",frame);
        //MessageBox (0, "Setup image structs \n", "Setup", MB_ICONINFORMATION);
        /* allocate all the buffers */
        image = cvCreateImage( cvGetSize(frame), 8, 3 );
        image->origin = frame->origin;
        image2    = cvCreateImage( cvGetSize(frame), IPL_DEPTH_16S, 1);
        grey      = cvCreateImage( cvGetSize(frame), 8, 1 );
        edges     = cvCreateImage( cvGetSize(frame), 8, 1 );
        prev_grey = cvCreateImage( cvGetSize(frame), 8, 1 );
        pyramid   = cvCreateImage( cvGetSize(frame), 8, 1 );
        prev_pyramid = cvCreateImage( cvGetSize(frame), 8, 1 );
        //MessageBox (0, "Alloc arrays \n", "Setup", MB_ICONINFORMATION);
        points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
        points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0]));
        status    = (char*)cvAlloc(MAX_COUNT);
        flags     = 0;
    }    
  
    //MessageBox (0, "Copy frame to image \n", "copy", MB_ICONINFORMATION);
    cvCopy( frame, image, 0 );
    //MessageBox (0, "Copied frame to image \n", "copied", MB_ICONINFORMATION);
    cvCvtColor( image, grey, CV_RGB2GRAY ); //CV_BGR2GRAY
    //MessageBox (0, "cvCvtColor image \n", "copied", MB_ICONINFORMATION);
  //  fprintf(stdout,"Got Frame %i \n",frame); 
    if( FindGoodFeaturesToTrack )
    {
        /* automatic initialization */
        
      //  fprintf(stdout,"FindGoodFeaturesToTrack ... %i \n",FindGoodFeaturesToTrack);
        
        IplImage* eig  = cvCreateImage( cvGetSize(grey), 32, 1 );
        IplImage* temp = cvCreateImage( cvGetSize(grey), 32, 1 );
        double quality = 0.01;
        double min_distance = 10;

        count = MAX_COUNT;
        cvGoodFeaturesToTrack( grey, eig, temp, points[1], &count,
                               quality, min_distance, 0, 3, 0, 0.04 );
        cvFindCornerSubPix( grey, points[1], count,
            cvSize(win_size,win_size), cvSize(-1,-1),
            cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03));
        cvReleaseImage( &eig );
        cvReleaseImage( &temp );

        add_remove_pt = 0;
    }
    else if( count > 0 )
    {
    
       // MessageBox (0, "cvCalcOpticalFlowPyrLK \n", "cvCalcOpticalFlowPyrLK", MB_ICONINFORMATION);         
        cvCalcOpticalFlowPyrLK( prev_grey, grey, prev_pyramid, pyramid,
            points[0], points[1], count, cvSize(win_size,win_size), 2, status, 0,
            cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03), flags );
    //    flags |= CV_LKFLOW_PYR_A_READY;
        for( i = k = 0; i < count; i++ )
        {
            if( add_remove_pt )
            {
                double dx = pt.x - points[1][i].x;
                double dy = pt.y - points[1][i].y;
                
               
                if( dx*dx + dy*dy <= 25 )
                {                    
                  //  fprintf(stdout," **>> dx*dx + dy*dy <= 25 ... %i \n",dx*dx + dy*dy);
                    add_remove_pt = 0;
                    continue;
                }
            }
            
            if( !status[i] )
                continue;
            
            points[1][k++] = points[1][i];
           // cvCircle( image, cvPointFrom32f(points[1][i]), 3, CV_RGB(0,255,0), -1, 8,0); 
           // fprintf(stdout,"point ... %d , %d \n",cvPointFrom32f(points[1][i]).x,cvPointFrom32f(points[1][i]).y);
                
        }
    //    cvCircle( image, pt, 3, CV_RGB(255,255,0), -1, 8,0);
        count = k;
        PointsTracked = k;
       // fprintf(stdout,"PointsTracked ... %i \n",PointsTracked);
    }

    if (add_remove_pt && count < MAX_COUNT )
    {
        
       // MessageBox (0, "add point \n", "Setup", MB_ICONINFORMATION);
        points[1][count++] = cvPointTo32f(pt);
        cvFindCornerSubPix( grey, points[1] + count - 1, 1,
            cvSize(win_size,win_size), cvSize(-1,-1),
            cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03));
        add_remove_pt = 0;
    }
    
    CV_SWAP( prev_grey, grey, swap_temp );
    CV_SWAP( prev_pyramid, pyramid, swap_temp );
    CV_SWAP( points[0], points[1], swap_points );
 //   FindGoodFeaturesToTrack = 0;
 
    if (linedraw)
    {
        if (linedraw ==1)
        {
            cvCanny( grey, edges, 30,100, 3 );
           // cvCvtColor( image, grey, CV_GRAY2BGR );
           return edges; 
        }
        else if (linedraw ==2)
        {
            cvLaplace(grey, image2,5);
            cvConvertScale( image2, grey, 1, 0);     
        return grey;
        //cvSmooth(grey, grey, CV_GAUSSIAN, 5, 0, 0,0); 
        }
       
    }
    
   // MessageBox (0, "return imaget \n", "finish", MB_ICONINFORMATION);
    return image;
  //  cvShowImage( "TRacker", image );

}

       



BOOL APIENTRY DllMain (HINSTANCE hInst     /* Library instance handle. */ ,
                       DWORD reason        /* Reason this function is being called. */ ,
                       LPVOID reserved     /* Not used. */ )
{
    switch (reason)
    {
      case DLL_PROCESS_ATTACH:
        break;

      case DLL_PROCESS_DETACH:
        EndCam ();
        break;

      case DLL_THREAD_ATTACH:
        break;

      case DLL_THREAD_DETACH:
        break;
    }

    /* Returns TRUE on success, FALSE on failure */
    return TRUE;
}