HalCon学习笔记

一、连接相机算子

open_framegrabber:连接相机并设置一些基本的采集参数,如选择相机类型和指定采集设备

Parameters: 

1.HorizontalResolution:水平相对分辨率,如果是1,说明采集的图宽度和原图一样大,是2,表示采集的图宽度是原图的两倍,默认为1

2.VerticalResolution:垂直相对分辨率,如果是1,说明采集的图宽度和原图一样大

3.ImageWidth、ImageHeight:表示图像的宽和高,即每行、列的像素数,默认为0,表示原始图的宽、高度

4.StartRow、StartColumn:表示采集的图在原始图像上的起始坐标,这两个值默认都为0

5.Field:相机的类型,默认为default

6.BitsPerChannel:表示像素的位数,默认为-1

7.ColorSpace:表示颜色空间,默认为default,也可以选择Gray,表示灰度,或选择RGB,表示彩色

8.Generic:表示特定设备,默认为-1

9.CameraType:表示相机的类型,默认为default

10.Device:表示所连接的采集设备的编号,默认为default,如果不确定相机的编号,可使用info_framegrabber算子进行查询

11.Port:表示连接的端口,默认为-1

open_framegrabber ('File', 1, 1, 0, 0, 0, 0, 'default', -1, 'default', -1, 'false', 'printer_chip/printer_chip_01', 'default', 1, -1, AcqHandle)

二、具体代码


// LwVisionDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "LwVision.h"
#include "LwVisionDlg.h"
#include "afxdialogex.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CLwVisionDlg 对话框



CLwVisionDlg::CLwVisionDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_LWVISION_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CLwVisionDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_SHOW_WND, m_ctlShowWnd);
}

BEGIN_MESSAGE_MAP(CLwVisionDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDOK, &CLwVisionDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDCANCEL, &CLwVisionDlg::OnBnClickedCancel)
END_MESSAGE_MAP()


// CLwVisionDlg 消息处理程序

BOOL CLwVisionDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时,框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	

	//打开相机
	OpenFramegrabber("File", 1, 1, 0, 0, 0, 0, "default", -1, "default", -1, "false",
		"printer_chip/printer_chip_01", "default", 1, -1, &hv_AcqHandle);

	//开窗口
	CRect rct;
	m_ctlShowWnd.GetClientRect(rct);
	long lWindowID = 0;
	long m_nPicWidth = rct.Width();
	long m_nPicHeigth = rct.Height();

	lWindowID = (long)m_ctlShowWnd.GetSafeHwnd();

	OpenWindow(0, 0, (Hlong)m_nPicWidth, (Hlong)m_nPicHeigth, lWindowID, "visible", "", &hWndID);

	//采图
	GrabImage(&ho_Image, hv_AcqHandle);

	//显示
	HTuple hW, hH;
	GetImageSize(ho_Image, &hW, &hH);
	SetPart(hWndID, 0, 0, hH, hW);

	DispObj(ho_Image, hWndID);


	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

void CLwVisionDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮,则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序,
//  这将由框架自动完成。

void CLwVisionDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CLwVisionDlg::OnQueryDragIcon()
{
	return static_cast(m_hIcon);
}



void CLwVisionDlg::OnBnClickedOk()
{
	// TODO: 在此添加控件通知处理程序代码
	CDialogEx::OnOK();
}


void CLwVisionDlg::OnBnClickedCancel()
{
	// TODO: 在此添加控件通知处理程序代码

	CloseFramegrabber(hv_AcqHandle);


	CDialogEx::OnCancel();
}

此部分为HalCon导出C++程序代码

///
// File generated by HDevelop for HALCON/C++ Version 21.11.0.0
// Non-ASCII strings in this file are encoded in local-8-bit encoding (cp936).
// Ensure that the interface encoding is set to locale encoding by calling
// SetHcppInterfaceStringEncodingIsUtf8(false) at the beginning of the program.
// 
// Please note that non-ASCII characters in string constants are exported
// as octal codes in order to guarantee that the strings are correctly
// created on all systems, independent on any compiler settings.
// 
// Source files with different encoding should not be mixed in one project.
///



#ifndef __APPLE__
#  include "HalconCpp.h"
#  include "HDevThread.h"
#else
#  ifndef HC_LARGE_IMAGES
#    include 
#    include 
#    include 
#  else
#    include 
#    include 
#    include 
#  endif
#  include 
#  include 
#endif



using namespace HalconCpp;


#ifndef NO_EXPORT_MAIN
// Main procedure 
void action()
{

  // Local iconic variables
  HObject  ho_Image;

  // Local control variables
  HTuple  hv_AcqHandle;

  //Image Acquisition 01: Code generated by Image Acquisition 01
  OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", -1, "false",
      "default", "[1] 2", 0, -1, &hv_AcqHandle);
  while (true)
  {
    GrabImage(&ho_Image, hv_AcqHandle);
    //Image Acquisition 01: Do something
  }
  CloseFramegrabber(hv_AcqHandle);

}


#ifndef NO_EXPORT_APP_MAIN

#ifdef __APPLE__
// On OS X systems, we must have a CFRunLoop running on the main thread in
// order for the HALCON graphics operators to work correctly, and run the
// action function in a separate thread. A CFRunLoopTimer is used to make sure
// the action function is not called before the CFRunLoop is running.
// Note that starting with macOS 10.12, the run loop may be stopped when a
// window is closed, so we need to put the call to CFRunLoopRun() into a loop
// of its own.
static HMutex*     sStartMutex;
static H_pthread_t sActionThread;
static bool        sTerminate = false;

static void timer_callback(CFRunLoopTimerRef timer, void *info)
{
  sStartMutex->UnlockMutex();
}

static Herror apple_action(void **parameters)
{
  // Wait until the timer has fired to start processing.
  sStartMutex->LockMutex();
  sStartMutex->UnlockMutex();

  try
  {
    action();
  }
  catch (HException &exception)
  {
    fprintf(stderr,"  Error #%u in %s: %s\n", exception.ErrorCode(),
            exception.ProcName().TextA(),
            exception.ErrorMessage().TextA());
  }

  // Tell the main thread to terminate itself.
  sStartMutex->LockMutex();
  sTerminate = true;
  sStartMutex->UnlockMutex();
  CFRunLoopStop(CFRunLoopGetMain());
  return H_MSG_OK;
}

static int apple_main(int argc, char *argv[])
{
  Herror                error;
  CFRunLoopTimerRef     Timer;
  CFRunLoopTimerContext TimerContext = { 0, 0, 0, 0, 0 };

  sStartMutex = new HMutex("type","sleep");
  sStartMutex->LockMutex();

  error = HpThreadHandleAlloc(&sActionThread);
  if (H_MSG_OK != error)
  {
    fprintf(stderr,"HpThreadHandleAlloc failed: %d\n", error);
    exit(1);
  }

  error = HpThreadCreate(sActionThread,0,apple_action);
  if (H_MSG_OK != error)
  {
    fprintf(stderr,"HpThreadCreate failed: %d\n", error);
    exit(1);
  }

  Timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
                               CFAbsoluteTimeGetCurrent(),0,0,0,
                               timer_callback,&TimerContext);
  if (!Timer)
  {
    fprintf(stderr,"CFRunLoopTimerCreate failed\n");
    exit(1);
  }
  CFRunLoopAddTimer(CFRunLoopGetCurrent(),Timer,kCFRunLoopCommonModes);

  for (;;)
  {
    bool terminate;

    CFRunLoopRun();

    sStartMutex->LockMutex();
    terminate = sTerminate;
    sStartMutex->UnlockMutex();

    if (terminate)
      break;
  }

  CFRunLoopRemoveTimer(CFRunLoopGetCurrent(),Timer,kCFRunLoopCommonModes);
  CFRelease(Timer);

  error = HpThreadHandleFree(sActionThread);
  if (H_MSG_OK != error)
  {
    fprintf(stderr,"HpThreadHandleFree failed: %d\n", error);
    exit(1);
  }

  delete sStartMutex;
  return 0;
}
#endif

int main(int argc, char *argv[])
{
  int ret = 0;

  try
  {
#if defined(_WIN32)
    SetSystem("use_window_thread", "true");
#endif

    // file was stored with local-8-bit encoding
    //   -> set the interface encoding accordingly
    SetHcppInterfaceStringEncodingIsUtf8(false);

    // Default settings used in HDevelop (can be omitted)
    SetSystem("width", 512);
    SetSystem("height", 512);

#ifndef __APPLE__
    action();
#else
    ret = apple_main(argc,argv);
#endif
  }
  catch (HException &exception)
  {
    fprintf(stderr,"  Error #%u in %s: %s\n", exception.ErrorCode(),
            exception.ProcName().TextA(),
            exception.ErrorMessage().TextA());
    ret = 1;
  }
  return ret;
}

#endif


#endif



// LwVisionDlg.h: 头文件
//

#pragma once
#include "afxwin.h"
#include "SystemInclude.h"
// CLwVisionDlg 对话框
class CLwVisionDlg : public CDialogEx
{
// 构造
public:
	CLwVisionDlg(CWnd* pParent = nullptr);	// 标准构造函数

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_LWVISION_DIALOG };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV 支持


// 实现
public:
	HTuple hv_AcqHandle;
	HTuple hWndID;

	HObject ho_Image;
protected:
	HICON m_hIcon;

	// 生成的消息映射函数
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()
public:
	CStatic m_ctlShowWnd;
	afx_msg void OnBnClickedOk();
	afx_msg void OnBnClickedCancel();
};
#ifndef System_INCLUDE_H
#define System_INCLUDE_H

#include "halconcpp.h"
#pragma comment(lib,"halconcpp.lib")
using namespace HalconCpp;

#endif

三、运行结果

HalCon学习笔记_第1张图片

 

你可能感兴趣的:(机器视觉,halcon,学习,c++)