Basler相机SDK开发

作为集成商,本着万事从官方开始的原则,先来到basler官网Basler – 德国工业相机_工业镜头_工业光源_线材等视觉组件提供商
随便找一款相机,下载Basler pylon相机软件套装,下载pylon6.0.1相机软件套装(windows版本)

 

我这里用的是pylon5,一样的,安装的时候注意development装上,gige√上,usb√上

这里安装完软件,把手上的相机接到电脑上,首先要做的肯定是配置一下相机的IP等等之类的东西,不然你是连不上相机滴
具体怎么做见上一篇博客https://blog.csdn.net/qq_33628827/article/details/103857266

打开软件安装位置,选到basler/pylon/development/samples/C#/Basler.Pylon,双击打开pylon.NET.API.Samples.sln

这里我们只看其中的两个官方例子,一个是Grab,一个是PylonLiveView,这能满足我们基本的图像采集需求

下面是Grab项目代码分析

        /*
This sample illustrates how to grab images and process images asynchronously.
This means that while the application is processing a buffer,
the acquisition of the next buffer is done in parallel.
The sample uses a pool of buffers. The buffers are automatically allocated. Once a buffer is filled
and ready for processing, the buffer is retrieved from the stream grabber as part of a grab
result. The grab result is processed and the buffer is passed back to the stream grabber by
disposing the grab result. The buffer is reused and refilled.
A buffer retrieved from the stream grabber as a grab result is not overwritten in the background
as long as the grab result is not disposed.
*/

using System;
using Basler.Pylon;

namespace Grab
{
	class Grab
	{
		internal static void Main()
		{
			// The exit code of the sample application.
			int exitCode = 0;

			try
			{
				// Create a camera object that selects the first camera device found.
				// More constructors are available for selecting a specific camera device.
				//新建一个相机对象
				using (Camera camera = new Camera())
				{
					// Print the model name of the camera.
					Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);

					// Set the acquisition mode to free running continuous acquisition when the camera is opened.
					camera.CameraOpened += Configuration.AcquireContinuous;

					// Open the connection to the camera device.
					//打开相机
					camera.Open();

					// The parameter MaxNumBuffer can be used to control the amount of buffers
					// allocated for grabbing. The default value of this parameter is 10.
					//设置最大缓冲数,默认数值是10
					camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);

					// Start grabbing.
					//开始采集图像
					camera.StreamGrabber.Start();

					// Grab a number of images.
					//工采集10帧图像
					for (int i = 0; i < 10; ++i)
					{
						// Wait for an image and then retrieve it. A timeout of 5000 ms is used.
						//采集结果,超时时间5000ms
						IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
						using (grabResult)
						{
							// Image grabbed successfully?
							//判断是否采集成功
							if (grabResult.GrabSucceeded)
							{
								// Access the image data.
								Console.WriteLine("SizeX: {0}", grabResult.Width);//图像宽
								Console.WriteLine("SizeY: {0}", grabResult.Height);//图像高
								byte[] buffer = grabResult.PixelData as byte[];
								//第一个像素的灰度值
								Console.WriteLine("Gray value of first pixel: {0}", buffer[0]);
								Console.WriteLine("");

								// Display the grabbed image.
								//显示图像
								ImageWindow.DisplayImage(0, grabResult);
							}
							else
							{
								Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
							}
						}
					}//end using

					 // Stop grabbing.
					camera.StreamGrabber.Stop();

					// Close the connection to the camera device.
					camera.Close();
				}
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("Exception: {0}", e.Message);
				exitCode = 1;
			}
			finally
			{
				// Comment the following two lines to disable waiting on exit.
				Console.Error.WriteLine("\nPress enter to exit.");
				Console.ReadLine();
			}

			Environment.Exit(exitCode);
		}
	}
}

以上代码运行将连续采集10张图像,在控制台上打印每幅图像第一个点的灰度值,并且显示最后一张图像在baslerSDk自带的窗口上。

下面是PylonLive项目代码分析,这个是带有一个自带窗口,可实时采集与触发采集的例子

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using PylonLiveView;
using Basler.Pylon;


namespace PylonLiveView
{
	// The main window.
	public partial class MainForm : Form
	{
		private Camera camera = null;
		//图像转换
		private PixelDataConverter converter = new PixelDataConverter();
		//测量时间
		private Stopwatch stopWatch = new Stopwatch();

		// Set up the controls and events to be used and update the device list.
		public MainForm()
		{
			InitializeComponent();//初始化控件

								  // Set the default names for the controls.
								  //设置各个组合控件的名字
			testImageControl.DefaultName = "Test Image Selector";
			pixelFormatControl.DefaultName = "Pixel Format";
			widthSliderControl.DefaultName = "Width";
			heightSliderControl.DefaultName = "Height";
			gainSliderControl.DefaultName = "Gain";
			exposureTimeSliderControl.DefaultName = "Exposure Time";

			// Update the list of available camera devices in the upper left area.
			//更新相机设备信息
			UpdateDeviceList();

			// Disable all buttons.
			EnableButtons(false, false);
		}


		// Occurs when the single frame acquisition button is clicked.
		private void toolStripButtonOneShot_Click(object sender, EventArgs e)
		{
			OneShot(); // Start the grabbing of one image.
		}


		// Occurs when the continuous frame acquisition button is clicked.
		private void toolStripButtonContinuousShot_Click(object sender, EventArgs e)
		{
			ContinuousShot(); // Start the grabbing of images until grabbing is stopped.
		}


		// Occurs when the stop frame acquisition button is clicked.
		private void toolStripButtonStop_Click(object sender, EventArgs e)
		{
			Stop(); // Stop the grabbing of images.
		}


		// Occurs when a device with an opened connection is removed.
		private void OnConnectionLost(Object sender, EventArgs e)
		{
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper thread.
				BeginInvoke(new EventHandler<EventArgs>(OnConnectionLost), sender, e);
				return;
			}

			// Close the camera object.
			DestroyCamera();
			// Because one device is gone, the list needs to be updated.
			UpdateDeviceList();
		}


		// Occurs when the connection to a camera device is opened.
		private void OnCameraOpened(Object sender, EventArgs e)
		{
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper thread.
				BeginInvoke(new EventHandler<EventArgs>(OnCameraOpened), sender, e);
				return;
			}

			// The image provider is ready to grab. Enable the grab buttons.
			EnableButtons(true, false);
		}


		// Occurs when the connection to a camera device is closed.
		private void OnCameraClosed(Object sender, EventArgs e)
		{
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper thread.
				BeginInvoke(new EventHandler<EventArgs>(OnCameraClosed), sender, e);
				return;
			}

			// The camera connection is closed. Disable all buttons.
			EnableButtons(false, false);
		}


		// Occurs when a camera starts grabbing.
		private void OnGrabStarted(Object sender, EventArgs e)
		{
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper thread.
				BeginInvoke(new EventHandler<EventArgs>(OnGrabStarted), sender, e);
				return;
			}

			// Reset the stopwatch used to reduce the amount of displayed images. The camera may acquire images faster than the images can be displayed.

			stopWatch.Reset();

			// Do not update the device list while grabbing to reduce jitter. Jitter may occur because the GUI thread is blocked for a short time when enumerating.
			updateDeviceListTimer.Stop();

			// The camera is grabbing. Disable the grab buttons. Enable the stop button.
			EnableButtons(false, true);
		}


		// Occurs when an image has been acquired and is ready to be processed.
		private void OnImageGrabbed(Object sender, ImageGrabbedEventArgs e)
		{
			//跨线程访问控件
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper GUI thread.
				// The grab result will be disposed after the event call. Clone the event arguments for marshaling to the GUI thread.
				BeginInvoke(new EventHandler<ImageGrabbedEventArgs>(OnImageGrabbed), sender, e.Clone());
				return;
			}

			try
			{
				// Acquire the image from the camera. Only show the latest image. The camera may acquire images faster than the images can be displayed.

				// Get the grab result.
				IGrabResult grabResult = e.GrabResult;

				// Check if the image can be displayed.
				if (grabResult.IsValid)
				{
					// Reduce the number of displayed images to a reasonable amount if the camera is acquiring images very fast.
					if (!stopWatch.IsRunning || stopWatch.ElapsedMilliseconds > 33)
					{
						stopWatch.Restart();

						Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
						// Lock the bits of the bitmap.
						BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
						// Place the pointer to the buffer of the bitmap.
						converter.OutputPixelFormat = PixelType.BGRA8packed;
						IntPtr ptrBmp = bmpData.Scan0;
						converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
						bitmap.UnlockBits(bmpData);

						// Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
						Bitmap bitmapOld = pictureBox.Image as Bitmap;
						// Provide the display control with the new bitmap. This action automatically updates the display.
						pictureBox.Image = bitmap;
						if (bitmapOld != null)
						{
							// Dispose the bitmap.
							bitmapOld.Dispose();
						}
					}
				}
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
			finally
			{
				// Dispose the grab result if needed for returning it to the grab loop.
				e.DisposeGrabResultIfClone();
			}
		}


		// Occurs when a camera has stopped grabbing.
		private void OnGrabStopped(Object sender, GrabStopEventArgs e)
		{
			if (InvokeRequired)
			{
				// If called from a different thread, we must use the Invoke method to marshal the call to the proper thread.
				BeginInvoke(new EventHandler<GrabStopEventArgs>(OnGrabStopped), sender, e);
				return;
			}

			// Reset the stopwatch.
			stopWatch.Reset();

			// Re-enable the updating of the device list.
			updateDeviceListTimer.Start();

			// The camera stopped grabbing. Enable the grab buttons. Disable the stop button.
			EnableButtons(true, false);

			// If the grabbed stop due to an error, display the error message.
			if (e.Reason != GrabStopReason.UserRequest)
			{
				MessageBox.Show("A grab error occured:\n" + e.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}


		// Helps to set the states of all buttons.
		private void EnableButtons(bool canGrab, bool canStop)
		{
			toolStripButtonContinuousShot.Enabled = canGrab;
			toolStripButtonOneShot.Enabled = canGrab;
			toolStripButtonStop.Enabled = canStop;
		}


		// Stops the grabbing of images and handles exceptions.
		private void Stop()
		{
			// Stop the grabbing.
			try
			{
				camera.StreamGrabber.Stop();
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
		}


		// Closes the camera object and handles exceptions.
		private void DestroyCamera()
		{
			// Disable all parameter controls.
			try
			{
				if (camera != null)
				{

					testImageControl.Parameter = null;
					pixelFormatControl.Parameter = null;
					widthSliderControl.Parameter = null;
					heightSliderControl.Parameter = null;
					gainSliderControl.Parameter = null;
					exposureTimeSliderControl.Parameter = null;
				}
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}

			// Destroy the camera object.
			try
			{
				if (camera != null)
				{
					camera.Close();
					camera.Dispose();
					camera = null;
				}
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
		}


		// Starts the grabbing of a single image and handles exceptions.
		private void OneShot()
		{
			try
			{
				// Starts the grabbing of one image.
				camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
				camera.StreamGrabber.Start(1, GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
		}


		// Starts the continuous grabbing of images and handles exceptions.
		private void ContinuousShot()
		{
			try
			{
				// Start the grabbing of images until grabbing is stopped.
				camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
				camera.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
		}


		// Updates the list of available camera devices.
		private void UpdateDeviceList()
		{
			try
			{
				// Ask the camera finder for a list of camera devices.
				//枚举电脑上的所有可用设备
				List<ICameraInfo> allCameras = CameraFinder.Enumerate();

				//当前已存在的相机列表
				ListView.ListViewItemCollection items = deviceListView.Items;

				// Loop over all cameras found.
				//循环所有可用的设备信息
				foreach(ICameraInfo cameraInfo in allCameras)
				{
					// Loop over all cameras in the list of cameras.
					bool newitem = true;
					foreach(ListViewItem item in items)
					{
						ICameraInfo tag = item.Tag as ICameraInfo;

						// Is the camera found already in the list of cameras?
						//检查当前查找到的相机是否已在相机列表中
						if (tag[CameraInfoKey.FullName] == cameraInfo[CameraInfoKey.FullName])
						{
							tag = cameraInfo;
							newitem = false;
							break;
						}
					}

					// If the camera is not in the list, add it to the list.
					//如果相机未在当前列表中添加到列表中
					if (newitem)
					{
						// Create the item to display.
						//创建一个Item,内容是当前相机的FriendlyName
						ListViewItem item = new ListViewItem(cameraInfo[CameraInfoKey.FriendlyName]);

						// Create the tool tip text.
						string toolTipText = "";
						foreach(KeyValuePair<string, string> kvp in cameraInfo)
						{
							toolTipText += kvp.Key + ": " + kvp.Value + "\n";
						}
						item.ToolTipText = toolTipText;

						// Store the camera info in the displayed item.
						item.Tag = cameraInfo;

						// Attach the device data.
						//把Item添加到List中
						deviceListView.Items.Add(item);
					}
				}



				// Remove old camera devices that have been disconnected.
				//从相机列表中移除不存在的相机
				foreach(ListViewItem item in items)
				{
					bool exists = false;

					// For each camera in the list, check whether it can be found by enumeration.
					foreach(ICameraInfo cameraInfo in allCameras)
					{
						if (((ICameraInfo)item.Tag)[CameraInfoKey.FullName] == cameraInfo[CameraInfoKey.FullName])
						{
							exists = true;
							break;
						}
					}
					// If the camera has not been found, remove it from the list view.
					if (!exists)
					{
						deviceListView.Items.Remove(item);
					}
				}
			}
			catch (Exception exception)
			{
				ShowException(exception);
			}
		}


		// Shows exceptions in a message box.
		private void ShowException(Exception exception)
		{
			//发生错误信息时弹出一个MessageBox提示错误信息
			MessageBox.Show("Exception caught:\n" + exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}


		// Closes the camera object when the window is closed.
		private void MainForm_FormClosing(object sender, FormClosingEventArgs ev)
		{
			// Close the camera object.
			//关闭相机,释放相机资源,这一步是必须的,如果关闭程序没有执行这一步,相机将一直处于被占用状态
			DestroyCamera();
		}


		// Occurs when a new camera has been selected in the list. Destroys the object of the currently opened camera device and
		// creates a new object for the selected camera device. After that, the connection to the selected camera device is opened.
		private void deviceListView_SelectedIndexChanged(object sender, EventArgs ev)
		{
			// Destroy the old camera object.
			if (camera != null)
			{
				DestroyCamera();
			}


			// Open the connection to the selected camera device.
			if (deviceListView.SelectedItems.Count > 0)
			{
				// Get the first selected item.
				ListViewItem item = deviceListView.SelectedItems[0];
				// Get the attached device data.
				ICameraInfo selectedCamera = item.Tag as ICameraInfo;
				try
				{
					// Create a new camera object.
					camera = new Camera(selectedCamera);

					camera.CameraOpened += Configuration.AcquireContinuous;

					// Register for the events of the image provider needed for proper operation.
					//对相机注册相应的事件处理函数
					camera.ConnectionLost += OnConnectionLost;
					camera.CameraOpened += OnCameraOpened;
					camera.CameraClosed += OnCameraClosed;
					camera.StreamGrabber.GrabStarted += OnGrabStarted;
					camera.StreamGrabber.ImageGrabbed += OnImageGrabbed;//采集图像处理函数,当调用camera.StreamGrabber.Start函数的时候会触发
					camera.StreamGrabber.GrabStopped += OnGrabStopped;

					// Open the connection to the camera device.
					camera.Open();

					// Set the parameter for the controls.
					testImageControl.Parameter = camera.Parameters[PLCamera.TestImageSelector];
					pixelFormatControl.Parameter = camera.Parameters[PLCamera.PixelFormat];
					widthSliderControl.Parameter = camera.Parameters[PLCamera.Width];
					heightSliderControl.Parameter = camera.Parameters[PLCamera.Height];
					if (camera.Parameters.Contains(PLCamera.GainAbs))
					{
						gainSliderControl.Parameter = camera.Parameters[PLCamera.GainAbs];
					}
					else
					{
						gainSliderControl.Parameter = camera.Parameters[PLCamera.Gain];
					}
					if (camera.Parameters.Contains(PLCamera.ExposureTimeAbs))
					{
						exposureTimeSliderControl.Parameter = camera.Parameters[PLCamera.ExposureTimeAbs];
					}
					else
					{
						exposureTimeSliderControl.Parameter = camera.Parameters[PLCamera.ExposureTime];
					}
				}
				catch (Exception exception)
				{
					ShowException(exception);
				}
			}
		}


		// If the F5 key has been pressed, update the list of devices.
		private void deviceListView_KeyDown(object sender, KeyEventArgs ev)
		{
			if (ev.KeyCode == Keys.F5)
			{
				ev.Handled = true;
				// Update the list of available camera devices.
				UpdateDeviceList();
			}
		}


		// Timer callback used to periodically check whether displayed camera devices are still attached to the PC.
		private void updateDeviceListTimer_Tick(object sender, EventArgs e)
		{
			UpdateDeviceList();
		}
	}
}

所有搜索到的相机显示在列表框中,三个按钮分别控制列表框中被选中相机的单张采集,连续采集,停止采集图像,并且可以设置增益,曝光时间等参数

以上是官方的例程,仅仅是展示了相机的使用方式,但感觉跟我们的面向对象编程格格不入。下面是我封装的相机SDK类,内部已把图像装换成Halcon的图像格式HImage。添加到自己的项目中可以直接使用,其原理与以上介绍的第一个例程是完全一样的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Basler.Pylon;
using HalconDotNet;
namespace BaslerSdk
{
	class BaslerClass
	{
		List<ICameraInfo> allCameras = null;//ICameraInfo对象的列表,用于保存遍历到的所有相机信息
		Camera myCamera = null;//相机对象
		HImage image = null;

		//构造函数
		public BaslerClass()
		{
		}

		public int connectCamera(string id)//连接相机,通过相机ID找到对应的相机并打开。返回-1为失败,0为成功
		{
			allCameras = CameraFinder.Enumerate();//获取所有相机设备
			for (int i = 0; i < allCameras.Count; i++)
			{
				try
				{
					if (allCameras[i][CameraInfoKey.SerialNumber] == id)
					{
						//如果当前相机信息中序列号是指定的序列号,则实例化相机类
						myCamera = new Camera(allCameras[i]);
						myCamera.Open();//打开相机
						return 0;
					}
					continue;
				}
				catch
				{
					return -1;
				}
			}
			return -1;
		}

		public int startCamera()//相机开始采集,返回-1为失败,0为成功
		{
			try
			{
				myCamera.StreamGrabber.Start();
			}
			catch
			{
				return -1;
			}
			return 0;
		}
		public int stopCamera()//停止相机采集,返回-1为失败,1为成功
		{
			try
			{
				myCamera.StreamGrabber.Stop();
			}
			catch
			{
				return -1;
			}
			return 0;
		}

		public int closeCamera()//关闭相机,返回-1为失败,1为成功
		{
			try
			{
				myCamera.Close();
			}
			catch
			{
				return -1;
			}
			return 0;
		}

		public int softTrigger()//发送软触发命令
		{
			try
			{
				myCamera.ExecuteSoftwareTrigger();
			}
			catch
			{
				return -1;
			}
			return 0;
		}

		public HImage ReadBuffer()//读取相机buffer并转换成Halcon HImage格式的图像
		{
			if (myCamera == null)
			{
				return null;
			}
			IGrabResult grabResult = myCamera.StreamGrabber.RetrieveResult(4000, TimeoutHandling.ThrowException);//读取buffer,超时时间为4000ms
			image = new HImage();
			using (grabResult)
			{
				if (grabResult.GrabSucceeded)
				{
					if (IsMonoData(grabResult))
					{
						//如果是黑白图像,则利用GenImage1算子生成黑白图像
						byte[] buffer = grabResult.PixelData as byte[];
						IntPtr p = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
						image.GenImage1("byte", grabResult.Width, grabResult.Height, p);
					}
					else
					{
						if (grabResult.PixelTypeValue != PixelType.RGB8packed)
						{
							//如果图像不是RGB8格式,则将图像转换为RGB8,然后生成彩色图像
							//因为GenImageInterleaved算子能够生成的图像的数据,常见的格式只有RGB8
							//如果采集的图像是RGB8则不需转换,具体生成图像方法请自行测试编写。
							byte[] buffer_rgb = new byte[grabResult.Width * grabResult.Height * 3];
							Basler.Pylon.PixelDataConverter convert = new PixelDataConverter();
							convert.OutputPixelFormat = PixelType.RGB8packed;
							convert.Convert(buffer_rgb, grabResult);
							IntPtr p = Marshal.UnsafeAddrOfPinnedArrayElement(buffer_rgb, 0);
							image.GenImageInterleaved(p, "rgb", grabResult.Width, grabResult.Height, 0, "byte", grabResult.Width, grabResult.Height, 0, 0, -1, 0);
						}
					}
					return image;
				}
				else
				{
					return null;
				}
			}
		}

		public int setExposureTime(long ExposureTimeNum)//设置曝光时间us
		{
			try
			{
				myCamera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureTimeNum);
			}
			catch
			{
				return -1;
			}
			return 0;
		}
		public int pixelFormat(uint pixelType)//设置图像格式,黑白相机的只能设置成黑白图像
		{
			//1:Mono8 2:彩色YUV422
			try
			{
				if (pixelType == 1)
				{
					myCamera.Parameters[PLCamera.PixelFormat].TrySetValue(PLCamera.PixelFormat.Mono8);
				}
				else if (pixelType == 2)
				{
					myCamera.Parameters[PLCamera.PixelFormat].TrySetValue(PLCamera.PixelFormat.YUV422Packed);
				}
			}
			catch
			{
				return -1;
			}
			return 0;
		}

		public int setHeight(long height)//设置图像高度,数值不要超过相机的分辨率
		{
			try
			{
				if (myCamera.Parameters[PLCamera.Height].TrySetValue(height))
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}
		public int setWidth(long width)//设置图像宽度,数值不要超过相机的分辨率
		{
			try
			{
				if (myCamera.Parameters[PLCamera.Width].TrySetValue(width))
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}
		public int setOffsetX(long offsetX)//设置图像水平偏移
		{
			try
			{
				if (myCamera.Parameters[PLCamera.OffsetX].TrySetValue(offsetX))
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}
		public int setOffsetY(long offsetY)//设置图像竖直偏移
		{
			try
			{
				if (myCamera.Parameters[PLCamera.OffsetY].TrySetValue(offsetY))
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}
		public int setTriggerMode(uint TriggerModeNum)//设置触发模式开关
		{
			//1:为On 触发模式
			//0:Off 连续模式
			try
			{
				if (myCamera.Parameters[PLCamera.TriggerMode].TrySetValue(TriggerModeNum == 1 ? "On" : "Off"))
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}

		public int closeBalanceAuto()//关闭自动白平衡
		{
			try
			{
				myCamera.Parameters[PLCamera.BalanceWhiteAuto].TrySetValue("Off");
			}
			catch
			{
				return -1;
			}
			return 0;
		}
		public int setSoftTrigger()//设置软触发
		{
			try
			{
				if (myCamera.Parameters[PLCamera.TriggerSource].TrySetValue("Software"))//设置为软触发
					return 0;
				else
					return -1;
			}
			catch
			{
				return -1;
			}
		}
		private Boolean IsMonoData(IGrabResult iGrabResult)//判断图像是否为黑白格式
		{
			switch (iGrabResult.PixelTypeValue)
			{
			case PixelType.Mono1packed:
			case PixelType.Mono2packed:
			case PixelType.Mono4packed:
			case PixelType.Mono8:
			case PixelType.Mono8signed:
			case PixelType.Mono10:
			case PixelType.Mono10p:
			case PixelType.Mono10packed:
			case PixelType.Mono12:
			case PixelType.Mono12p:
			case PixelType.Mono12packed:
			case PixelType.Mono16:
				return true;
			default:
				return false;
			}
		}

		public void DestroyCamera()
		{
			// Disable all parameter controls.
			if (myCamera != null)
			{
				myCamera.Close();
				myCamera.Dispose();
				myCamera = null;
			}
		}
	}
}

下面的代码是调用的上面自己封装的类采集并处理图像的例子,要运行的话需要在窗口上拖几个按钮和一个Halcon窗口

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using Basler.Pylon;
namespace BaslerSdk
{
	public partial class BaslerSdk : Form
	{
		HWindow hWin;
		HImage hImage;
		BaslerClass camera;
		public BaslerSdk()
		{
			InitializeComponent();
			hWin = hWindowControl1.HalconWindow;//窗口句柄,使用窗口显示图像
			hImage = new HImage();

			List<ICameraInfo>  allCameras = CameraFinder.Enumerate();//获取所有相机设备
			if (allCameras.Count == 0)
			{
				return;
			}
			for (int i = 0; i < allCameras.Count; i++)
			{
				this.comboBox1.Items.Add(allCameras[i][CameraInfoKey.SerialNumber]);
			}
			camera = new BaslerClass();
			camera.connectCamera(allCameras[0][CameraInfoKey.SerialNumber].ToString());

		}
		///采集图像
		private void button1_Click(object sender, EventArgs e)
		{
			camera.startCamera();
			hImage = camera.ReadBuffer();
			hWin.DispImage(hImage);
			camera.stopCamera();
		}
		///对图像处理
		private void button2_Click(object sender, EventArgs e)
		{
			HOperatorSet.Threshold(hImage, out HObject ThreshRegion, 0, 50);

			hWin.DispObj(ThreshRegion);
		}
		///保存图像
		private void button3_Click(object sender, EventArgs e)
		{

		}
		///程序关闭时释放相机,让其他程序能正常使用相机
		private void BaslerSdk_FormClosing(object sender, FormClosingEventArgs e)
		{

			if (camera == null)
			{
				return;
			}
			camera.DestroyCamera();
		}
	}
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

究极调参工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值