Docstoc

Source Code_

Document Sample
Source Code_ Powered By Docstoc
					Source Code:

// qcsdk2.cpp : Defines the entry point for the application.
//

using namespace std;

#include "stdafx.h"
#include "resource.h"
#include <stdio.h>
#include <math.h>
#include <time.h>

// the following two files are located in the inc directory of the QuickCam
// SDK. These two files contain interface definitions for the video portal
// control.
#include "VPortal2.h"
#include "VPortal2_i.c"
#include "LVServerDefs.H"
#include <iostream.h>
#include <fstream.h>

//#include "FileIO.h"

#define MAX_LOADSTRING 100

// Global Variables:
bool first_pass = true;
bool time_done = false;
time_t start_t = time(NULL);
time_t curr_t = time(NULL);
long qqq = 0;
bool crash = false;
char* message = NULL;
HINSTANCE hInst;                                                              // current
instance
TCHAR szTitle[MAX_LOADSTRING];
        // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];
                // The title bar text
HBITMAP* bitmap = new HBITMAP();

// Foward declarations of functions included in this code module:
ATOM                          MyRegisterClass(HINSTANCE hInstance);
BOOL                         InitInstance(HINSTANCE, int);
LRESULT CALLBACK             WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK             About(HWND, UINT, WPARAM, LPARAM);


// IVideoPortal is the interface to the video portal control
IVideoPortal* gpVideo = NULL;
// InitializeVideo is used to actually create an instance of the video
// portal control and obtain a IVideoPortal pointer to this interface.
BOOL InitializeVideo( HWND hWnd );
// UnInitializeVideo is used for clean up purposes
BOOL UnInitializeVideo( void );
CComModule _Module;
HWND gMainHwnd = NULL;
DWORD gdwAdviseCookie = 0;
//the following CDriver class implements the connection point to the video
//portal control. This connection point allows the video control to commuicate
//with the application through the PortalNotification event. The
//PortalNotification method is called by the video portal control and is
//handled here.
class CDriver :
         public IDispatchImpl<_IVideoPortalEvents, &IID__IVideoPortalEvents,
                   &LIBID_VPORTAL2Lib>,
         public CComObjectRoot
{
         public:
                 CDriver() {}
         BEGIN_COM_MAP(CDriver)
                 COM_INTERFACE_ENTRY(IDispatch)
                 COM_INTERFACE_ENTRY(_IVideoPortalEvents)
         END_COM_MAP()

               STDMETHOD(PortalNotification)(
                      long lMsg,
                      long lParam1,
                      long lParam2,
                      long lParam3 )
       {// implement any PortalNotification notification handling here.
               switch( lMsg )
               {
                      case NOTIFICATIONMSG_MOTION:
                              break;
                      case NOTIFICATIONMSG_MOVIERECORDERROR:
                              break;
                      case NOTIFICATIONMSG_CAMERADETACHED:
                              break;
                   case NOTIFICATIONMSG_CAMERAREATTACHED:
                           break;
                   case NOTIFICATIONMSG_IMAGESIZECHANGE:
                           break;
                   case NOTIFICATIONMSG_CAMERAPRECHANGE:
                           break;
                   case NOTIFICATIONMSG_CAMERACHANGEFAILED:
                           break;
                   case NOTIFICATIONMSG_POSTCAMERACHANGED:
                           break;
                   case NOTIFICATIONMSG_CAMERBUTTONCLICKED:
                           break;
                   case NOTIFICATIONMSG_VIDEOHOOK:
                           break;
                   case NOTIFICATIONMSG_SETTINGDLGCLOSED:
                           break;
                   case
NOTIFICATIONMSG_QUERYPRECAMERAMODIFICATION:
                           break;
                   case NOTIFICATIONMSG_MOVIESIZE:
                           break;
                   default:
                           break;
           };
           return S_OK;
     }
};

     // the following defines the connection point interface pointer
CComObject<CDriver>* gpDriver;

int APIENTRY WinMain(HINSTANCE hInstance,
              HINSTANCE hPrevInstance,
              LPSTR lpCmdLine,
              int     nCmdShow)
{
       //Initializes the COM library on the current apartment and identifies the
       //concurrency model as single-thread apartment (STA).
       CoInitialize(NULL);

       // Initialize the ATL module
       _Module.Init(NULL, hInstance);

       //Initialize ATL control containment code.
       AtlAxWinInit();
    // TODO: Place code here. NOT




    MSG msg;

    HACCEL hAccelTable;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_QCSDK2, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
             return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_QCSDK2);

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0))
    {
           if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
           {

                   TranslateMessage(&msg);
                   DispatchMessage(&msg);
           }
    }




    UnInitializeVideo(); // clean up the video control...
    _Module.Term();
    CoUninitialize();

    return msg.wParam;
}
//######################################################################
######################

struct SRU_Vision_Rec_Obj {
        bool flag;
        double mean_x;
        double mean_y;
        double stdev;
        int pixelsfit;
        double mean_minus_stdev;
};

struct SRU_vector_3d {
        double y;   //y scale value
        double u;   //u scale value
        double v;   //v scale value
};

struct SRU_vector_2d {
        double x;
        double y;
};

struct SRU_ellipse_2d {
 SRU_vector_2d f1; //foci point 1
 SRU_vector_2d f2; //foci point 2
 SRU_vector_2d x1; //major axis start
 SRU_vector_2d x2; //major axis end
 SRU_vector_2d y1; //minor axis start
 SRU_vector_2d y2; //minor axis end
 SRU_vector_2d c; //center
 double r;             //elliptical radius
 double fd;            //distance from center to foci points
 bool vert;       //true if ellipse's major axis is parallel with y axis, false if it is parallel
with x axis
};

struct SRU_yuv_model {
 double dist;
 SRU_vector_3d center;
 SRU_ellipse_2d YU_ellipse;
 //SRU_ellipse_2d YV_ellipse;
 //SRU_ellipse_2d UV_ellipse;
 double Y_min;
 double U_min;
 double V_min;
 double Y_max;
 double U_max;
 double V_max;
};

double SRU_vector_3d_dist(SRU_vector_3d a, SRU_vector_3d b) {
       double ret = sqrt( pow(a.y-b.y, 2) + pow(a.u-b.u, 2) + pow(a.v-b.v, 2) );
       return ret;
}

double SRU_vector_2d_dist(SRU_vector_2d a, SRU_vector_2d b) {
       double ret = sqrt( pow(a.x-b.x, 2) + pow(a.y-b.y, 2) );
       return ret;
}

SRU_vector_2d SRU_make_vector_2d(double X, double Y) {
     SRU_vector_2d ret;
     ret.x = X;
     ret.y = Y;
     return ret;
}

SRU_vector_3d SRU_make_vector_3d(double Y, double U, double V) {
     SRU_vector_3d ret;
     ret.y = Y;
     ret.u = U;
     ret.v = V;
     return ret;
}

SRU_ellipse_2d SRU_make_ellipse_2d_horizontal(double majorMin, double majorMax,
double minorMin, double minorMax){
       SRU_ellipse_2d ret;
       ret.c = SRU_make_vector_2d(majorMin+(majorMax-majorMin)/2.0,
minorMin+(minorMax-minorMin)/2.0);
       ret.r = majorMax - ret.c.x;
       ret.fd = sqrt(pow(ret.r, 2) - pow(minorMax-ret.c.y, 2));
       ret.f1 = SRU_make_vector_2d(ret.c.x-ret.fd, ret.c.y);
       ret.f2 = SRU_make_vector_2d(ret.c.x+ret.fd, ret.c.y);
       ret.x1 = SRU_make_vector_2d(majorMin, ret.c.y);
       ret.x2 = SRU_make_vector_2d(majorMax, ret.c.y);
       ret.y1 = SRU_make_vector_2d(ret.c.x, minorMin);
       ret.y2 = SRU_make_vector_2d(ret.c.x, minorMax);
       ret.vert = false;
       return ret;
}

SRU_ellipse_2d SRU_make_ellipse_2d_vertical(double majorMin, double majorMax,
double minorMin, double minorMax){
       SRU_ellipse_2d ret;
       ret.c = SRU_make_vector_2d(minorMin+(minorMax-minorMin)/2.0,
majorMin+(majorMax-majorMin)/2.0);
       ret.r = majorMax - ret.c.y;
       ret.fd = sqrt(pow(ret.r, 2) - pow(minorMax-ret.c.x, 2));
       ret.f1 = SRU_make_vector_2d(ret.c.x, ret.c.y-ret.fd);
       ret.f2 = SRU_make_vector_2d(ret.c.x, ret.c.y+ret.fd);
       ret.x1 = SRU_make_vector_2d(minorMin, ret.c.y);
       ret.x2 = SRU_make_vector_2d(minorMax, ret.c.y);
       ret.y1 = SRU_make_vector_2d(ret.c.x, majorMin);
       ret.y2 = SRU_make_vector_2d(ret.c.x, majorMax);
       ret.vert = true;
       return ret;
}

SRU_ellipse_2d SRU_scale_ellipse_2d(SRU_ellipse_2d e, double f){
  SRU_ellipse_2d ret;
  ret.x1 = SRU_make_vector_2d(e.c.x - (e.c.x-e.x1.x)*f, e.c.y);
  ret.x2 = SRU_make_vector_2d(e.c.x - (e.x2.x-e.c.x)*f, e.c.y);
  ret.y1 = SRU_make_vector_2d(e.c.x, e.c.y - (e.c.y-e.y1.y)*f);
  ret.y2 = SRU_make_vector_2d(e.c.x, e.c.y + (e.y2.y-e.c.y)*f);
  ret.c = e.c;
  ret.r = e.r*f;
  ret.fd = e.fd*f;
  ret.vert = e.vert;
  if(e.vert){
    //vertical
    ret.f1 = SRU_make_vector_2d(e.c.x, e.c.y - e.fd*f);
    ret.f2 = SRU_make_vector_2d(e.c.x, e.c.y + e.fd*f);
  }
  else{
    //horizontal
    ret.f1 = SRU_make_vector_2d(e.c.x - e.fd*f, e.c.y);
    ret.f2 = SRU_make_vector_2d(e.c.x - e.fd*f, e.c.y);
  }
  return ret;
}

bool SRU_point_within_ellipse_2d(SRU_vector_2d p, SRU_ellipse_2d e){
 if(SRU_vector_2d_dist(p, e.f1) + SRU_vector_2d_dist(p, e.f2) <= 2*e.r) {
   return true;
    }
    return false;
}

SRU_yuv_model SRU_make_model(double Ymin, double Ymax, double Umin, double
Umax, double Vmin, double Vmax,
                                                        double distin){
  SRU_yuv_model ret;
  ret.dist = distin;
  ret.center = SRU_make_vector_3d((Ymax+Ymin)/2.0, (Umax+Umin)/2.0,
(Vmax+Vmin)/2.0);
  ret.Y_min = Ymin;
  ret.Y_max = Ymax;
  ret.U_min = Umin;
  ret.U_max = Umax;
  ret.V_min = Vmin;
  ret.V_max = Vmax;
  if( Ymax-Ymin > Umax-Umin){
    ret.YU_ellipse = SRU_make_ellipse_2d_horizontal(Ymin, Ymax, Umin, Umax);
  }
  else{
    ret.YU_ellipse = SRU_make_ellipse_2d_vertical(Umin, Umax, Ymin, Ymax);
  }
  //if( Vmax-Vmin > Ymax-Ymin){
  // ret.YV_ellipse = SRU_make_ellipse_2d_vertical(Vmin, Vmax, Ymin, Ymax);
  //}
  //else{
  // ret.YV_ellipse = SRU_make_ellipse_2d_horizontal(Ymin, Ymax, Vmin, Vmax);
  //}
  //if( Vmax-Vmin > Umax-Umin){
  // ret.UV_ellipse = SRU_make_ellipse_2d_vertical(Vmin, Vmax, Umin, Umax);
  //}
  //else{
  // ret.UV_ellipse = SRU_make_ellipse_2d_horizontal(Umin, Umax, Vmin, Vmax);
  //}
  return ret;
}

bool SRU_point_fits_model(SRU_yuv_model m, SRU_vector_3d p) {
        /*
        double factor;
 SRU_ellipse_2d temp_ellipse;
 SRU_vector_2d yu_proj;
 bool ret;
 if((p.y < m.Y_min) || (p.y > m.Y_max)) {
   return false;
    }
    if((p.u < m.U_min) || (p.u > m.U_max)) {
      return false;
    }
    if((p.v < m.V_min) || (p.v > m.V_max)) {
      return false;
    }
    factor = 1 - fabs(p.v - m.center.v) / ((m.V_min+m.V_max)/2.0);
    temp_ellipse = SRU_scale_ellipse_2d(m.YU_ellipse, factor);
    yu_proj = SRU_make_vector_2d(p.y, p.u);
    ret = SRU_point_within_ellipse_2d(yu_proj, temp_ellipse);
    return ret;
           */

    //bool ret;

    if(SRU_vector_3d_dist(m.center, p) < m.dist){
          return true;
    }

    return false;


}

//void SRU_commander(){
// //im going to sleep on this
//}

char* readFile( const char* fileName, unsigned int* size )
{
       int length;
       char * buffer;

           ifstream is;
           is.open ( fileName, ios::binary );

           // get length of file:
           is.seekg (0, ios::end);
           length = is.tellg();
           is.seekg (0, ios::beg);

           // allocate memory:
           buffer = new char [length];

           // read data as a block:
       is.read (buffer,length);

       is.close();
       *size = length;
       //cout.write (buffer,length);
       return buffer;
}

void writeFile( const char* fileName, char* buffer, unsigned int size )
{
       ofstream writeFile;
       writeFile.open( fileName, ios::out | ios::binary );
       writeFile.write( buffer, size );
       writeFile.close();
}




SRU_Vision_Rec_Obj VisionController(HWND hWnd){


       //Save image to file
       long lResult;
       WCHAR wFile[] = L"C:\\image_orig.bmp";
       BSTR bStrFile = ::SysAllocString(wFile);
       if ( FAILED( gpVideo->PictureToFile( 0, 24, bStrFile, NULL, &lResult ) ))
       {
               // handle error condition
       }
       ::SysFreeString(bStrFile);


       ///////MessageBox( gMainHwnd, "Saved file from camera", "Info", MB_OK );




       //Read the file into memory
       char* buffer;
       unsigned int size = 0;
buffer = readFile( "../../image_orig.bmp", &size );
cout << "Size is " << size << endl;
cout.write( buffer, size );

///////MessageBox( gMainHwnd, "Read file in", "Info", MB_OK );

message = new char[256];
sprintf( message, "Buffer Length = %d", size );
///////MessageBox( gMainHwnd, message, "Info", MB_OK );

message = new char[256];
sprintf( message, "size = %u", size );
///////MessageBox( gMainHwnd, message, "Info", MB_OK );




//Write the file from memory
writeFile( "../../image_in.bmp", buffer, size );
//delete[] buffer;

///////MessageBox( gMainHwnd, "Wrote copy of original", "Info", MB_OK );




int headersize = sizeof(BITMAPFILEHEADER);
message = new char[256];
sprintf( message, "Size of header = %d", headersize );
///////MessageBox( gMainHwnd, message, "Header size", MB_OK );
delete[] message;




//run color recognition code to generate the color morel and
//to compare image pixels vs the color model
int len = (int) size;

message = new char[256];
sprintf( message, "len is %d", len );
///////MessageBox( gMainHwnd, message, "Info", MB_OK );
delete[] message;
      /*double RedMax = 255.0;
      double RedMin = 160.0;
      double GreenMax = 100.0;
      double GreenMin = 0.0;
      double BlueMax = 150.0;
      double BlueMin = 0.0;*/
      double RedMax = 150.0;
      double RedMin = 0.0;
      double GreenMax = 255.0;
      double GreenMin = 150.0;
      double BlueMax = 150.0;
      double BlueMin = 0.0;

      /*
      double HMax = 0.5333;//
      double HMin = 0.1333;//
      double SMax = 1.0;//
      double SMin = 0.4;//
      double LMax = 0.6;
      double LMin = 0.3;*/
      double HMax = 0.4167;//all ranges: 0 to 1
      double HMin = 0.2500;//
      double SMax = 1.0;//0 to 1
      double SMin = 0.25;//
      double LMax = 0.7;
      double LMin = 0.3;


      SRU_yuv_model SRU_model;
      long p1 = 0;
      double red_mean = 200.0;
      double green_mean = 100.0;
      double blue_mean = 50.0;
      double red_stdev = .0;
      double green_stdev = 100.0;
      double blue_stdev = 100.0;
      double color_dist = 100.0;
      SRU_model = SRU_make_model(red_mean - red_stdev, red_mean + red_stdev,
                                                 green_mean - green_stdev,
green_mean + green_stdev,
                                                 blue_mean - blue_stdev,
blue_mean + blue_stdev,
                                                 color_dist);
       int badpix = 0;

       int ii = 0;
       int iii = 0;

        char** pixel_matrix;
  pixel_matrix = new char*[240];
  for (int i = 0; i < 240; ++i)
     pixel_matrix[i] = new char[320];

       for(ii = 0; ii<240; ii++){
                for(iii = 0; iii<320; iii++){
                         pixel_matrix[ii][iii] = 0;
                }
       }

       ii = 0;
       iii = 0;

       long pixels;
       long pixels2;
       double sumx;
       double sumy;

       for(int u = headersize+55; u<len-5; u=u+3){

                  p1++;

                  //BLUE, GREEN, RED

                  unsigned char btemp = (unsigned char) buffer[u];
                  unsigned char gtemp = (unsigned char) buffer[u+1];
                  unsigned char rtemp = (unsigned char) buffer[u+2];

               double R = (double) rtemp;
               double G = (double) gtemp; //swap colors to accomodate for
inconsistancies in encoding
               double B = (double) btemp;

                  if(R>255.0 || R<0 || G>255.0 || G<0 || B>255.0 || B<0){
                         message = new char[256];
                         sprintf( message, "R = %d, G = %d, B = %d", R, G, B);
                         MessageBox( gMainHwnd, message, "Pixels checked", MB_OK );
                         delete[] message;
                         delete[] pixel_matrix;
                         SRU_Vision_Rec_Obj ret;
                     ret.flag = false;
                     ret.mean_x = 0;
                     ret.mean_y = 0;
                     ret.stdev = 0;
                     return ret;
             }

             if(R>255 || R<0 || G>255 || G<0 || B>255 || B<0){
                    badpix++;
                    R=0;
                    G=0;
                    B=0;
             }

             double var_R = ( R / 255.0 );                //RGB values = From 0 to 255
             double var_G = ( G / 255.0 );
             double var_B = ( B / 255.0 );

             double var_Min = min( var_R, min(var_G, var_B ));          //Min. value of
RGB
             double var_Max = max( var_R, max(var_G, var_B ));            //Max. value of
RGB
             double del_Max = var_Max - var_Min;                //Delta RGB value

             double L = ( var_Max + var_Min ) / 2.0;
             double H = 0;
             double S = 0;

             if ( del_Max == 0 )                 //This is a gray, no chroma...
             {
                H = 0;                       //HSL results = From 0 to 1
                S = 0;
             }
             else                          //Chromatic data...
             {
                      if ( L < 0.5 ) S = del_Max / ( var_Max + var_Min );
                      else        S = del_Max / ( 2 - var_Max - var_Min );

                     double del_R = ( ( ( var_Max - var_R ) / 6.0 ) + ( del_Max / 2.0 ) )
/ del_Max;
                     double del_G = ( ( ( var_Max - var_G ) / 6.0 ) + ( del_Max / 2.0 ) )
/ del_Max;
                     double del_B = ( ( ( var_Max - var_B ) / 6.0 ) + ( del_Max / 2.0 ) )
/ del_Max;

                     if   ( var_R == var_Max ) H = del_B - del_G;
                     else if ( var_G == var_Max ) H = ( 1.0 / 3.0 ) + del_R - del_B;
                     else if ( var_B == var_Max ) H = ( 2.0 / 3.0 ) + del_G - del_R;

                     if ( H < 0 ) H += 1;
                     if ( H > 1 ) H -= 1;
              }

               if(H>360 || H<0 || S>1 || S<0 || L>1 || L<0){// || p1==111*320+130){
                       message = new char[256];
                       sprintf( message, "R = %f, G = %f, B = %f,\nH = %f, S = %f, L =
%f", R, G, B, H, S, L);
                       MessageBox( gMainHwnd, message, "Pixels checked", MB_OK );
                       delete[] message;
                       delete[] pixel_matrix;
                       buffer[u] = (char) 0;
                       buffer[u+1] = (char) 0;
                       buffer[u+2] = (char) 255;
                       SRU_Vision_Rec_Obj ret;
                       ret.flag = false;
                       ret.mean_x = 0;
                       ret.mean_y = 0;
                       ret.stdev = 0;
                       return ret;
               }


              //double Y = (0.257 * R) + (0.504 * G) + (0.098 * B) + 16;
              //double V = (0.439 * R) - (0.368 * G) - (0.071 * B) + 128; //(Cr)
              //double U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128; //(Cb)



              SRU_vector_3d SRU_pixel_to_test;
              SRU_pixel_to_test = SRU_make_vector_3d(R, G, B);

              bool pixel_fits;
              pixel_fits = SRU_point_fits_model(SRU_model, SRU_pixel_to_test);

              /*if(pixel_fits){
                      buffer[u] = (char) 0;
                      buffer[u+1] = (char) 0;
                      buffer[u+2] = (char) 255;
                      pixels++;
              }*/

              /*if( ((R<=RedMax) && (R>=RedMin)) &&
                  ((B<=BlueMax) && (B>=BlueMin)) &&
                  ((G<=GreenMax) && (G>=GreenMin)) ) {
                  buffer[u] = (char) 0;
                  buffer[u+1] = (char) 0;
                  buffer[u+2] = (char) 255;
                  pixels++;
           }

           if(R>255.0 || R<0 || G>255.0 || G<0 || B>255.0 || B<0){
                  message = new char[256];
                  sprintf( message, "R = %d, G = %d, B = %d", R, G, B);
                  ///////MessageBox( gMainHwnd, message, "Pixels checked",
MB_OK );
                  delete[] message;
                  break;
           }*/

           //green
           if( ((H<=HMax) && (H>=HMin)) &&
                   ((S<=SMax) && (S>=SMin)) &&
                   ((L<=LMax+H/10.0) && (L>=LMin-H/10.0)) ) {
                   buffer[u] = (char) 0;
                   buffer[u+1] = (char) 0;
                   buffer[u+2] = (char) 255;
                   pixels++;
                   pixel_matrix[ii][iii] = 1;
                   if(ii>0 && iii>0){
                           if((pixel_matrix[ii-1][iii-1] == 1) ||
                                   (pixel_matrix[ii][iii-1] == 1) ||
                                   (pixel_matrix[ii-1][iii] == 1)){
                                   buffer[u] = (char) 255;
                                   buffer[u+1] = (char) 255;
                                   buffer[u+2] = (char) 0;
                                   pixels2++;
                                   sumx+=iii;
                                   sumy+=ii;
                           }
                   }
           }

           iii++;
           if(iii>=320) {
                   iii=0;
                   ii++;
                   if(ii>=240){
                           iii=319;
                       ii=239;
               }
       }

}

message = new char[256];
sprintf( message, "Pixels tested = %d", p1 );
///////MessageBox( gMainHwnd, message, "Pixels checked", MB_OK );
delete[] message;

message = new char[256];
sprintf( message, "Pixels matching the model = %d", pixels );
///////MessageBox( gMainHwnd, message, "Pixels found", MB_OK );
delete[] message;

message = new char[256];
sprintf( message, "Bad pixels: %d", badpix );
///////MessageBox( gMainHwnd, message, "Pixels found", MB_OK );
delete[] message;




//Write the modified file from memory
writeFile( "../../image_out.bmp", buffer, size );
//delete[] buffer;

///////MessageBox( gMainHwnd, "Wrote the modified file", "Info", MB_OK );


double meanx = sumx/320.0;
double meany = sumy/240.0;
double dist_squared_sum = 0;

for(ii = 0; ii<240; ii++){
         for(iii = 0; iii<320; iii++){
                  if(pixel_matrix[ii][iii] == 1){
                          dist_squared_sum += pow(meanx-iii,2)+pow(meany-ii,2);
                  }
         }
}

double s_dev = sqrt(dist_squared_sum / (320.0*240.0 - 1));
     SRU_Vision_Rec_Obj ret;

     ret.mean_x = meanx;
     ret.mean_y = meany;
     ret.stdev = s_dev;
     ret.pixelsfit = pixels2;
     ret.mean_minus_stdev = ret.mean_y - ret.stdev;
     if(ret.mean_minus_stdev < 0) ret.mean_minus_stdev = 0;

for (i = 0; i < 240; ++i)
   delete[] pixel_matrix[i];
      delete[] pixel_matrix;




     /*if(time_done == false){
             curr_t = time(NULL);
             if(curr_t - start_t > (time_t) 5){
                     time_done = true;
             }
     }
     else{*/




     /*
     //long lResult;
     //Pic to File
     WCHAR wFile[] = L"C:\\image_test.bmp";
     BSTR bStrFile = ::SysAllocString(wFile);
     if ( FAILED( gpVideo->PictureToFile( 0, 24, bStrFile, NULL, &lResult ) ))
     {
                // handle error condition
     }
     ::SysFreeString(bStrFile);
     //////////////////////
    int headersize = sizeof(BITMAPFILEHEADER);
    message = new char[256];
    sprintf( message, "Size of header = %d", headersize );
    ///////MessageBox( gMainHwnd, message, "This is the tutle", MB_OK );
    delete[] message;



    //Read the file into memory
    int length;
    char *buffer;

    ifstream is;
    is.open ("../../image_test.bmp", ios::binary );

    // get length of file:
    is.seekg (0, ios::end);
    length = is.tellg();
    is.seekg (0, ios::beg);

    // allocate memory:
    buffer = new char [length];

    // read data as a block:
    is.read (buffer,length);

    is.close();

    cout.write (buffer,length);


    ///////MessageBox( gMainHwnd, "Read file in", "Info", MB_OK );

    message = new char[256];
    sprintf( message, "Buffer Length = %d", length );
    ///////MessageBox( gMainHwnd, message, "Info", MB_OK );

    ///////MessageBox( gMainHwnd, buffer, "Buffer Info", MB_OK );


     fstream file_op("c:\\image_out.txt",ios::out);
file_op<<buffer;
file_op.close();
      ///////MessageBox( gMainHwnd, "Wrote file out", "Info", MB_OK );
      */




      /*
      ///// Save buffer to file
      FILE* myfile;
      myfile = fopen("./moomoo1.bmp", "w");
      if(myfile!=NULL){

             size_t ret;
             ret = fwrite(buffer, sizeof(BYTE), length, myfile);
             fclose(myfile);

      }
      //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxx

      char * buffer = (char *) array_of_bytes;
      */


      /*

      //Pic to Mem
      long lSize;

      if ( FAILED(gpVideo->PictureToMemory(0, 24, 0, &lSize, NULL, &lResult)) )
      {
              return FALSE;
      }
      //MODIFIED HERE
      BYTE* pBuffer = new BYTE[lSize];
      if ( FAILED(gpVideo->PictureToMemory( 0, 24, (long)pBuffer, &lSize, NULL,
      &lResult )) )
      {
              delete []pBuffer; // delete the memory we allocated...
              return FALSE;
      }
     int headersize = sizeof(BITMAPFILEHEADER);
     char* message = new char[256];
     sprintf( message, "Size of header = %d", headersize );
     ///////MessageBox( gMainHwnd, message, "This is the tutle", MB_OK );
     delete[] message;

     ///// Save buffer to file
     FILE* myfile;
     myfile = fopen("./moomoo1.bmp", "w");
     if(myfile!=NULL){

            size_t ret;
            ret = fwrite(pBuffer, sizeof(BYTE), lSize, myfile);
            fclose(myfile);

     }
     //xxxxxxxxxxxxxxxxxxxxxxx

     */


/*
     BYTE* pBuffer2 = new BYTE[lSize];
     for(int y = 0; y < lSize; y++){
             pBuffer2[y] = pBuffer[y];
     }




     SRU_yuv_model SRU_model;

     SRU_model = SRU_make_model(125, 255, 125, 255, 125, 255);

     for(int u = headersize; u<lSize-2; u=u+3){

            double R = (double)pBuffer[u];
            double G = (double)pBuffer[u+1];
            double B = (double)pBuffer[u+2];

            SRU_vector_3d SRU_pixel_to_test;
            SRU_pixel_to_test = SRU_make_vector_3d(R, G, B);

            bool pixel_fits;
           pixel_fits = SRU_point_fits_model(SRU_model, SRU_pixel_to_test);

           if(pixel_fits){
                   pBuffer2[u] = (BYTE) 255;
                   pBuffer2[u+1] = (BYTE) 0;
                   pBuffer2[u+2] = (BYTE) 0;
           }

    }



    //pBuffer now contains a .BMP file in memory
    ////////////////

    ///// Save buffer to file
    FILE* myfile2;
    myfile2 = fopen("./moomoo2.bmp", "w");
    if(myfile2!=NULL){

           size_t ret;
           ret = fwrite(pBuffer2, sizeof(BYTE), lSize, myfile2);
           fclose(myfile2);

    }

    */


    //xxxxxxxxxxxxxxxxxxxxxxx

    /*
    *bitmap = CreateBitmap( 160, 120, 24, 24, pBuffer );
    delete []pBuffer;
    delete []pBuffer2;


    */

    HDC hDC, MemDCExercising;
PAINTSTRUCT Ps;
HBITMAP bmpExercising;
    hDC = BeginPaint(hWnd, &Ps);

                  // Load the bitmap from the resource
                          bmpExercising = (HBITMAP) LoadImage (0,
"../../image_out.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
                          // Create a memory device compatible with the above DC variable
                          MemDCExercising = CreateCompatibleDC(hDC);
          // Select the new bitmap
          SelectObject(MemDCExercising, bmpExercising);

                      // Copy the bits from the memory DC into the current dc
                      //BitBlt(hDC, 0, 300, 360, 540, MemDCExercising, 0, 0,
SRCCOPY);
                      BitBlt(hDC, 600, 0, 960, 240, MemDCExercising, 0, 0,
SRCCOPY);
                      //BitBlt(hDC, 500, 300, 700, 500, MemDCExercising, 0, 0,
SRCCOPY);

                      // Restore the old bitmap
                      DeleteDC(MemDCExercising);
                      DeleteObject(bmpExercising);
                      EndPaint(hWnd, &Ps);


       return ret;


}




//######################################################################
#######################

//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage is only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

         wcex.cbSize = sizeof(WNDCLASSEX);

         wcex.style                    = CS_HREDRAW | CS_VREDRAW;
         wcex.lpfnWndProc        = (WNDPROC)WndProc;
         wcex.cbClsExtra               = 0;
         wcex.cbWndExtra               = 0;
         wcex.hInstance                = hInstance;
         wcex.hIcon                    = LoadIcon(hInstance, (LPCTSTR)IDI_QCSDK2);
         wcex.hCursor            = LoadCursor(NULL, IDC_ARROW);
         wcex.hbrBackground      = (HBRUSH)(COLOR_WINDOW+1);
         wcex.lpszMenuName       = (LPCSTR)IDC_QCSDK2;
         wcex.lpszClassName      = szWindowClass;
         wcex.hIconSm            = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

         return RegisterClassEx(&wcex);
}

//
// FUNCTION: InitInstance(HANDLE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
//   In this function, we save the instance handle in a global variable and
//   create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

    hInst = hInstance; // Store instance handle in our global variable

    hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
     CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

    if (!hWnd)
    {
       return FALSE;
    }
        gMainHwnd = hWnd;
        InitializeVideo( hWnd );

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    return TRUE;
}

//
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT         - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
      int wmId, wmEvent;
      //PAINTSTRUCT ps;
      //HDC hdc;
      TCHAR szHello[MAX_LOADSTRING];
      LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);
      //BYTE* pBuffer;
      qqq++;
      switch (message)
      {
             case WM_COMMAND:
                    wmId = LOWORD(wParam);
                    wmEvent = HIWORD(wParam);
                    // Parse the menu selections:
                    switch (wmId)
                    {
                             case IDM_ABOUT:
                               MessageBox( gMainHwnd, "Infinite loop time.. un-oh..
nooooooooooo!!!", "All hail pacman", MB_OK );
                               crash = true;
                               qqq=0;
                               break;
                             case IDM_EXIT:
                               DestroyWindow(hWnd);
                               break;
                               default:
                                 return DefWindowProc(hWnd, message, wParam,
lParam);
                        }
                        break;
                case WM_PAINT:
                        //doPaint(gMainHwnd);
                        if(qqq>100000){
                                SRU_Vision_Rec_Obj VCret;
                                if(crash){
                                        while(1){
                                                 qqq=qqq+qqq-qqq+1-1;
                                        }
                                }
                                VCret = VisionController( hWnd );
                                qqq=0;
                        }
                        break;
                case WM_DESTROY:
                        PostQuitMessage(0);
                        break;
                default:
                        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam,
LPARAM lParam)
{
       switch (message)
       {
              case WM_INITDIALOG:
                             return TRUE;

                case WM_COMMAND:
                      if (LOWORD(wParam) == IDOK || LOWORD(wParam) ==
IDCANCEL)
                      {
                               EndDialog(hDlg, LOWORD(wParam));
                               return TRUE;
                      }
                      break;
         }
    return FALSE;
}


// IntializeVideo creates the video portal control instance, obtains the
// connection point object, and connects the video portal to a camera device.
BOOL InitializeVideo( HWND hParent )
{
         long lResult;
         USES_CONVERSION;
         LPOLESTR strGUIDVideoPortalActiveXControl = NULL;
         StringFromCLSID(CLSID_VideoPortal, &strGUIDVideoPortalActiveXControl);
         // first we create a window which contains the video portal control.
         // notice the class name as “AtlAxWin”, and the window name
         // is the CLSID of the video portal control itself…
         HWND hWndCtl = ::CreateWindow( "AtlAxWin",

      OLE2T(strGUIDVideoPortalActiveXControl),
                                                                  WS_CHILD |
WS_VISIBLE | WS_GROUP,
                                                                  0,
                                                                  0,
                                                                  400,
                                                                  400,
                                                                  hParent,
                                                                  NULL,

      ::GetModuleHandle(NULL),
                                                                  NULL );
      CoTaskMemFree(strGUIDVideoPortalActiveXControl );
      if(!hWndCtl)
      {
             return FALSE;
      }

      // the following method retrieves the IVideoPortal interface from the HWND
      // of the window we just created.
      if ( FAILED( AtlAxGetControl(hWndCtl, (IUnknown **)&gpVideo)) )
      {
               return FALSE;
      }

      // the following instantiates the CDriver connection point object
      CComObject<CDriver>::CreateInstance(&gpDriver);
      // the following assigns the CDriver connection point to the video
      // portal’s connection point.
      if ( FAILED ( AtlAdvise(gpVideo, gpDriver->GetUnknown(),
        IID__IVideoPortalEvents, &gdwAdviseCookie) ) )
{
       gpVideo->Release();
       gpVideo = NULL;
       return FALSE;
}

// now we have everything we need to start communicating with the
// video portal. The gpVideo object is the interface to the video
// portal
WCHAR wstrKey[] = L"HKEY_CURRENT_USER\\Software\\TestApp1";
WCHAR wstrUnique[] = L"Aaron";
BSTR bStrKey = ::SysAllocString(wstrKey);
BSTR bStrUnique = ::SysAllocString(wstrUnique);
// the following line initializes the video control to be used by
// the application
if ( FAILED(gpVideo->PrepareControl( bStrUnique, bStrKey, 0, &lResult)) )
{
         ::SysFreeString(bStrKey);
         ::SysFreeString(bStrUnique);
         UnInitializeVideo();
         return FALSE;
}

::SysFreeString(bStrUnique);

gpVideo->put_PreviewMaxWidth( 320 );
gpVideo->put_PreviewMaxHeight( 240 );

// next we turn on the video portal’s status bar
if ( FAILED(gpVideo->EnableUIElements( UIELEMENT_STATUSBAR,
                                                          0,
                                                          TRUE,

&lResult )) )
{
}

// next, we connect to a camera device
if ( FAILED(gpVideo->ConnectCamera2( &lResult )) )
{
         ::SysFreeString(bStrKey);
         UnInitializeVideo();
         return FALSE;
}
      ::SysFreeString(bStrKey);

      // finally, we tell the video portal, to enable video preview.
      gpVideo->put_EnablePreview(TRUE);


      //SRU_Vision_Rec_Obj VCret;
      //VCret = VisionController( hWnd );


      return FALSE;
}

// UnInitialize video performs cleanup of the video portal when
//it is no longer needed.
BOOL UnInitializeVideo( void )
{
         if ( gpDriver )
         {
                 AtlUnadvise(gpVideo,IID__IVideoPortalEvents, gdwAdviseCookie);
                 gpDriver = NULL;
         }
         if ( gpVideo )
         {
                 gpVideo->Release();
                 gpVideo = NULL;
         }
         return TRUE;
}

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:126
posted:7/14/2010
language:English
pages:29