• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Basler相机Sdk采图的例程C#

武飞扬头像
~晓广~
帮助1

这个话题的起因是追求极速的拍图速度。

机器ppm不达标的情况下,往往对视觉的处理速度有变态的要求,为了争取处理时间最短,几十毫秒也要争取。

halcon的接口是通用接口,其速度是比不上相机厂商自己相机配套的SDK的采图速度的。

下面程序运行后,500w的CCD拍图的时间(不算显示时间)达到惊人的32毫秒,如果用halcon接口,最快的我见过是180毫秒。

学新通

  1.  
    using Basler.Pylon;
  2.  
    using HalconDotNet;
  3.  
    using System;
  4.  
    using System.Collections.Generic;
  5.  
    using System.ComponentModel;
  6.  
    using System.Data;
  7.  
    using System.Diagnostics;
  8.  
    using System.Drawing;
  9.  
    using System.Linq;
  10.  
    using System.Runtime.InteropServices;
  11.  
    using System.Text;
  12.  
    using System.Threading;
  13.  
    using System.Threading.Tasks;
  14.  
    using System.Windows.Forms;
  15.  
     
  16.  
    namespace WindowsFormsApplication1
  17.  
    {
  18.  
    public partial class Form1 : Form
  19.  
    {
  20.  
    private PixelDataConverter converter = new PixelDataConverter();
  21.  
    /// <summary>
  22.  
    /// 相机ID
  23.  
    /// </summary>
  24.  
    public string UserID { get { return userID; } }
  25.  
    private string userID = string.Empty;
  26.  
     
  27.  
    private Stopwatch sw = new Stopwatch();
  28.  
    private bool isOkGrab = false;
  29.  
    private IntPtr latestFrameAddress = IntPtr.Zero;
  30.  
    public HObject Image { get { return image; } }
  31.  
    private HObject image = null;
  32.  
    static Version Sfnc2_0_0 = new Version(2, 0, 0);
  33.  
    private Camera camera = null;
  34.  
    HTuple handle;
  35.  
    public Form1()
  36.  
    {
  37.  
    InitializeComponent();
  38.  
    }
  39.  
     
  40.  
    private void button1_Click(object sender, EventArgs e)
  41.  
    {
  42.  
    var f1=BaslerCameraInit();
  43.  
    if(f1)
  44.  
    {
  45.  
    MessageBox.Show( Open().ToString());
  46.  
    }
  47.  
    }
  48.  
     
  49.  
     
  50.  
    /// <summary>
  51.  
    /// 实例化第一个找到的相机
  52.  
    /// </summary>
  53.  
    public bool BaslerCameraInit()
  54.  
    {
  55.  
    try
  56.  
    {
  57.  
    camera = new Camera();
  58.  
    camera.StreamGrabber.ImageGrabbed -= StreamGrabber_ImageGrabbed;
  59.  
    camera.StreamGrabber.ImageGrabbed =StreamGrabber_ImageGrabbed;
  60.  
    return true;
  61.  
    }
  62.  
    catch (Exception ex)
  63.  
    {
  64.  
    return false;
  65.  
    //NotifyG.Error(ex.ToString());
  66.  
    }
  67.  
    }
  68.  
     
  69.  
     
  70.  
    /// <summary>
  71.  
    /// 根据相机UserID实例化相机
  72.  
    /// </summary>
  73.  
    /// <param name="UserID"></param>
  74.  
    public bool BaslerCameraInit(string userID)
  75.  
    {
  76.  
    try
  77.  
    {
  78.  
    // 枚举相机列表
  79.  
    List<ICameraInfo> allCameraInfos = CameraFinder.Enumerate();
  80.  
    foreach (ICameraInfo cameraInfo in allCameraInfos)
  81.  
    {
  82.  
    if (userID == cameraInfo[CameraInfoKey.UserDefinedName])
  83.  
    {
  84.  
    this.userID = userID;
  85.  
    camera = new Camera(cameraInfo);
  86.  
    camera.StreamGrabber.ImageGrabbed -= StreamGrabber_ImageGrabbed;
  87.  
    camera.StreamGrabber.ImageGrabbed = StreamGrabber_ImageGrabbed;
  88.  
    }
  89.  
    }
  90.  
    if (camera == null)
  91.  
    {
  92.  
    //NotifyG.Error("未识别到UserID为“" UserID "”的相机!");
  93.  
    return false;
  94.  
    }
  95.  
    return true;
  96.  
    }
  97.  
    catch (Exception ex)
  98.  
    {
  99.  
    return false;
  100.  
    //NotifyG.Error(ex.ToString());
  101.  
    }
  102.  
    }
  103.  
     
  104.  
     
  105.  
    void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
  106.  
    {
  107.  
    try
  108.  
    {
  109.  
    // Acquire the image from the camera. Only show the latest image. The camera may acquire images faster than the images can be displayed.
  110.  
     
  111.  
    // Get the grab result.
  112.  
    IGrabResult grabResult = e.GrabResult;
  113.  
     
  114.  
    // Check if the image can be displayed.
  115.  
    if (grabResult.IsValid)
  116.  
    {
  117.  
    //grabTime = sw.ElapsedMilliseconds;
  118.  
    //if (eventComputeGrabTime != null) eventComputeGrabTime(grabTime);
  119.  
     
  120.  
    //Reduce the number of displayed images to a reasonable amount if the camera is acquiring images very fast.
  121.  
    // **** 降低显示帧率,减少CPU占用率 **** //
  122.  
    //if (!stopWatch.IsRunning || stopWatch.ElapsedMilliseconds > 33)
  123.  
    {
  124.  
    //stopWatch.Restart();
  125.  
    // 判断是否是黑白图片格式
  126.  
    if (grabResult.PixelTypeValue == PixelType.Mono8)
  127.  
    {
  128.  
    //allocate the m_stream_size amount of bytes in non-managed environment
  129.  
    if (latestFrameAddress == IntPtr.Zero)
  130.  
    {
  131.  
    latestFrameAddress = Marshal.AllocHGlobal((Int32)grabResult.PayloadSize);
  132.  
    }
  133.  
    converter.OutputPixelFormat = PixelType.Mono8;
  134.  
    converter.Convert(latestFrameAddress, grabResult.PayloadSize, grabResult);
  135.  
    HOperatorSet.GenEmptyObj(out image);
  136.  
    image.Dispose();
  137.  
    // 转换为Halcon图像显示
  138.  
    HOperatorSet.GenImage1(out image, "byte", grabResult.Width, grabResult.Height, latestFrameAddress);
  139.  
    HOperatorSet.SetPart(handle, 0, 0, grabResult.Height - 1, grabResult.Width - 1);
  140.  
    }
  141.  
    else if (grabResult.PixelTypeValue == PixelType.BayerBG8 || grabResult.PixelTypeValue == PixelType.BayerGB8
  142.  
    || grabResult.PixelTypeValue == PixelType.BayerRG8 || grabResult.PixelTypeValue == PixelType.YUV422packed)
  143.  
    {
  144.  
    int imageWidth = grabResult.Width - 1;
  145.  
    int imageHeight = grabResult.Height - 1;
  146.  
    HOperatorSet.SetPart(handle, 0, 0, imageHeight, imageWidth);
  147.  
    int payloadSize = imageWidth * imageHeight;
  148.  
     
  149.  
    //allocate the m_stream_size amount of bytes in non-managed environment
  150.  
    if (latestFrameAddress == IntPtr.Zero)
  151.  
    {
  152.  
    latestFrameAddress = Marshal.AllocHGlobal((Int32)(3 * payloadSize));
  153.  
    }
  154.  
    converter.OutputPixelFormat = PixelType.RGB8packed; // 根据下面halcon转换的色彩格式bgr
  155.  
    converter.Parameters[PLPixelDataConverter.InconvertibleEdgeHandling].SetValue("Clip");
  156.  
    converter.Convert(latestFrameAddress, 3 * payloadSize, grabResult);
  157.  
     
  158.  
    HOperatorSet.GenImageInterleaved(out image, latestFrameAddress, "bgr",
  159.  
    (HTuple)imageWidth, (HTuple)imageHeight, -1, "byte", (HTuple)imageWidth, (HTuple)imageHeight, 0, 0, -1, 0);
  160.  
    }
  161.  
    else
  162.  
    {
  163.  
    //NotifyG.Error(DeviceName "拍照失败,相机图像格式设置");
  164.  
    return;
  165.  
    }
  166.  
    isOkGrab = true;
  167.  
    //MessageBox.Show(isOkGrab.ToString());
  168.  
    // 抛出图像处理事件
  169.  
    //if (EventGrab != null) EventGrab(this, new CameraGrabEventArgs(image));
  170.  
    }
  171.  
    }
  172.  
     
  173.  
    }
  174.  
    catch (Exception ex)
  175.  
    {
  176.  
    //MessageBox.Show(ex.ToString());
  177.  
    return;
  178.  
    }
  179.  
    finally
  180.  
    {
  181.  
    // Dispose the grab result if needed for returning it to the grab loop.
  182.  
    e.DisposeGrabResultIfClone();
  183.  
    }
  184.  
    }
  185.  
     
  186.  
    /// <summary>
  187.  
    /// 打开相机
  188.  
    /// </summary>
  189.  
    public bool Open()
  190.  
    {
  191.  
    try
  192.  
    {
  193.  
    if (camera.IsOpen) camera.Close();
  194.  
    Thread.Sleep(200);
  195.  
    camera.Open();
  196.  
    var imageWidth = camera.Parameters[PLCamera.Width].GetValue(); // 获取图像宽
  197.  
    var imageHeight = camera.Parameters[PLCamera.Height].GetValue(); // 获取图像高
  198.  
    GetMinMaxExposureTime();
  199.  
    GetMinMaxGain();
  200.  
    camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
  201.  
    //NotifyG.Debug(DeviceName "打开相机成功:" userID);
  202.  
    }
  203.  
    catch (Exception ex)
  204.  
    {
  205.  
    MessageBox.Show(ex.ToString());
  206.  
    return false;
  207.  
    }
  208.  
    return true;
  209.  
    }
  210.  
     
  211.  
    /// <summary>
  212.  
    /// 关闭相机,释放相关资源
  213.  
    /// </summary>
  214.  
    public new bool Close()
  215.  
    {
  216.  
    try
  217.  
    {
  218.  
    camera.Close();
  219.  
    camera.Dispose();
  220.  
    if (Image != null)
  221.  
    {
  222.  
    Image.Dispose();
  223.  
    }
  224.  
    if (latestFrameAddress != null)
  225.  
    {
  226.  
    Marshal.FreeHGlobal(latestFrameAddress);
  227.  
    latestFrameAddress = IntPtr.Zero;
  228.  
    }
  229.  
    //NotifyG.Debug(DeviceName "关闭相机成功:" userID);
  230.  
    }
  231.  
    catch (Exception ex)
  232.  
    {
  233.  
    MessageBox.Show(ex.ToString());
  234.  
    return false;
  235.  
    }
  236.  
    return true;
  237.  
    }
  238.  
     
  239.  
    /// <summary>
  240.  
    /// 单张采集
  241.  
    /// </summary>
  242.  
    public bool GrabImage()
  243.  
    {
  244.  
    try
  245.  
    {
  246.  
    isOkGrab = false;
  247.  
    sw.Restart();
  248.  
    if (camera.StreamGrabber.IsGrabbing)
  249.  
    {
  250.  
    //NotifyG.Error("相机当前正处于采集状态!");
  251.  
    return false;
  252.  
    }
  253.  
    else
  254.  
    {
  255.  
    camera.StreamGrabber.Start(1, GrabStrategy.LatestImages, GrabLoop.ProvidedByStreamGrabber);
  256.  
    //while (!isOkGrab)
  257.  
    //{
  258.  
    // if (sw.ElapsedMilliseconds > 2000) { isOkGrab = false; return false; }
  259.  
    // Thread.Sleep(1);
  260.  
    //}
  261.  
    //NotifyG.Debug(DeviceName "拍照成功:" sw.ElapsedMilliseconds);
  262.  
    return true;
  263.  
    }
  264.  
    }
  265.  
    catch (Exception ex)
  266.  
    {
  267.  
    MessageBox.Show(ex.ToString());
  268.  
    return false;
  269.  
    }
  270.  
    return true;
  271.  
    }
  272.  
     
  273.  
    /// <summary>
  274.  
    /// 开始连续采集
  275.  
    /// </summary>
  276.  
    public bool StartGrabbing()
  277.  
    {
  278.  
    try
  279.  
    {
  280.  
    if (camera.StreamGrabber.IsGrabbing)
  281.  
    {
  282.  
    //NotifyG.Error("相机当前正处于采集状态!");
  283.  
    return false;
  284.  
    }
  285.  
    else
  286.  
    {
  287.  
    camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
  288.  
    camera.StreamGrabber.Start(GrabStrategy.LatestImages, GrabLoop.ProvidedByStreamGrabber);
  289.  
     
  290.  
    return true;
  291.  
    }
  292.  
    }
  293.  
    catch (Exception ex)
  294.  
    {
  295.  
    //NotifyG.Error(DeviceName ex.ToString());
  296.  
    return false;
  297.  
    }
  298.  
    }
  299.  
     
  300.  
    /// <summary>
  301.  
    /// 停止连续采集
  302.  
    /// </summary>
  303.  
    public bool StopGrabbing()
  304.  
    {
  305.  
    try
  306.  
    {
  307.  
    if (camera.StreamGrabber.IsGrabbing)
  308.  
    {
  309.  
    camera.StreamGrabber.Stop();
  310.  
    }
  311.  
    }
  312.  
    catch (Exception ex)
  313.  
    {
  314.  
    //NotifyG.Error(DeviceName ex.ToString());
  315.  
    }
  316.  
    return true;
  317.  
    }
  318.  
     
  319.  
     
  320.  
    /// <summary>
  321.  
    /// 获取最小最大曝光时间
  322.  
    /// </summary>
  323.  
    public void GetMinMaxExposureTime()
  324.  
    {
  325.  
    try
  326.  
    {
  327.  
    if (camera.GetSfncVersion() < Sfnc2_0_0)
  328.  
    {
  329.  
    var minExposureTime = camera.Parameters[PLCamera.ExposureTimeRaw].GetMinimum();
  330.  
    var maxExposureTime = camera.Parameters[PLCamera.ExposureTimeRaw].GetMaximum();
  331.  
    }
  332.  
    else
  333.  
    {
  334.  
    var minExposureTime = (long)camera.Parameters[PLUsbCamera.ExposureTime].GetMinimum();
  335.  
    var maxExposureTime = (long)camera.Parameters[PLUsbCamera.ExposureTime].GetMaximum();
  336.  
    }
  337.  
    }
  338.  
    catch (Exception ex)
  339.  
    {
  340.  
     
  341.  
    }
  342.  
    }
  343.  
     
  344.  
    /// <summary>
  345.  
    /// 获取最小最大增益
  346.  
    /// </summary>
  347.  
    public void GetMinMaxGain()
  348.  
    {
  349.  
    try
  350.  
    {
  351.  
    if (camera.GetSfncVersion() < Sfnc2_0_0)
  352.  
    {
  353.  
    var minGain = camera.Parameters[PLCamera.GainRaw].GetMinimum();
  354.  
    var maxGain = camera.Parameters[PLCamera.GainRaw].GetMaximum();
  355.  
    }
  356.  
    else
  357.  
    {
  358.  
    var minGain = (long)camera.Parameters[PLUsbCamera.Gain].GetMinimum();
  359.  
    var maxGain = (long)camera.Parameters[PLUsbCamera.Gain].GetMaximum();
  360.  
    }
  361.  
    }
  362.  
    catch (Exception ex)
  363.  
    {
  364.  
    //NotifyG.Error(DeviceName ex.ToString());
  365.  
    }
  366.  
    }
  367.  
     
  368.  
    private void button2_Click(object sender, EventArgs e)
  369.  
    {
  370.  
    Stopwatch sw1 = new Stopwatch();
  371.  
    sw1.Start();
  372.  
    var f1 = GrabImage();
  373.  
    sw1.Stop();
  374.  
    MessageBox.Show(string.Format("grab time:{0}",sw1.ElapsedMilliseconds));
  375.  
    //if(f1)
  376.  
    //{
  377.  
    // if (null != Image)
  378.  
    // HOperatorSet.DispObj(Image, hWindowControl1.Handle);
  379.  
    //}
  380.  
    }
  381.  
     
  382.  
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  383.  
    {
  384.  
    if (null != camera && camera.IsOpen)
  385.  
    Close();
  386.  
    }
  387.  
     
  388.  
    private void button6_Click(object sender, EventArgs e)
  389.  
    {
  390.  
    try
  391.  
    {
  392.  
    if (null != Image && Image.IsInitialized())
  393.  
    {
  394.  
    //HOperatorSet.WriteImage(Image, "bmp", 0, "d:\\123.bmp");
  395.  
    HOperatorSet.DispObj(Image, handle);
  396.  
    }
  397.  
    }
  398.  
    catch (Exception ex)
  399.  
    {
  400.  
    MessageBox.Show(ex.Message);
  401.  
    }
  402.  
    }
  403.  
     
  404.  
    private void Form1_Load(object sender, EventArgs e)
  405.  
    {
  406.  
    handle = hWindowControl1.HalconWindow;
  407.  
     
  408.  
    }
  409.  
     
  410.  
    private void button3_Click(object sender, EventArgs e)
  411.  
    {
  412.  
    timer1.Start();
  413.  
    StartGrabbing();
  414.  
    }
  415.  
     
  416.  
    private void button4_Click(object sender, EventArgs e)
  417.  
    {
  418.  
    timer1.Stop();
  419.  
    StopGrabbing();
  420.  
    }
  421.  
     
  422.  
    private void timer1_Tick(object sender, EventArgs e)
  423.  
    {
  424.  
    button6_Click(null, null);
  425.  
    }
  426.  
     
  427.  
     
  428.  
    }
  429.  
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfkcba
系列文章
更多 icon
同类精品
更多 icon
继续加载