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

📄 camera.cpp

📁 BCAM 1394 Driver
💻 CPP
📖 第 1 页 / 共 4 页
字号:
//-----------------------------------------------------------------------------
//  (c) 2002 by Basler Vision Technologies
//  Section:  Vision Components
//  Project:  BCAM
//  $Header: Camera.cpp, 33, 04.07.2006 11:03:03, Happe, A.$
//-----------------------------------------------------------------------------
/**
\file     Camera.cpp
*
* 
*
\brief   Implementation of the CCamera class.
*/
//-----------------------------------------------------------------------------


#include "stdafx.h"

#define SHOW_OMITTED_BUFFERS FALSE
#define VERBOSE 0

#ifndef _DEBUG
#if SHOW_OMITTED_BUFFERS
#error SHOW_OMITTED_BUFFERS = TRUE is not allowed in Release Build
#endif
#endif

#include "mainfrm.h"
#include "Camera.h"
#include "CameraManager.h"
#include "ChildFrm.h"
#include "utility.h"
#include "BvcColorConverter.h"
#include "CreateCorrectionTable.h"

#define NEARLYINFINITE 10000

// initialize static members
long CCamera::s_cGrabsActive = 0;


//------------------------------------------------------------------------------
// CCamera::CCamera(CString& DeviceName, HWND hWndNotify, CMainFrame& MainFrame) : 
// Author: 
//------------------------------------------------------------------------------
/**
* Constructor
*
* \param     DeviceName  Name of the device
* \param     hWndNotify  Handle of window which should receive device notifications
* \param     MainFrame   Reference to main window
*
*/
//------------------------------------------------------------------------------
CCamera::CCamera(CString& DeviceName, HWND hWndNotify, CMainFrame& MainFrame) : 
m_FriendlyDeviceName(BcamUtility::FriendlyDeviceName(DeviceName)),
m_State(sIdle),
m_hWndNotify(hWndNotify),
m_fIsInitialized(false),
m_cBuffers(0),
m_ppBuffers(NULL),
m_pBitmap(NULL),
m_ConvertMono8ToRGB(0),
m_GainB(1.0),
m_GainR(1.0),
m_fBitmapValid(false),
m_SensorSize(0,0),
m_ImageSize(0,0),
m_Origin(0,0),
m_ColorCode(DCSColor_Mono8),
m_fIsWhiteBalanceSupported(false),
m_fSurpressFurtherErrorMessages(false),
m_pChildFrame(NULL),
m_MainFrame(MainFrame),
m_WhiteBalancer(*this),
m_AcquisitionThread(this),
m_DisplayThread(this)
{


  // initialize LUTs for Bayer to RGB conversion
  SetRGain(m_GainR);
  SetBGain(m_GainB);
  for ( int i = 0; i < 256; i++ )
  {
    m_pLutG[i] = i;
  }

}

//------------------------------------------------------------------------------
// CCamera::~CCamera()
// Author: 
//------------------------------------------------------------------------------
/**
* Destructor
*
* \return    
*
*/
//------------------------------------------------------------------------------
CCamera::~CCamera()
{
  try
  {
    // If we are still grabbing, cancel the grabbing
    if ( IsGrabActive() )
    {
      GrabCancel();
    }
  }
  catch ( BcamException& e)
  {
    m_MainFrame.ReportError(e);
  }

  // Free memory buffers 
  ReleaseBuffers();
  if ( m_pBitmap != NULL )
    delete m_pBitmap;

  Deactivate();
}

//------------------------------------------------------------------------------
// CCamera::Activate()
// Author: 
//------------------------------------------------------------------------------
/**
* Open the device driver and do some initialization
* 
* \return void
*
*/
//------------------------------------------------------------------------------
void CCamera::Activate()
{
  if ( ! IsOpen() )
  {
    CBcam::Open(m_FriendlyDeviceName, m_hWndNotify);
    if ( ! m_fIsInitialized )
      InitializeCamera();
    else
      Refresh(); // Refresh the cached information and notify clients about changes
  }
}

//------------------------------------------------------------------------------
// void CCamera::Deactivate()
// Author: 
//------------------------------------------------------------------------------
/**
* Close the device driver and do some cleanup
*
* \return void
*
*/
//------------------------------------------------------------------------------
void CCamera::Deactivate()
{
  DestroyThreads();
  if ( IsOpen() )
  {
    CBcam::Close();
  }
}

//------------------------------------------------------------------------------
// CCamera::InitializeCamera()
// Author: 
//------------------------------------------------------------------------------
/**
*  Setup our CCamera object and initialze camera.
*  The display thread and the acquisition thread will be created
*
* \return void
*
*/
//------------------------------------------------------------------------------
void CCamera::InitializeCamera()
{
  if ( ! m_fIsInitialized )
  {
    DCSVideoFormat    format;
    DCSVideoMode      mode;
    DCSVideoFrameRate rate;
    GetVideoMode(&format, &mode, &rate);
    // Set the video mode, format again to update cached information
    if ( format != 7 )
    {
      ParametrizeCamera(format, mode, rate);  // parametrization of standard format
    }
    else      // parametrize camera in format 7
    {
      ParametrizeCamera(mode, FormatSeven[mode].ColorCoding(), FormatSeven[mode].Position(), FormatSeven[mode].Size(), FormatSeven[mode].BytePerPacket());
    }
    m_fIsInitialized = true;
  }
}

//------------------------------------------------------------------------------
// void CCamera::SetMDIChild(CChildFrame* pChild)
// Author: 
//------------------------------------------------------------------------------
/**
* Tell the camera object which is its assoicated MDI child window
*
* \param     pChild
* \return    void
*
*/
//------------------------------------------------------------------------------
void CCamera::SetMDIChild(CChildFrame* pChild)
{ 
  m_pChildFrame = pChild; 
  if ( pChild != NULL )
  {
    // Inform the the image view about the current video format and AOI dimensions
    m_pChildFrame->m_View.ConfigurationChanged(m_VideoFormat, m_VideoMode, m_SensorSize, m_ImageSize, m_Origin); 
  }
}

//------------------------------------------------------------------------------
// void CCamera::GrabSingle()
// Author: 
//------------------------------------------------------------------------------
/**
* Grab single frame
*
* \return    void
*
*/
//------------------------------------------------------------------------------
void CCamera::GrabSingle()
{
  assert ( m_State == sIdle );
  assert ( m_pChildFrame != NULL );
  StartSingleGrab(sSingleGrab);
}

//------------------------------------------------------------------------------
// void CCamera::GrabContinuous()
// Author: 
//------------------------------------------------------------------------------
/**
* Activate continuous grabbing
*
* \return void 
*
*/
//------------------------------------------------------------------------------
void CCamera::GrabContinuous(bool invalidate)
{
  assert ( m_State == sIdle);
  assert ( m_pChildFrame != NULL );
  CAutoLock<CCriticalSection> lock(m_csAcquisition);

  // create threads if they aren't already running
  CreateThreads();

  // Allocate bandwidth and memory, queue in buffers
  PrepareContinuousGrab(invalidate);

  // book keeping about number of active grabs
  s_cGrabsActive ++;
  if ( s_cGrabsActive == 1 )
  {   // Start timer for the frame rate display
    m_MainFrame.SetTimer(TIMERID, TIMERINTERVAL);
  }

  // start watches to measure fps
  m_DisplayWatch.Start();
  m_AcquisitionWatch.Start();

  m_State = sContinuousGrab;

  // Switch on ISO_ENABLE  -> camera will send continuously data
  ContinuousShot = true;
}

//------------------------------------------------------------------------------
// void CCamera::GrabFromFile(CString FileName)
// Author: 
//------------------------------------------------------------------------------
/**
* Grab image from file
*
* \param     FileName
* \return    void
*
* 
*/
//------------------------------------------------------------------------------
void CCamera::GrabFromFile(CString FileName)
{
  assert ( m_State == sIdle );
  assert ( m_pChildFrame != NULL );
  CAutoLock<CCriticalSection> lock(m_csAcquisition);

  // release image buffers and current bitmap
  ReleaseBuffers();
  if ( m_pBitmap != NULL )
  {
    delete m_pBitmap;
    m_pBitmap = NULL;
    m_fBitmapValid = false;
  }

  // Load bitmap from file
  m_pBitmap = new CBcamBitmap(FileName);
  if ( m_pBitmap != NULL )
  {
    m_fBitmapValid = true;
    // inform the child view 
    m_pChildFrame->m_View.ConfigurationChanged((DCSVideoFormat) -1, (DCSVideoMode) -1, m_pBitmap->GetSensorSize(),m_pBitmap->GetSize(), m_pBitmap->GetOrigin());
  }
}

//------------------------------------------------------------------------------
// void CCamera::CreateShadingCorrectionTable()
// Author: 
//------------------------------------------------------------------------------
/**
* Create Shading correction table and display it as bitmap
* 
* \return  void
*/
//------------------------------------------------------------------------------
void CCamera::CreateShadingCorrectionTable()
{
  assert ( ! IsGrabActive() );
  assert ( m_pChildFrame != NULL );

  if ( m_pChildFrame != NULL )
  {
    m_pChildFrame->m_View.ConfigurationChanged(m_VideoFormat, m_VideoMode, m_SensorSize, m_ImageSize, m_Origin); 
  }

  CreateNewBuffers(1);  // old buffers will be released

  AllocateResources(1, m_ppBuffers[0]->GetBufferSize());

  try
  {
    SetCursor(LoadCursor(NULL, IDC_WAIT));

    // Calculate correction table ( take into account that some cameras sends images having distorted border lines or columns )
    // The average image is calculated using 100 images
    SCMode_t ShadingMode = ::CreateShadingCorrectionTable(100, *this, *m_ppBuffers[0], CRect(1, 1, m_ImageSize.cx - 2 , m_ImageSize.cy - 2 ));

    // Display the shading table as image
    ConvertBitmap(&m_pBitmap, &m_ppBuffers[0]);
    m_fBitmapValid = true;
    m_pChildFrame->m_View.Invalidate();
    if ( ShadingMode == SCM_Disabled )
    {
      // Something went wrong.
      ZeroMemory(*m_ppBuffers[0], m_ImageSize.cx * m_ImageSize.cy * m_Bpp / 8);
    }
    else
    {
      // Store the proper shading mode in the bitmap's user data. The camera properties dialog 
      // will read this information to set the right shading mode after uploading the image
      m_ppBuffers[0]->SetUserData(ShadingMode);
    }
  }
  catch ( BcamException& e)
  {
    ZeroMemory(*m_ppBuffers[0], m_ImageSize.cx * m_ImageSize.cy * m_Bpp / 8);
    if ( IsBandwidthAllocated() )
      FreeResources();
    throw e;
  }

  // Free Resources (bandwith and isochronous channel )
  if ( IsBandwidthAllocated() )
    FreeResources();  

}


//------------------------------------------------------------------------------
// void CCamera::PerformWhiteBalance()
// Author: 
//------------------------------------------------------------------------------
/**
* Auto-adjust white balance
*
* \return void 
*
*/
//------------------------------------------------------------------------------
void CCamera::PerformWhiteBalance()
{
  assert ( m_State == sContinuousGrab || m_State == sIdle );
  if ( m_State == sContinuousGrab || m_State == sIdle )
  {
    if ( WhiteBalance.IsSupported(inqOnePush) )
    {
      // the camera itself can perform the white balance
      WhiteBalance.OnePush();
      if ( m_MainFrame.m_CameraManager.GetCurrentDevice() == this )
      {
        // Refresh the white balance control
        m_MainFrame.m_Features[FeatureID_WhiteBalance]->CurrentDeviceChanged(this);
      }
    }
    else
    { 
      // We have to perform the white balance
      // Initialize the white balance object
      if ( ! IsWhiteBalanceSupported() )
      {
        assert( IsMono() );
        // raw monochrome image data, white balance feature not supported by the device.
        // --> white balance is performed by modifying the LUT used for the 
        // Bayer->RGB conversion
        m_WhiteBalancer.Init(GetBGain() * 100, GetRGain() * 100);
      }
      else
      {
        // white balance will be performed using the device's 
        // white balance scalar feature
        m_WhiteBalancer.Init(WhiteBalance.Raw.UBValue(), WhiteBalance.Raw.VRValue());
      }

      eState state;
      if ( IsContinuousGrabActive()  )
      {
        // cancel running continuous grab
        GrabCancel();
        state = sAutoWhiteBalanceCont;
      }
      else
        state = sAutoWhiteBalanceIdle;

      // Start single grab
      StartSingleGrab(state);

      // the auto white balance will be performed by the acquisition thread
    }
  }
}

//------------------------------------------------------------------------------
// void CCamera::GrabCancel()
// Author: 
//------------------------------------------------------------------------------
/**
* Cancel continuous grabbing.
*  * kill timer to display framerates ( if the last grabbing instance is to be cancelled )
*  * suspend the display thread ( to prevent it from accessing image buffers )
*  * cancel pending i/o requests
*
* \return void
*/
//------------------------------------------------------------------------------

void CCamera::GrabCancel()
{
  DWORD error = 0;

  if ( IsContinuousGrabActive() )
  {
    s_cGrabsActive --;  // bookkeeping of numbers of running continuous grabs
    // if last grab is canceled we have to kill the timer used to display frame rates
    if ( s_cGrabsActive == 0 )
      m_MainFrame.KillTimer(TIMERID);
    error = CancelContinuousGrab();
  }
  else
  {
    // cancel single grab
    CAutoLock<CCriticalSection> lock(m_csAcquisition);
    m_State = sIdle;
    try
    {
      Cancel(); // cancel I/O requests 
      if ( IsBandwidthAllocated() )
        FreeResources();
    }
    catch ( BcamException& e )
    {
      if ( e.Error() != ERROR_DEVICE_REMOVED )
        error = e.Error();
    }
  }

⌨️ 快捷键说明

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