⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 camera.h

📁 BCAM 1394 Driver
💻 H
字号:
//-----------------------------------------------------------------------------
//  (c) 2002 by Basler Vision Technologies
//  Section:  Vision Components
//  Project:  BCAM
//  $Header: Camera.h, 20, 11.06.2004 09:56:49, Happe, A.$
//-----------------------------------------------------------------------------
/**
\file     Camera.h
\brief   Interface for the CCamera class.
*/
//-----------------------------------------------------------------------------


#if !defined(AFX_CAMERA_H__508A7277_978A_11D5_922E_0090278E5E96__INCLUDED_)
#define AFX_CAMERA_H__508A7277_978A_11D5_922E_0090278E5E96__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define WM_ERROR WM_USER + 42   // user defined message, sent by the acquisistion thread to the main frame if 
// an error occured in the thread's run method

class CChildFrame;
class CMainFrame;

#include "Image.h"
#include "WhiteBalancer.h"
#include <queue>

const unsigned long TIMERID = 0xa7a3;
const unsigned long TIMERINTERVAL = 1000;

//------------------------------------------------------------------------------
// class CCamera
// Author: 
// Date: 
//------------------------------------------------------------------------------
/**
* \brief   CCamera: encapsulation of a CBcam object
*
* This class encapsulates a camera device. 
*
* A CCamera object is responsible for
*  - grabbing images ( single grab and continuous grab, 
*    managment of image buffers )
*  - color conversion
*  - initiation of image display
*  - calculation of frame rates
*  - creation of shading correction table
*  - reparametrization of camera 
*  - auto-white-balance
*/
//------------------------------------------------------------------------------

class CCamera : public CBcam  
{
protected:
  /// image acquisition related state 
  typedef enum
  {
    sIdle,                    //< no acquisition active
    sSingleGrab,              //< single grab in process
    sContinuousGrab,          //< continuous grab active
    sContinuousGrabSuspended, //< suspended continuous grab 
    sAutoWhiteBalanceIdle,    //< auto-white-balance triggered in idle state
    sAutoWhiteBalanceCont     //< auto-white-balance triggered in continuous grab state
  } eState; 


  /// Thread doing the image acquisition and auto white balancing
  class CAcquisitionThread : protected CThread
  {
  protected:
    CAcquisitionThread(CCamera* pParent) : CThread(), Parent(pParent) {};
    /// thread procedure
    static DWORD WINAPI ThreadProc(void* pThis);
    /// create the thread
    BOOL Create( int Priority=THREAD_PRIORITY_NORMAL );
    /// Run() will be called by the static thread procedure
    DWORD Run();                    
    /// Process buffer retrieved from the completion port
    void ProcessImage(CBcamBitmap* pBitmap, bool omitBuffer); 
    /// Process buffer passed to the completion port by the display thread
    /// via user notificaions
    void ProcessUserNotification(CBcamBitmap* pBitmap);
    /// Cleanup after a single grab has been completed
    void FinishSingleGrab();
    /// Destroy the thread
    void Destroy();

    /// The camera object 
    CCamera*  Parent;

    friend class CCamera;
  } m_AcquisitionThread;

  /// Thread which will build the bitmap from the latest acquired image buffer. After creating the bitmap
  /// its rendering is initiated by invalidating the image view's client region
  class CDisplayThread : protected CThread
  {

    CDisplayThread(CCamera* pParent);
    /// thread procedure
    static DWORD WINAPI ThreadProc(void* pThis);
    /// create the thread
    BOOL Create( int Priority=THREAD_PRIORITY_NORMAL );
    /// Run() will be called by the static thread procedure
    DWORD Run();                    
    DWORD WaitUntilIdle();
    void NextWhiteBalanceIteration();
    void Destroy();
    CBcamBitmap* SetBuffer(CBcamBitmap* pBuffer);

    /// signals that the display thread is to be terminated
    CEvent              m_evtTerminate;
    /// signals that the display thread hat to cancel it's buffers
    CEvent              m_evtCancelRequest;
    /// signals that the display thread has cancelled its I/O requests and has flushed the display queue
    CEvent              m_evtCancelComplete;
    /// signals that a new buffer is available to be processed by the display thread
    CEvent              m_evtNewBufferAvailable;  

    /// The camera object 
    CCamera*  Parent;

    /// the next buffer to be processed by the display thread
    CBcamBitmap*		    m_pNextBuffer;		
    /// Critical section to synchronize access to m_pNextBuffer
    CCriticalSection	  m_csNextBuffer;


    friend class CCamera;
    friend class CAcquisitionThread;
  } m_DisplayThread;




public:
  CCamera(CString& DeviceName, HWND hWndNotify, CMainFrame& MainFrame);

  virtual ~CCamera();

  /// open the device driver and do some initialization
  void Activate();

  /// close the device driver ad do some cleanup
  void Deactivate();


  /// Tell the camera object which is its assoicated MDI child window
  void SetMDIChild(CChildFrame* pChild);

  /// Grab single frame
  void GrabSingle();
  /// "Grab" image from file
  void GrabFromFile(CString FileName);
  /// Create shading corection table
  void CreateShadingCorrectionTable();
  /// Activate continuous grabbing
  void GrabContinuous(bool invalidate=true);
  /// Perform a white balance
  void PerformWhiteBalance();
  /// Cancel continouus grabbing
  void GrabCancel();
  /// Are we currently grabbing ?
  bool IsGrabActive() { return m_State != sIdle; }
  /// Is an auto white balance operation active
  bool IsAutoWhiteBalanceActive() { return ( m_State == sAutoWhiteBalanceIdle ) || ( m_State == sAutoWhiteBalanceCont ); }
  /// Is continous mode grabbing active?
  bool IsContinuousGrabActive() { return ( m_State == sContinuousGrab ) || ( m_State == sContinuousGrabSuspended ); }
  /// Is a single grab pending?
  bool IsSingleGrabActive() { return m_State == sSingleGrab; }
  /// Have we allocated 1394 resources?
  bool IsBandwidthAllocated() { return m_IsoChannel != -1; }
  /// Is the white balance feature supported?
  bool IsWhiteBalanceSupported(){ return m_fIsWhiteBalanceSupported; }

  bool IsMono() { return ( m_ColorCode == DCSColor_Mono8 ) || ( m_ColorCode == DCSColor_Raw8); }
  bool IsBayerConversionEnabled() { return GetBayerToRGBConversion() && IsMono(); }

  /// Retrieve actual frame rate
  void GetFrameRate(double& acquired, double& displayed); 
  /// Return the bitmap to display  ( The image view will use this function in its OnPaint method)
  CBcamBitmap* GetBitmap() 
  { 
    return m_fBitmapValid ? m_pBitmap : NULL;
  }
  /// Return the current color code
  DCSColorCode GetColorCode() { return m_ColorCode; }


  /// Inform the camera object that it is to be reconfigured (e.g. by the properties dialog or by changing the AOI)
  /// An active grabbed will be suspended.
  bool ReconfigurationRequest();

  /// Inform the camera object that the reconfiguration is done. A suspended grab will be resumed.
  void ConfigurationChanged();

  /// SetAOI
  void SetAOI(CRect AOI);
  /// Maximize the AOI
  void MaximizeAOI();
  /// Parametrize Camera ( format 0 - 2 )
  void ParametrizeCamera(DCSVideoFormat format, DCSVideoMode mode, DCSVideoFrameRate rate);
  /// Parametrize Camera ( format 7 )
  void ParametrizeCamera(DCSVideoMode mode, DCSColorCode code, CPoint position, CSize size, unsigned long bpp);
  /// Has the camera a scalable AOI ?
  bool IsScalable() { return m_VideoFormat == DCS_Format7; }

  /// Set Bayer to RGB conversion mode ( 0: no conversion, 1 .. 4 enable conversion)
  void SetBayerToRGBConversion( int mode );
  /// Get Bayer to RGB conversion mode ( 0: no conversion, 1 .. 4 enable conversion)
  int GetBayerToRGBConversion() { return m_ConvertMono8ToRGB; }
  /// Bayer to RGB conversion: Set gain for the red channel 
  void SetRGain(double gain);
  /// Bayer to RGB conversion: Set gain for the blue channel 
  void SetBGain(double gain);
  /// Bayer to RGB conversion: Get gain for the red channel 
  double GetRGain() { return m_GainR; }
  /// Bayer to RGB conversion: Get gain for the blue channel 
  double GetBGain() { return m_GainB; }
  /// save the current configuration to a CPropertyBag
  void SaveConfiguration(const CPropertyBagPtr ptrBag);
  /// save the current configuration to a file
  void SaveConfiguration(const CString fileName) { SaveConfiguration(CIniFilePropertyBag::Create(fileName, "BCAM")); }
  /// restore configuration from a CPropertyBag
  void RestoreConfiguration(const CPropertyBagPtr ptrBag);
  /// restore configuration from a file
  void RestoreConfiguration(const CString fileName) {   RestoreConfiguration(CIniFilePropertyBag::Open(fileName, "BCAM"));}







private:
  // hide copy constructor and assignment operator
  CCamera( const CCamera& );
  CCamera& operator=( const CCamera& );


  /// Initialize Camera 
  void InitializeCamera(); 
  /// Starts a single grab
  void StartSingleGrab(eState stateToEnter);
  /// To be called before a continuous grab is started
  void PrepareContinuousGrab(bool invalidate=true);
  /// Create the threads
  void CreateThreads();
  /// Destroy the threads
  void DestroyThreads();
  /// Cancel an active continuous grab
  DWORD CancelContinuousGrab();
  /// Allocate n new buffers
  void CreateNewBuffers(unsigned long n);
  /// Release Buffers
  void ReleaseBuffers();
  /// Enqueue a buffer into the driver's queue. 
  void Enqueue(CBcamBitmap* pBitmap, bool singleShot = false);
  /// Callback. It is called if an error occured in one of the threads
  void OnContinuousGrabError(DWORD err);
  // ensure that the given AOI size has a width beeing a multiple of 4, because the length of a bitmap's scanline
  // is a multiple of 4
  void AlignAOI(CSize& Size, DCSVideoMode mode);
  // Convert to RGB
  void ConvertBitmap(CBcamBitmap* *ppDest, CBcamBitmap* *ppSource);
  // Refresh the cached information and notify clients about changes
  void Refresh(bool force = false);

  void InternalParametrizeCamera(DCSVideoFormat format, DCSVideoMode mode, DCSVideoFrameRate rate, 
    DCSColorCode code, CPoint position, CSize size, unsigned long bpp);  

  /// Hide the close function
  void Close() { throw BcamException(ERROR_INVALID_FUNCTION , "Don't call Close(), use Deactivate Instead!!"); }  

  // member variables

  /// Device name
  CString             m_FriendlyDeviceName;
  /// Window handle to recieve device notifications
  HWND                m_hWndNotify;
  /// Is camera initilized
  bool                m_fIsInitialized;
  /// number of buffers we use for image acquisition
  int                 m_cBuffers;       
  /// array of buffers to be filled by the DMA
  CBcamBitmap**       m_ppBuffers;      
  /// bitmap to display. 
  CBcamBitmap*        m_pBitmap;       
  /// Critical section guarding resources used by the acquisition thread
  CCriticalSection    m_csAcquisition;
  /// does the bitmap match the current camera configuration?
  bool                m_fBitmapValid; 
  /// image acquisition related state of the camera object
  eState              m_State;
  /// if m_fSurpressFurtherErrorMessages is true, the acquisition thread proc will not report errors
  bool                m_fSurpressFurtherErrorMessages;
  /// true, if the white balance feature is enabled (either the camera's white balance feature or the bayer8 convert's one)
  bool                m_fIsWhiteBalanceSupported;

  /// Size of sensor
  CSize               m_SensorSize;
  /// Size of AOI
  CSize               m_ImageSize;
  /// Origin of AOI
  CPoint              m_Origin;
  /// Current color mode
  DCSColorCode        m_ColorCode;
  /// number of bits per pixel
  unsigned short      m_Bpp;
  /// current video mode
  DCSVideoMode        m_VideoMode;
  /// current video format
  DCSVideoFormat      m_VideoFormat;
  /// current framerate
  DCSVideoFrameRate   m_VideoFrameRate;



  /// timer to measure the time needed to display one buffer
  CStopWatch          m_DisplayWatch;              
  /// timer to measure the time needed to acquire one buffer
  CStopWatch          m_AcquisitionWatch;
  /// Moving average of time needed to acquire one buffer
  CMovingAvg<double, 20>  m_AcquisitionAvg;
  /// Moving average of time needed to display one buffer
  CMovingAvg<double, 20>  m_DisplayAvg;
  /// MDI child window which will display our image data
  CChildFrame*        m_pChildFrame;
  /// Reference to main frame 
  CMainFrame&         m_MainFrame;

  CWhiteBalancer      m_WhiteBalancer;

  // Bayer to RGB conversion

  /// shall we convert MONO8 images to RGB ( Bayer -> RGB conversion )
  int                 m_ConvertMono8ToRGB; 
  double              m_GainR;
  double              m_GainB;
  BYTE                m_pLutG[256];
  BYTE                m_pLutR[256];
  BYTE                m_pLutB[256];

  /// 
  static long         s_cGrabsActive;


  friend class CCameraManager;
  friend class CImageView;
  friend class CMainFrame;
  friend class CAcquisitionThread;

}; // CCamera

#endif // !defined(AFX_CAMERA_H__508A7277_978A_11D5_922E_0090278E5E96__INCLUDED_)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -