Basler相機SDK開發

作爲集成商,本着萬事從官方開始的原則,先來到basler官網https://www.baslerweb.com/cn/
隨便找一款相機,下載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();
		}
	}
}

 

發佈了60 篇原創文章 · 獲贊 8 · 訪問量 9680
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章