SR4000自带软件修改(二)

/*-----------------------------------------------------------------------------
*  
*   版权声明:
*   可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明
*   http://www.cnblogs.com/yuliyang/
*   联系方式:
*   Mail:yuliyang@qq.com
*
*-----------------------------------------------------------------------------*/

实现功能:

  1. 录制视频。
/*
 * =====================================================================================
 *
 *       Filename:  SwissRangerSampleGui.cpp
 *      Environment:    
 *    Description:  使用opencv获取深度和幅度数据并且录制视频
 *
 *
 *        Version:  1.0
 *        Created:  2013/11/6 21:55:43
 *         Author:  yuliyang
I*
 *             Mail:  wzyuliyang911@gmail.com
 *             Blog:  http://www.cnblogs.com/yuliyang
 *
 * =====================================================================================
 */

#include "stdafx.h"
//#include <vld.h>
#include "SwissRangerSampleGui.h"
#include "commdlg.h"
#include "commctrl.h"
#pragma comment( lib, "comctl32" )  //Used for slider control
#include "richedit.h"
#include <math.h>
#include "opencv2/core/core.hpp"  
#include "opencv2/highgui/highgui.hpp"  
#include "opencv2/imgproc/imgproc.hpp"  
/*------------------------------------------------------------------------------------------------------------
 *  rgb2gray用到                                                                                                  
 *------------------------------------------------------------------------------------------------------------*/
#include "opencv2/imgproc/imgproc_c.h" 
#include "opencv2/core/core_c.h"      
#include "opencv2/highgui/highgui_c.h"
using namespace cv;
CvVideoWriter *distance_vedio;                  /* 写入距离 */
CvVideoWriter *amp_vedio;                       /* 写入幅度 */
IplImage *video_a;                              /* 幅度数据的临时图像 */
IplImage *video_d;                              /* 距离数据的临时图像 */
IplImage *tempbule; /* 蓝色单通道 */
IplImage *tempgreen; /* 绿色单通道 */
IplImage *tempred; /* 红色单通道 */
IplImage *tempbule_A; /* 幅度(Amp)室外蓝色单通道 */
IplImage *tempgreen_A;                          /* 幅度彩色图像的绿色通道 */
IplImage *tempred_A;                            /* 幅度彩色图像的红色通道 */
IplImage *temprgb;                              /* 距离图像(D)的彩色如何图像 */
IplImage *temprgb_A;                            /* 幅度彩色融合图像 */
IplImage *tempgray;                             /* 距离图像的灰度图 */
IplImage *tempgray_A;                           /* 幅度图像的灰度图 */
bool start_flag(false);                         /* 未用到 */
bool stop_flag(false);                          /* 未用到 */
HANDLE hT=NULL;
/*------------------------------------------------------------------------------------------------------------
 *  本打算用子线程录制视频的,但是没用到                                                                                                  
 *------------------------------------------------------------------------------------------------------------*/
DWORD WINAPI ThreadFunction(LPVOID lpParameter)
{
    
    while (TRUE){
        if (video_a==NULL)
        {
            video_a=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,1);
            video_d=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,3);
            
        }
        else{
            /*cvWriteFrame(distance_vedio,video_d);
            cvWriteFrame(amp_vedio,video_a);*/
//             video_a=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,1);
//             video_d=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,3);
            cvShowImage("0",video_a);
            cvShowImage("1",video_d);
        }
        
        }
    MessageBox(NULL,"helo","sd",MB_OK);
    return true;
}

#ifndef DOXYGEN //exclude these defines from doxygen
// Global Variables:
static HINSTANCE hInst;                // current instance

HINSTANCE AfxGetInstanceHandle(){return hInst;}

CPreciseTimer precTimer;

#define LIMIT(val,min,max) (((val)<(min))?(min):(((val)>(max))? (max):(val)))

#ifndef D3DCOLOR_ARGB
typedef DWORD D3DCOLOR; //!<32 bit color value
  #define D3DCOLOR_ARGB(a,r,g,b) \
    ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))
#endif

//Colors for error overflow etc.
#define OVFL_COL D3DCOLOR_ARGB(0,0xff,0xe0,0xc0)
#define UDFL_COL D3DCOLOR_ARGB(0,0xc0,0xe0,0xff)
#define ERR_COL  D3DCOLOR_ARGB(0,0x00,0xe0,0x00)
#endif //DOXYGEN

//!The RGBColMap struct is used to generate colormaps.
//!This is a local class in the file OCTViewSlice.cpp
typedef struct
{
  BYTE    pos;//!<position in the color shading
  BYTE    r;  //!<red value
  BYTE    g;  //!<green value
  BYTE    b;  //!<blue value
} RGBColMap; //!<colormap entry for SetColormap()

static const RGBColMap jet[]={
  {0x00, 0x00, 0x00, 0x80},
  {0x20, 0x00, 0x00, 0xff},
  {0x60, 0x00, 0xff, 0xff},
  {0xa0, 0xff, 0xff, 0x00},
  {0xe0, 0xff, 0x00, 0x00},
  {0xff, 0x80, 0x00, 0x00}
};

//!fills a folormap with a desired color shading
void SetColormap(const RGBColMap* cm, RGBQUAD* col)
{
  int i,x;
  float f;
  col[0].rgbBlue =(BYTE)cm[0].b;
  col[0].rgbGreen=(BYTE)cm[0].g;
  col[0].rgbRed  =(BYTE)cm[0].r;
  col[0].rgbReserved=0x00;
  x=1;
  for (i=1;i<256;i++)
  {
    while (cm[x].pos<i)x++;
    f=((float)i-cm[x-1].pos)/(cm[x].pos-cm[x-1].pos);
    col[i].rgbBlue =(BYTE)(f*cm[x].b+(1.-f)*cm[x-1].b);
    col[i].rgbGreen=(BYTE)(f*cm[x].g+(1.-f)*cm[x-1].g);
    col[i].rgbRed  =(BYTE)(f*cm[x].r+(1.-f)*cm[x-1].r);
    col[i].rgbReserved=0x00;
  }
}

//!Loops and calls CWndSwissranger::Acquire() until CCameraThread::Stop() is called
DWORD CCameraThread::CameraLoop()
{
  while(!_stop)
  {
    _srWnd->Acquire();
  }
  return 0;
}


const TCHAR* CWndSwissranger::_wndClass="WndSwissrangerClass";
const TCHAR* CWndSwissranger::_wndTitle="Swissranger";

//!\ingroup swissRangerSampleGui
//!This is he main entry function that allocates a CWndSwissranger object, creates the window and starts the message loop.
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
  MSG msg;
  WINDOWINFO winf;
  HACCEL hAccelTable;
  HWND dlg;
  hInst = hInstance;
  InitCommonControls();

  SR_CheckForNewDllVersion(0);

  CWndSwissranger wndSR;

  wndSR.Create(hInstance,0);
  hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_SWISSRANGERSAMPLEGUI);

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

    dlg=msg.hwnd;
    while(IsWindow(dlg) && GetWindowInfo(dlg,&winf))
    {
      if ((winf.dwStyle&WS_POPUP) && IsDialogMessage(dlg, &msg))
      {
        goto cont2;
      }
      dlg=GetParent(dlg);
    }
    TranslateMessage(&msg);
    DispatchMessage(&msg);
cont2:;
  }
  return (int) msg.wParam;
}

//!redirects the call from this static function to the method WindowProc
BOOL CALLBACK CDlgAbout::SWindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
  CDlgAbout* pWnd;
  if (message == WM_INITDIALOG)
  {
    pWnd=(CDlgAbout*)lParam;
    pWnd->_hWnd=hDlg;
    // get the pointer to the window from lpCreateParams which was set in CreateWindow
    SetWindowLong(hDlg, GWL_USERDATA, (long)(lParam));
    pWnd->OnInitialUpdate();
    return TRUE;
  }
  // get the pointer to the window
  pWnd = GetObjectFromWindow(hDlg);
  // if we have the pointer, go to the message handler of the window
  // else, use DefWindowProc
  if (pWnd)
    return pWnd->WindowProc(hDlg, message, wParam, lParam);
  else
    return FALSE;
}

//!window message handling function
BOOL CALLBACK CDlgAbout::WindowProc(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;
}

CWndSwissranger* CWndSwissranger::_cbInstance=0;
//!registers a new window class
ATOM CWndSwissranger::RegisterClass(HINSTANCE hInstance)
{
  static bool registered=false;
  if(registered)return 0;
  registered=true;
  WNDCLASSEX wcex;

  wcex.cbSize = sizeof(WNDCLASSEX);

  wcex.style      = CS_HREDRAW | CS_VREDRAW;
  //wcex.lpfnWndProc  = SWindowProc;
  wcex.cbClsExtra    = 0;
  wcex.cbWndExtra    = 0;
  wcex.hInstance    = hInstance;
  wcex.hIcon      = LoadIcon(hInstance, (LPCTSTR)IDI_SWISSRANGERSAMPLEGUI);
  wcex.hCursor    = LoadCursor(NULL, IDC_ARROW);
  wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
  wcex.lpszMenuName  = (LPCTSTR)IDC_SWISSRANGERSAMPLEGUI;
  wcex.lpszClassName  = _wndClass;
  wcex.hIconSm    = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
  return RegisterClassEx(&wcex);
}



//!redirects the call from this static function to the method WindowProc
BOOL CALLBACK CWndSwissranger::SWindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
  CWndSwissranger* pWnd;
  if (message == WM_INITDIALOG)
  {
    pWnd=(CWndSwissranger*)lParam;
    pWnd->_hWnd=hDlg;
    // get the pointer to the window from lpCreateParams which was set in CreateWindow
    SetWindowLong(hDlg, GWL_USERDATA, (long)(lParam));
    pWnd->OnInitialUpdate();
    return TRUE;
  }
  // get the pointer to the window
  pWnd = GetObjectFromWindow(hDlg);
  // if we have the pointer, go to the message handler of the window
  // else, use DefWindowProc
  if (pWnd)
    return pWnd->WindowProc(hDlg, message, wParam, lParam);
  else
    return FALSE;
}

//!window message handling function
BOOL CALLBACK CWndSwissranger::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  int wmId, wmEvent;

  switch (message)
  {
  case WM_COMMAND:
    wmId    = LOWORD(wParam);
    wmEvent = HIWORD(wParam);
    // Parse the menu selections:
    switch (wmId)
    {
    case IDOK:
    case IDCANCEL:
    {
      _camThread.Stop(1000);
      if(IsWindowEnabled(::GetDlgItem(hWnd,IDC_CLOSE)))
      {
        OnCloseDev();
      }
      DestroyWindow(hWnd);
      break;
    }
    case IDM_ABOUT:
      {
        CDlgAbout about;
        about.DoModal(AfxGetInstanceHandle(),hWnd);
        break;
      }
    case IDM_EXIT:
      DestroyWindow(hWnd);
      break;
    case ID_SETTINGS_DLL:
      {
        if(_srCam)
          SR_OpenSettingsDlg(_srCam,hWnd);
        else
        {
          MessageBox(hWnd,"No Swissranger camera opened","Warning",MB_ICONEXCLAMATION);
        }
        break;
      }
    case  IDC_CHECK_NEW_DLL:
      {
        int res=SR_CheckForNewDllVersion(3);
        if(res)
          MessageBox(hWnd,"No new libMesaSR-dll version found","libMesaSR: Info",MB_ICONASTERISK);
        break;
      }

    case ID_OPEN_FORCE_DLG:
      {
        OnOpenDlg(2);
        break;
      }
    case IDC_OPEN:
    case ID_OPEN_DLG:
      {
        short s=GetKeyState(VK_LSHIFT);
        if(s<0)//shift pressed?
          OnOpenDlg(2);
        else
          OnOpenDlg(3);
        break;
      }
    case IDC_ACQUIRE:
      {
        //_camThread.Run(this);
        HWND hcntrl=GetDlgItem(hWnd,IDC_CONTINUOUS);
        LRESULT lResult = SendMessage(hcntrl, BM_GETCHECK, 0, 0);
        if(lResult)
        {
          if(_camThread.IsRunning())
          {
            _camThread.Stop(0);
            EnableWindow(::GetDlgItem(hWnd,IDC_CLOSE),TRUE);
            ::SendMessage(::GetDlgItem(hWnd,IDC_ACQUIRE),WM_SETTEXT,0,(LPARAM)"Acquire");
          }
          else
          {
            EnableWindow(::GetDlgItem(hWnd,IDC_CLOSE),FALSE);
            ::SendMessage(::GetDlgItem(hWnd,IDC_ACQUIRE),WM_SETTEXT,0,(LPARAM)"Stop");
            precTimer.StartTimer();
            _camThread.Run(this);
          }
        }
        else
        {
          precTimer.StartTimer();
          Acquire();
        }
        break;
      }
    case IDC_CLOSE:
      {
        OnCloseDev();
        break;
      }
    case IDC_MINCOL:
      {
        HWND hcntrl=(HWND)lParam;
        switch(wmEvent)
        {
        case EN_CHANGE:
          {
            char buf[64];
            HWND hcntrl=(HWND)lParam;
            GetWindowText(hcntrl,buf,_countof(buf));
            hcntrl=GetDlgItem(hWnd,IDC_CB_COL);
            LRESULT lResult = SendMessage(hcntrl,CB_GETCURSEL,0,0);
            float v=(float)atof(buf);
            _minVal[lResult]=v;
            break;
          }
        }
        break;
      }
    case IDC_MAXCOL:
      {
        HWND hcntrl=(HWND)lParam;
        switch(wmEvent)
        {
        case EN_CHANGE:
          {
            char buf[64];
            HWND hcntrl=(HWND)lParam;
            GetWindowText(hcntrl,buf,_countof(buf));
            hcntrl=GetDlgItem(hWnd,IDC_CB_COL);
            LRESULT lResult = SendMessage(hcntrl,CB_GETCURSEL,0,0);
            float v=(float)atof(buf);
            _maxVal[lResult]=v;
            break;
          }
        }
        break;
      }
    case IDC_CB_COL:
      {
        switch(wmEvent)
        {
        case CBN_SELCHANGE:
          {
            HWND hcntrl=(HWND)lParam;
            LRESULT lResult = SendMessage(hcntrl,CB_GETCURSEL,0,0);
            SetColorLim((int)lResult);
            break;
          }
        }
        break;
      }
    case IDC_AUTO_EXPOSURE:
      {
        bool optInt=SendMessage(GetDlgItem(_hWnd,IDC_AUTO_EXPOSURE), BM_GETCHECK, 0, 0)?true:false;
        if(optInt)
          SR_SetAutoExposure(_srCam, 5,255,10,45);
        else
          SR_SetAutoExposure(_srCam, 255,0,0,0);
        break;
      }
    case IDC_MEDIAN:
      {
        if(SendMessage((HWND)lParam,(UINT)BM_GETCHECK,0,0)==BST_CHECKED)
          SetMode(_acquMode|AM_MEDIAN);
        else
          SetMode(_acquMode&~AM_MEDIAN);
        break;
      }
    case IDC_CONV_GRAY:
      {
        if(SendMessage((HWND)lParam,(UINT)BM_GETCHECK,0,0)==BST_CHECKED)
          SetMode(_acquMode|AM_CONV_GRAY);
        else
          SetMode(_acquMode&~AM_CONV_GRAY);
        break;
      }
    case IDC_COORD_TRANSF:
      {
        HWND hcntrl=GetDlgItem(_hWnd,IDC_COORD_TRANSF);
        LRESULT lResult = SendMessage(hcntrl, BM_GETCHECK, 0, 0);
        _coordTrf=lResult?true:false;
        break;
      }
    default:
        return FALSE;            // Didn't process the message: Got a WM_COMMAND message with unknown id.
    }
    break;
  case WM_PAINT:
    {
      OnPaint();
      break;
    }
  case WM_SIZE:
    {
      RECT rct0;
      RECT cltRct;
      HWND imgWnd0=GetDlgItem(hWnd,IDC_IMAGE0);
      int w = LOWORD(lParam);
      int h = HIWORD(lParam);
      TRACE("WM_SIZE %d,%d",w,h);
      GetClientRect(hWnd,&cltRct);
      GetWindowRect(imgWnd0,&rct0);ScreenToClient(hWnd,(LPPOINT)&rct0);ScreenToClient(hWnd,((LPPOINT)&rct0)+1);
      int d=10;
      int ww=(cltRct.right-rct0.left-d);
      MoveWindow(imgWnd0,
                 rct0.left,//
                 rct0.top,//
                 ww,
                 cltRct.bottom-rct0.top-d,
                 true);
      break;
    }
  case WM_DESTROY:
    PostQuitMessage(0);
    break;
  default:
    return FALSE;            // Didn't process the message: Got a WM_COMMAND message with unknown id.
  }
  return TRUE;            // processed the message
}

//!fills the dib with image data from the camera
                                                /*  */
/*------------------------------------------------------------------------------------------------------------
 *  主要修改部分by
 *                                yuliyang    2013/11/7 20:27:06
 *
 *
 *
 *
 *
 *------------------------------------------------------------------------------------------------------------*/
void CWndSwissranger::SetDib()                  /* 该函数在aquire() 图像时重复调用*/
{

    /*------------------------------------------------------------------------------------------------------------ *  
     * 0000-0xffff    扩展到0x000000-0xffffff每种颜色    
     * 每种颜色占一个字节 00-ff
     * 扩张后再分配到各个通道,然后再组装成彩色一幅图
     *
     *                                                                                           
     *
     *------------------------------------------------------------------------------------------------------------*/
    tempbule=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1); /* 蓝色单通道 */
    tempgreen=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1); /* 绿色单通道 */
    tempred=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1); /* 红色单通道 */
    tempbule_A=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1); /* 幅度室外蓝色单通道 */
    tempgreen_A=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1);
    tempred_A=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1);
    temprgb=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,3);
    temprgb_A=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,3);
    tempgray=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1);
    tempgray_A=cvCreateImage(cvSize(_imgSz.cx,_imgSz.cy),IPL_DEPTH_8U,1);
    //IplImage *temp0=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,1);
    if (distance_vedio==NULL)                   /* 第一次是初始化视频读写 */
    {
        distance_vedio=cvCreateVideoWriter("distance.avi",CV_FOURCC('X','V','I','D'),20,cvSize(_imgSz.cx,_imgSz.cy),1); /* 彩色 */
        amp_vedio=cvCreateVideoWriter("amp.avi",CV_FOURCC('X','V','I','D'),20,cvSize(_imgSz.cx,_imgSz.cy),0); /* 灰度 */
    }
    if (video_a==NULL)                          /* 图像无数据时 */
    {
        video_a=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,1); /* 因为获取图像与写入图像有时间差 */
        video_d=cvCreateImage(cvSize(176,144),IPL_DEPTH_16U,3);
    }

    cvNamedWindow("distance",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("amp",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("gray",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("amp_gray",CV_WINDOW_AUTOSIZE);
    //cvNamedWindow("0",CV_WINDOW_AUTOSIZE);
    /*------------------------------------------------------------------------------------------------------------
     *  获取距离图像
     *
     *------------------------------------------------------------------------------------------------------------*/
  if(_dibCam)
  {
    int i,idx,img;
    int row=0;
    int col=0;

    float v,minVal,step;
    img=0;idx=0;
    if(_coordTrf)
    {
      int res;
      float lambda[MF_LAST]={3.75f, 5.f, 7.142857f, 7.5f, 7.894737f, 2.5f, 10.f, 15.f, 5.172414f, 4.838710f, 10.344828f, 9.677419f};//MF_40MHz,MF_30MHz,MF_21MHz,MF_20MHz,MF_19MHz,...
      ModulationFrq frq=SR_GetModulationFrequency(_srCam);
      res=SR_CoordTrfFlt(_srCam, 0,0,_z, sizeof(float),sizeof(float),sizeof(float));
      minVal=_minVal[img];
      step=(float)0xff/(_maxVal[img]-_minVal[img]);
      for(i=0;i<_imgSz.cx*_imgSz.cy;i++,idx++)
      {
            row=i/_imgSz.cx;
            col=i%_imgSz.cx;
        v=(_z[i]*((float)(1<<16)/lambda[frq])-minVal)*step;
        _dibCam[idx]=_bmiScale->bmiColors[(BYTE)LIMIT(v,0,255)];

        /*------------------------------------------------------------------------------------------------------------
         *  获取3个通道的数据分别给opencv图像赋值
         *
         *------------------------------------------------------------------------------------------------------------*/
        BYTE  Blue1 =_dibCam[idx].rgbBlue;
        BYTE  Green1=_dibCam[idx].rgbGreen;
        BYTE  Red1=_dibCam[idx].rgbRed;
        CV_IMAGE_ELEM( tempbule, uchar, row,col )=Blue1;
        CV_IMAGE_ELEM( tempgreen, uchar, row,col )=Green1;
        CV_IMAGE_ELEM( tempred, uchar, row,col )=Red1;

      }

      cvMerge(tempbule,tempgreen,tempred,NULL,temprgb); /* 图像融合 */
      cvShowImage("distance",temprgb);
      cvCvtColor(temprgb,tempgray,CV_RGB2GRAY);
      cvShowImage("gray",tempgray);
      video_d=temprgb;
    //  cvShowImage("1",video_d);
      cvWriteFrame(distance_vedio,temprgb);     /* 写入视频文件 */
     // cvCopy(temprgb,video_d,0);
      cvWaitKey(10);
      img++;
    }
                 
    /*------------------------------------------------------------------------------------------------------------
     *  获取幅度图像
     *
     *------------------------------------------------------------------------------------------------------------*/
    
    //cvShowImage("1",video_d);
    cvWriteFrame(amp_vedio,video_d);
    for(;img<_numImg;img++)
            {
              WORD* p=(WORD*)_imgEntryArray[img].data;
              unsigned short int * pdata0;
              pdata0=(unsigned short int *)SR_GetImage(_srCam, 1); /* 原数据 */
              minVal=_minVal[img];
              step=(float)0xff/(_maxVal[img]-_minVal[img]);
              for(i=0;i<_imgSz.cx*_imgSz.cy;i++,idx++)
                          {
                              int row=i/_imgSz.cx; /**/
                              int col=i%_imgSz.cx; /**/
                              v=((float)p[i]-minVal)*step;
                              _dibCam[idx]=_bmiScale->bmiColors[(BYTE)LIMIT(v,0,255)];
                              /*------------------------------------------------------------------------------------------------------------
                               *  幅度数据的赋值
                               *
                               *------------------------------------------------------------------------------------------------------------*/
                                            BYTE  Blue1 =_dibCam[idx].rgbBlue;
                                          BYTE  Green1=_dibCam[idx].rgbGreen;
                                          BYTE  Red1=_dibCam[idx].rgbRed;
                                          CV_IMAGE_ELEM( tempbule_A, uchar, row,col )=Blue1;
                                          CV_IMAGE_ELEM( tempgreen_A, uchar, row,col )=Green1;
                                          CV_IMAGE_ELEM( tempred_A, uchar, row,col )=Red1;
                          }
              cvMerge(tempbule_A,tempgreen_A,tempred_A,NULL,temprgb_A);
              cvShowImage("amp",temprgb_A);     /* 融合 */
              cvCvtColor(temprgb_A,tempgray_A,CV_RGB2GRAY);
              cvShowImage("amp_gray",tempgray_A);
              //cvWriteFrame(amp_vedio,tempgray_A);
              //  cvCopy(tempgray_A,video_a,0);
              video_a=tempgray_A;
              cvWaitKey(10);
              //for (int i=0;i<144;i++)
              //{
                 // for (int j=0;j<176;j++)
                 // {
                    //  CV_IMAGE_ELEM( temp0, unsigned short int, i, j)=*pdata0; /* 给图像赋值 */
                    //  pdata0++;

                 // }
              //}
              //cvShowImage("0",temp0);
              //cvWaitKey(10);
            }
      // cvShowImage("0",video_a);
       cvWriteFrame(amp_vedio,video_a);         /* 写入幅度视频文件 */
    
  }
  InvalidateRect(_hWnd,0,false);                /* 重绘窗口 */
  cvReleaseImage(&tempbule);
  cvReleaseImage(&tempgreen);
  cvReleaseImage(&tempred);
  cvReleaseImage(&temprgb);
 // cvDestroyWindow("distance");
}

//!redirects the call from this static function to the method SRFuncCB
int CWndSwissranger::SSRFuncCB(SRCAM srCam, unsigned int msg, unsigned int param, void* data)
{
  if(!_cbInstance)
    return 0;
  return _cbInstance->SRFuncCB(srCam, msg, param, data);
}
//!callback function of the libMesaSR. It enters/leaves the critical section during changes
int CWndSwissranger::SRFuncCB(SRCAM srCam, unsigned int msg, unsigned int param, void* data)
{
  switch(msg)
  {
  default:
    return SR_GetDefaultCallback()(srCam,msg,param,data);
    break;
  case CM_CHANGING:
    EnterCritSec();
    break;
  case CM_CHANGED:
    if(param)
      AllocObj();
    LeaveCritSec();
    break;
  }
  return 0;
}

//!allocates memory for _dibCam buffer and initializes the _bmiCam structure
void CWndSwissranger::AllocObj()
{
    _imgSz.cx=SR_GetCols(_srCam);
    _imgSz.cy=SR_GetRows(_srCam);
    _numImg=SR_GetImageList(_srCam,&_imgEntryArray);

    SAFE_FREE(_dibCam);
    _dibCam=(RGBQUAD*)malloc(_imgSz.cx*_imgSz.cy*_numImg*sizeof(RGBQUAD));//RGBQUAD,  RGBTRIPLE, BYTE, WORD
    _bmiCam->bmiHeader.biWidth =_imgSz.cx;
    _bmiCam->bmiHeader.biHeight=-_numImg*_imgSz.cy;

    SAFE_FREE(_z);
    _z=(float*)malloc(_imgSz.cx*_imgSz.cy*sizeof(float));
}

//!frees all allocated objects
void CWndSwissranger::Free()
{
  SAFE_FREE(_dibCam);
  SAFE_FREE(_bmiCam);
  SAFE_FREE(_dibScale);
  SAFE_FREE(_bmiScale);
  SAFE_FREE(_z);

}

//!initializes _maxVal,_bmiCam, _bmiScale and allocates _dibScale
void CWndSwissranger::Initialize()
{
  int i;
  for(i=0;i<_countof(_minVal);i++)
  {
    _minVal[i]=0;
    _maxVal[i]=0xffff;
  }
  _maxVal[0]=30000.f;
  _maxVal[1]=15000.f;
  _maxVal[2]=30000.f;
  _maxVal[3]=15000.f;

  _bmiCam=(BITMAPINFO*)malloc(sizeof(BITMAPINFOHEADER)+1*sizeof(RGBQUAD));
  memset(_bmiCam,0,sizeof(BITMAPINFOHEADER));
  _bmiCam->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  _bmiCam->bmiHeader.biPlanes = 1;
  _bmiCam->bmiHeader.biBitCount = 32;
  _bmiCam->bmiHeader.biCompression = BI_RGB;

  _bmiScale=(BITMAPINFO*)malloc(sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD));
  memset(_bmiScale,0,sizeof(BITMAPINFOHEADER));
  _bmiScale->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  _bmiScale->bmiHeader.biPlanes = 1;
  _bmiScale->bmiHeader.biBitCount = 8;
  _bmiScale->bmiHeader.biCompression = BI_RGB;
  _bmiScale->bmiHeader.biWidth=256;
  _bmiScale->bmiHeader.biHeight=1;

  //alloc and fill scale DIB
  int x;
  _dibScale=(BYTE*)malloc(256*sizeof(BYTE));
  for (x=0;x<256;x++)_dibScale[x]=x;
  SetColormap(jet,_bmiScale->bmiColors);
}
//!When the window is created this function will be called
void CWndSwissranger::OnInitialUpdate()
{
  LRESULT lResult;
  HWND hcntrl;
  int i;
  char buf[64];

  HICON hIcon=LoadIcon(hInst, (LPCTSTR)IDI_SMALL);
  lResult = SendMessage(_hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
  lResult = SendMessage(_hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);

  hcntrl=GetDlgItem(_hWnd,IDC_CB_COL);
  for(i=0;i<_countof(_minVal);i++)
  {
    _snprintf(buf,_countof(buf),"Image %d",i);
    lResult = SendMessage(hcntrl,CB_INSERTSTRING,-1,(LPARAM)buf);
  }
  lResult = SendMessage(hcntrl,CB_SETCURSEL,0,0);
  SetColorLim(0);
  hcntrl=GetDlgItem(_hWnd,IDC_CONTINUOUS);
  lResult = SendMessage(hcntrl, BM_SETCHECK, BST_CHECKED, 0);
  hcntrl=GetDlgItem(_hWnd,IDC_COORD_TRANSF);
  lResult = SendMessage(hcntrl, BM_SETCHECK, BST_CHECKED, 0);
  _coordTrf=true;
}

//!Sets the acuire mode of the camera
void CWndSwissranger::SetMode(int mode)
{
  EnterCritSec();
  _acquMode=mode;
  SR_SetMode(_srCam, mode);
  LeaveCritSec();
}
//!Sets color limits _minVal[idx] and _maxVal[idx] according to the gui settings
void CWndSwissranger::SetColorLim(int idx)
{
  HWND hcntrl;
  char buf[64];
  hcntrl=GetDlgItem(_hWnd,IDC_MINCOL);
  _snprintf(buf,_countof(buf),"%.2f",_minVal[idx]);
  SetWindowText(hcntrl,buf);
  hcntrl=GetDlgItem(_hWnd,IDC_MAXCOL);
  _snprintf(buf,_countof(buf),"%.2f",_maxVal[idx]);
  SetWindowText(hcntrl,buf);
}
//!called when close button is pressed
/*------------------------------------------------------------------------------------------------------------
 *  释放视频文件
 *
 *
 *
 *------------------------------------------------------------------------------------------------------------*/
void CWndSwissranger::OnCloseDev()
{
    /*------------------------------------------------------------------------------------------------------------
     *  重要:如果不释放的话得到的视频文件大小是不对的只有6K大小
     *
     *
     *------------------------------------------------------------------------------------------------------------*/
    cvReleaseVideoWriter(&distance_vedio);      /* 释放距离视频资源 */
    cvReleaseVideoWriter(&amp_vedio);           /* 释放幅度图像资源 */
  int res;
  TRACE("swissrangerTester: SR_Close");
  res=SR_Close(_srCam);
  EnableWindow(::GetDlgItem(_hWnd,IDC_OPEN),TRUE);
  if (res < 0)
  {
    TRACE("Failed to close device: error %d",res);
    //but change the button states anyway, no return;
  }
  EnableWindow(::GetDlgItem(_hWnd,IDC_CLOSE),FALSE);
  EnableWindow(::GetDlgItem(_hWnd,IDC_ACQUIRE),FALSE);
  _srCam=0;//there are no valid device opened
}

//!called on a \b WM_PAINT message
void CWndSwissranger::OnPaint()
{
  char buf[256];
  _snprintf(buf,_countof(buf)," %.2f fps\n",1.f/_timePerFrame);
  HWND hcntrl=GetDlgItem(_hWnd,IDC_TX_FPS);
  ::SetWindowText(hcntrl,buf);

  PAINTSTRUCT ps;
  HDC hdc;
  HWND imgWnd;
  hdc = BeginPaint(_hWnd, &ps);
  EndPaint(_hWnd, &ps);
  imgWnd=GetDlgItem(_hWnd,IDC_IMAGE0);
  
  /*------------------------------------------------------------------------------------------------------------
   *  删除掉了DC的绘图操作代码
   *
   *
   *------------------------------------------------------------------------------------------------------------*/
  //hdc = BeginPaint(imgWnd, &ps);
  //RECT rect;
  //GetClientRect(imgWnd,&rect);
  //float fct;
  //if(_dibScale)
  //{
  //  const SIZE sz={_bmiScale->bmiHeader.biWidth,_bmiScale->bmiHeader.biHeight};
  //  fct=(float)(rect.right-10)/sz.cx;
  //  StretchDIBits(hdc, 5, 5, (int)(fct*sz.cx), 10, 0, 0,     // x,y,w,h destination // x,y source
  //                _bmiScale->bmiHeader.biWidth, _bmiScale->bmiHeader.biHeight,  // width & height in source
  //                _dibScale, _bmiScale,                                         // pointer to 'bits' //BITMAPINFOHEADER
  //                DIB_RGB_COLORS, SRCCOPY);
  //}

  //if(_dibCam)
  //{
  //  const SIZE sz={_bmiCam->bmiHeader.biWidth,-_bmiCam->bmiHeader.biHeight};
  //  fct=min((float)(rect.right-10)/sz.cx,(float)(rect.bottom-25)/sz.cy);
  //  StretchDIBits(hdc, 5, 20, (int)(fct*sz.cx), (int)(fct*sz.cy), 0, 0,     // x,y,w,h destination // x,y source
  //                _bmiCam->bmiHeader.biWidth, -_bmiCam->bmiHeader.biHeight,  // width & height in source
  //                _dibCam, _bmiCam,                                         // pointer to 'bits' //BITMAPINFOHEADER
  //                DIB_RGB_COLORS, SRCCOPY);
  //}

  //EndPaint(imgWnd, &ps);
  return;
}

//!called when open button is pressed
void CWndSwissranger::OnOpenDlg(int mode)
{
  TRACE("swissrangerTester: SR_Open device");
  if (_srCam)
  {
    TRACE("Swiss Ranger device already opened.");
    return;
  }
  int res;
  res=SR_OpenDlg(&_srCam,mode,_hWnd);
  SendMessage(GetDlgItem(_hWnd,IDC_AUTO_EXPOSURE), BST_UNCHECKED, 0, 0);
  _acquMode=SR_GetMode(_srCam);

  SendMessage((HWND)GetDlgItem(_hWnd,IDC_MEDIAN),(UINT)BM_SETCHECK, (_acquMode&AM_MEDIAN)?BST_CHECKED:BST_UNCHECKED,0);
  SendMessage((HWND)GetDlgItem(_hWnd,IDC_CONV_GRAY),(UINT)BM_SETCHECK, (_acquMode&AM_CONV_GRAY)?BST_CHECKED:BST_UNCHECKED,0);

  if (res<=0)
  {
    TRACE("Couldn't connect to Swiss Ranger device error %d",res);
    return;
  }
  TRACE("swissrangerTester: Device opened successfully device handle=%d",_srCam);
  AllocObj();
  EnableWindow(::GetDlgItem(_hWnd,IDC_OPEN),FALSE);
  EnableWindow(::GetDlgItem(_hWnd,IDC_CLOSE),TRUE);
  EnableWindow(::GetDlgItem(_hWnd,IDC_ACQUIRE),TRUE);
}

//!Acquires an image and displays it
void CWndSwissranger::Acquire()
{ 

  EnterCritSec();
  int res=SR_Acquire(_srCam);
  
  if (res < 0)
  {
    TRACE("Failed to acquire the measurement");
  }
  else
  {
    //logPrintf("swissrangerTester: %d bytes read", res);
    SetDib();
  }
  LeaveCritSec();
  __int64 tic=precTimer.GetTime();precTimer.StartTimer();
  static __int64 smtic=0;
  _timePerFrame=0.90f*_timePerFrame+0.10f*(float)tic/1e6f;
  smtic+=tic;
  smtic=0;
}

100

posted @ 2013-11-07 20:51  小菜鸟_yang  阅读(658)  评论(0编辑  收藏  举报