当前位置:   article > 正文

使用c#连接Basler相机,halcon显示采集图像_basler相机 c#

basler相机 c#

使用c#连接Basler相机,halcon显示采集图像

在这里插入图片描述

开发工具:vs2022

第一步下载Basler的sdk

去官网下载Basler的sdk,安装完成后找到C:\Program Files\Basler/Basler.Pylon.dll文件,将dll放入新建解决方案bin>Debug文件夹下

第二步下载halcon

同上将halcon的dll文件放入新建解决方案bin>Debug文件夹下

以上完成后在代码中引用
在这里插入图片描述
引用文件如下:
在这里插入图片描述
当然没有上面那些dll文件的话,可以私信我
话不多说上代码

初始化相机与UI
 #region[初始化相机与UI]

 public Form1()
 {
     InitializeComponent();
     string Mes = Init();
     if (Mes != "OK")
     {
         MessageBox.Show(Mes);
         return;
     }
 }
 //初始化相机
 public string Init()
 {
     try
     {
         camera = new Camera();
         camera.StreamGrabber.ImageGrabbed -= SetReadBuffer;
         camera.StreamGrabber.ImageGrabbed += SetReadBuffer;
         return "ok";
     }
     catch (Exception ex)
     {
         return $"Init failed,{ex.Message}";
     }

 }

 //初始化构造参数
 void SetReadBuffer(object sender, ImageGrabbedEventArgs e)
 {
     try
     {
         IGrabResult grabResult = e.GrabResult;
         if (grabResult.IsValid)
         {
             if (image != null && image.IsInitialized())
             {
                 image.Dispose();
             }
             // 确保 image 对象为空
            // HOperatorSet.GenEmptyObj(out image);

             int imageWidth = grabResult.Width - 1;
                 int imageHeight = grabResult.Height - 1;
                 HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, imageHeight, imageWidth);
                 int payloadSize = imageWidth * imageHeight;

                 if (latestFrameAddress == IntPtr.Zero)
                 {
                     latestFrameAddress = Marshal.AllocHGlobal((Int32)(3 * payloadSize));
                 }
                 converter.OutputPixelFormat = PixelType.RGB8packed;
                 converter.Parameters[PLPixelDataConverter.InconvertibleEdgeHandling].SetValue("Clip");
                 converter.Convert(latestFrameAddress, 3 * payloadSize, grabResult);

                 HOperatorSet.GenImageInterleaved(out image, latestFrameAddress, "bgr",
                          (HTuple)imageWidth, (HTuple)imageHeight, -1, "byte", (HTuple)imageWidth, (HTuple)imageHeight, 0, 0, -1, 0);
         }
     }
     catch (Exception ex)
     {
         return;
     }
     finally
     {
         e.DisposeGrabResultIfClone();
     }
 }
   /// <summary>
   /// 获取最小最大曝光时间
   /// </summary>
   public void GetMinMaxExposureTime()
   {
       try
       {
           if (camera.GetSfncVersion() < Sfnc2_0_0)
           {
               var minExposureTime = camera.Parameters[PLCamera.ExposureTimeRaw].GetMinimum();
               var maxExposureTime = camera.Parameters[PLCamera.ExposureTimeRaw].GetMaximum();
           }
           else
           {
               var minExposureTime = (long)camera.Parameters[PLUsbCamera.ExposureTime].GetMinimum();
               var maxExposureTime = (long)camera.Parameters[PLUsbCamera.ExposureTime].GetMaximum();
           }
       }
       catch (Exception ex)
       {

       }
   }

   /// <summary>
   /// 获取最小最大增益
   /// </summary>
   public void GetMinMaxGain()
   {
       try
       {
           if (camera.GetSfncVersion() < Sfnc2_0_0)
           {
               var minGain = camera.Parameters[PLCamera.GainRaw].GetMinimum();
               var maxGain = camera.Parameters[PLCamera.GainRaw].GetMaximum();
           }
           else
           {
               var minGain = (long)camera.Parameters[PLUsbCamera.Gain].GetMinimum();
               var maxGain = (long)camera.Parameters[PLUsbCamera.Gain].GetMaximum();
           }
       }
       catch (Exception ex)
       {
           //NotifyG.Error(DeviceName + ex.ToString());
       }
   }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118

操作相机

 /// <summary>
 /// 打开相机
 /// </summary>
 public bool Open()
 {
     try
     {
         if (camera.IsOpen) camera.Close();
         Thread.Sleep(200);
         camera.Open();
         if (camera.IsOpen)
         {
             var imageWidth = camera.Parameters[PLCamera.Width].GetValue(); // 获取图像宽 
             var imageHeight = camera.Parameters[PLCamera.Height].GetValue(); // 获取图像高
             GetMinMaxExposureTime();
             GetMinMaxGain();
             camera.Parameters[PLCamera.GammaEnable].SetValue(true);
             camera.Parameters[PLCamera.GammaSelector].SetValue(PLCamera.GammaSelector.sRGB);
         }
         else
         {
             MessageBox.Show("相机打开失败!");
             return false;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
         return false;
     }
     return true;
 }


 /// <summary>
 /// 关闭相机,释放相关资源
 /// </summary>
 public new bool Close()
 {
     try
     {
         camera.Close();
         camera.Dispose();
         if (latestFrameAddress != null)
         {
             Marshal.FreeHGlobal(latestFrameAddress);
             latestFrameAddress = IntPtr.Zero;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
         return false;
     }
     return true;
 }
 /// <summary>
 /// 开始连续采集
 /// </summary>
 public bool StartGrabbing()
 {
     try
     {
         if (camera.StreamGrabber.IsGrabbing)
         {
             return false;
         }
         else
         {
             camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
             camera.StreamGrabber.Start(GrabStrategy.LatestImages, GrabLoop.ProvidedByStreamGrabber);
             return true;
         }
     }
     catch (Exception ex)
     {
         return false;
     }
 }

 /// <summary>
 /// 停止连续采集
 /// </summary>
 public bool StopGrabbing()
 {
     try
     {
         if (camera.StreamGrabber.IsGrabbing)
         {
             camera.StreamGrabber.Stop();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("错误信息" + ex.ToString());
     }
     return true;
 }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100

相机属性设置

  private void but_open_Click(object sender, EventArgs e)
  {
      if (Open())
      {
          try
          {
              double TExposure = camera.Parameters[PLCamera.ExposureTimeAbs].GetValue();
              string txposure = TExposure.ToString();
              textBox1.Text = txposure;
              string Enums = camera.Parameters[PLCamera.GammaSelector].GetValue();
              if (Enums == "sRGB")
              {
                  comboBox2.SelectedIndex = 1;
              }
              else
              {
                  comboBox2.SelectedIndex = 0;
              }
              decimal exposureTime = Convert.ToDecimal(camera.Parameters[PLCamera.ExposureTimeAbs].GetValue());
              numericUpDown2.Value = exposureTime;
              btn_grap.Enabled = true;
              btn_stop.Enabled = true;
              checkBox1.Checked = camera.Parameters[PLCamera.GammaEnable].GetValue();
          }
          catch (Exception ex)
          {
              MessageBox.Show("初始化属性失败!" + ex.Message);
              return;
          }
      }
      else
      {
          MessageBox.Show("打开失败!");
          return;
      }
  }

  private void but_close_Click(object sender, EventArgs e)
  {
      if (btn_stop.Enabled)
      {
          Close();
          but_open.Enabled = true;
          btn_BalanceWhiteAuto.Enabled = false;
          btn_GainAuto.Enabled = false;
          but_Continuous.Enabled = false;
          ExposureAuto.Enabled = false;
          ExposureAuto_Continuous.Enabled = false;
      }
      else
      {
          MessageBox.Show("打开失败!");
      }
  }

  private void btn_grap_Click(object sender, EventArgs e)
  {
      if (latestFrameAddress != IntPtr.Zero)
      {
          Marshal.FreeHGlobal(latestFrameAddress);
      }
      if (!StartGrabbing()) return;
      btn_BalanceWhiteAuto.Enabled = true;
      btn_GainAuto.Enabled = true;
      but_Continuous.Enabled = true;
      ExposureAuto.Enabled = true;
      ExposureAuto_Continuous.Enabled = true;
      timer1.Interval = 100;
      timer1.Tick += new EventHandler(timer1_Tick);
      // 启动Timer
      timer1.Start();
  }

  private void timer1_Tick(object sender, EventArgs e)
  {
      if (image != null && image.IsInitialized() && hWindowControl1.HalconWindow != null)
      {
          HOperatorSet.DispObj(image, hWindowControl1.HalconWindow);
      }
  }

  private void btn_stop_Click(object sender, EventArgs e)
  {
      timer1.Stop();
  }

  private void hWindowControl1_HMouseMove(object sender, HMouseEventArgs e)
  {
      try
      {
          double x = e.X;
          double y = e.Y;
          if (image != null)
          {
              HTuple redValue;
              HImage result = new HImage(image);
              HOperatorSet.GetGrayval(image, (int)y, (int)x, out redValue);
              R_red.Text = redValue.D.ToString();
              G_gree.Text = redValue[1].D.ToString();
              B_blue.Text = redValue[2].D.ToString();
          }
      }
      catch (Exception ex)
      {
          // 处理异常
      }
  }

  private void btn_BalanceWhiteAuto_Click(object sender, EventArgs e)
  {
      camera.Parameters[PLCamera.AutoFunctionAOISelector].SetValue(PLCamera.AutoFunctionAOISelector.AOI2);
      camera.Parameters[PLCamera.AutoFunctionAOIUsageWhiteBalance].SetValue(true);
      camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue(PLCamera.BalanceWhiteAuto.Once);
  }

  private void btn_GainAuto_Click(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.GainAuto].SetValue(PLCamera.GainAuto.Once);
      }
      catch (Exception)
      {

          throw;
      }
  }


  private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
  {
      if (comboBox2.SelectedIndex == 0)
      {
          camera.Parameters[PLCamera.GammaSelector].SetValue(PLCamera.GammaSelector.User);
      }
      else
      {
          camera.Parameters[PLCamera.GammaSelector].SetValue(PLCamera.GammaSelector.sRGB);
      }
  }

  private void trackBar1_Scroll(object sender, EventArgs e)
  {
      int IInteger = trackBar1.Value;
      camera.Parameters[PLCamera.DigitalShift].SetValue(IInteger);
  }

  private void but_Continuous_Click(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.GainAuto].SetValue(PLCamera.GainAuto.Continuous);
      }
      catch (Exception)
      {

          throw;
      }
  }

  private void trackBar2_Scroll(object sender, EventArgs e)
  {
      numericUpDown1.Value = trackBar2.Value;
      camera.Parameters[PLCamera.GainRaw].SetValue(trackBar2.Value);
  }

  private void numericUpDown1_ValueChanged(object sender, EventArgs e)
  {
      trackBar2.Value = (int)numericUpDown1.Value;
      int num = (int)numericUpDown1.Value;
      camera.Parameters[PLCamera.GainRaw].SetValue(num);
  }

  private void checkBox1_CheckedChanged(object sender, EventArgs e)
  {
      bool rado = checkBox1.Checked;
      camera.Parameters[PLCamera.GammaEnable].SetValue(rado);
  }

  private void checkBox2_CheckedChanged(object sender, EventArgs e)
  {
      bool X = ReverseX.Checked;
      camera.Parameters[PLCamera.ReverseY].SetValue(X);
  }

  private void checkBox3_CheckedChanged(object sender, EventArgs e)
  {
      bool Y = ReverseY.Checked;
      camera.Parameters[PLCamera.ReverseX].SetValue(Y);
  }

  private void ExposureAuto_Click(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.ExposureAuto].SetValue(PLCamera.ExposureAuto.Once);
      }
      catch (Exception ex)
      {
          MessageBox.Show("曝光设置失败!" + ex.Message);
      }

  }

  private void ExposureAuto_Continuous_Click(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.ExposureAuto].SetValue(PLCamera.ExposureAuto.Continuous);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }

  }

  private void textBox1_TextChanged(object sender, EventArgs e)
  {
      try
      {
          string comboBox = textBox1.Text;
          float ExposureAbs = Convert.ToSingle(comboBox);
          camera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureAbs);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }

  }

  private void trackBar3_Scroll(object sender, EventArgs e)
  {
      try
      {

          int exposureValue = trackBar3.Value;
          numericUpDown2.Value = exposureValue;
          camera.Parameters[PLCamera.ExposureTimeRaw].SetValue(exposureValue);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }
  }

  private void numericUpDown2_ValueChanged(object sender, EventArgs e)
  {

      try
      {
          camera.Parameters[PLCamera.ExposureAuto].SetValue(PLCamera.ExposureAuto.Off);
          trackBar3.Value = (int)numericUpDown2.Value;
          int numericUpDown = Convert.ToInt32(numericUpDown2.Value);
          camera.Parameters[PLCamera.ExposureTimeRaw].SetValue(numericUpDown);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }
  }

  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  {
      if (camera != null && camera.IsOpen)
      {
          StopGrabbing();
          Close();
      }
  }

  private void button1_Click(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.AutoFunctionAOISelector].SetValue(PLCamera.AutoFunctionAOISelector.AOI2);
          camera.Parameters[PLCamera.AutoFunctionAOIUsageWhiteBalance].SetValue(true);
          camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue(PLCamera.BalanceWhiteAuto.Continuous);
      }
      catch (Exception ex)
      {
          MessageBox.Show("连续白平衡失败!" + ex.Message);
      }

  }

  private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
  {
      try
      {
          if (comboBox4.SelectedIndex == 0)
          {
              camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Red);
          }
          if (comboBox4.SelectedIndex == 1)
          {
              camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Green);
          }
          if (comboBox4.SelectedIndex == 2)
          {
              camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Blue);
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show("调整失败!" + ex.Message);
      }
  }

  private void numericUpDown3_ValueChanged(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue(PLCamera.BalanceWhiteAuto.Off);
          trackBar4.Value = (int)numericUpDown3.Value;
          int numericUpDown = Convert.ToInt32(numericUpDown3.Value);
          camera.Parameters[PLCamera.BalanceRatioRaw].SetValue(numericUpDown);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }
  }

  private void trackBar4_ValueChanged(object sender, EventArgs e)
  {
      try
      {
          camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue(PLCamera.BalanceWhiteAuto.Off);
          int exposureValue = trackBar4.Value;
          numericUpDown3.Value = exposureValue;
          camera.Parameters[PLCamera.BalanceRatioRaw].SetValue(exposureValue);
      }
      catch (Exception ex)
      {
          MessageBox.Show("错误信息" + ex.Message);
      }
  }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/229553
推荐阅读
相关标签
  

闽ICP备14008679号