电脑连接海康相机并在PictureBox和HWindowControl中分别显示。

news/2024/10/31 1:42:57/

展示结果:

下面附上界面中所有控件的Name,只需照着红字设置对应的控件Name即可

下面附上小编主界面的全部代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using MvCameraControl;namespace MVC
{public partial class Form1 : Form{// ch:枚举的相机类型 | en:TLayerType for enumerate devicesreadonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();IDevice device = null;bool isGrabbing = false; //是否正在取图Thread receiveThread = null;  //接收图像线程Thread receiveImage = null;IntPtr pictureBoxHandle = IntPtr.Zero; //显示图像的控件句柄public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){//初始化SDKSDKSystem.Initialize();//枚举设备RefreshDeviceList();}/// <summary>/// ch:显示错误信息 | en:Show error message/// </summary>private void ShowErrorMsg(string message, int errorCode){string errorMsg;if (errorCode == 0){errorMsg = message;}else{errorMsg = message + ": Error =" + String.Format("{0:X}", errorCode);}switch (errorCode){case MvError.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;case MvError.MV_E_SUPPORT: errorMsg += " Not supported function "; break;case MvError.MV_E_BUFOVER: errorMsg += " Cache is full "; break;case MvError.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;case MvError.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;case MvError.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;case MvError.MV_E_NODATA: errorMsg += " No data "; break;case MvError.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;case MvError.MV_E_VERSION: errorMsg += " Version mismatches "; break;case MvError.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;case MvError.MV_E_UNKNOW: errorMsg += " Unknown error "; break;case MvError.MV_E_GC_GENERIC: errorMsg += " General error "; break;case MvError.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;case MvError.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;case MvError.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;case MvError.MV_E_NETER: errorMsg += " Network error "; break;}MessageBox.Show(errorMsg, "PROMPT");}private void RefreshDeviceList(){//创建设备列表cbDeviceList.Items.Clear();int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);if (nRet != MvError.MV_OK){ShowErrorMsg("Enumerate devices fail !", nRet);return;}//在窗体列表中显示设备名for (int i = 0; i < deviceInfoList.Count; i++){IDeviceInfo deviceInfo = deviceInfoList[i];if (deviceInfo.UserDefinedName != ""){cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.UserDefinedName + " (" + deviceInfo.SerialNumber + ")");}else{cbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.ManufacturerName + " " + deviceInfo.ModelName + " (" + deviceInfo.SerialNumber + ")");}}//选择第一项if (deviceInfoList.Count != 0){cbDeviceList.SelectedIndex = 0;}}private void bnClose_Click(object sender, EventArgs e){//取流标志位清零if (isGrabbing == true){bnStopGrab_Click(sender, e);}//关闭设备if (device != null){device.Close();device.Dispose();}//控件操作SetCtrlWhenClose();}private void SetCtrlWhenClose(){bnOpen.Enabled = true;bnClose.Enabled = false;bnStartGrab.Enabled = false;bnStopGrab.Enabled = false;bnContinuesMode.Enabled = false;bnTriggerMode.Enabled = false;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;tbExposure.Enabled = false;tbGain.Enabled = false;tbFrameRate.Enabled = false;bnGetParam.Enabled = false;bnSetParam.Enabled = false;}private void bnEnum_Click(object sender, EventArgs e){RefreshDeviceList();}private void bnOpen_Click(object sender, EventArgs e){if (deviceInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1){ShowErrorMsg("No device, please select", 0);return;}//获取选择的设备信息IDeviceInfo deviceInfo = deviceInfoList[cbDeviceList.SelectedIndex];try{//打开设备device = DeviceFactory.CreateDevice(deviceInfo);}catch (Exception ex){MessageBox.Show("Create Device fail !" + ex.Message);return;}int result = device.Open();if (result != MvError.MV_OK){ShowErrorMsg("Open Device fail", result);return;}//判断是否为gige设备if (device is IGigEDevice){//转换为gige设备IGigEDevice gigEDevice = device as IGigEDevice;//探测网络最佳包大小int optionPacketSize;result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);if (result != MvError.MV_OK){ShowErrorMsg("Waring: Get packet Size failed !", result);}else{result = device.Parameters.SetIntValue("GevSCPSPPacketSize", (long)optionPacketSize);if (result != MvError.MV_OK){ShowErrorMsg("Waring: Set Packet Size failed", result);}}}//设置采集卡连续模式device.Parameters.SetEnumValueByString("AcauisitionMode", "Continuous");device.Parameters.SetEnumValueByString("TriggerMode", "Off");//关闭触发模式//控件操作SetCtrlWhenOpen();//获取参数bnGetParam_Click(null, null);}private void SetCtrlWhenOpen(){bnOpen.Enabled = false;bnClose.Enabled = true;bnStartGrab.Enabled = true;bnStopGrab.Enabled = false;bnContinuesMode.Enabled = true;bnContinuesMode.Checked = true;//bnContinuesMode_CheckedChanged(null,null);bnTriggerMode.Enabled = true;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;tbExposure.Enabled = true;tbGain.Enabled = true;tbFrameRate.Enabled = true;bnGetParam.Enabled = true;bnSetParam.Enabled = true;}private void GetTriggerMode(){IEnumValue enumValue;int result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);if (result == MvError.MV_OK){if (enumValue.CurEnumEntry.Symbolic == "On"){bnTriggerMode.Checked = true;bnContinuesMode.Checked = false;result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);if (result == MvError.MV_OK){if (enumValue.CurEnumEntry.Symbolic == "TriggerSoftware"){cbSoftTrigger.Enabled = true;cbSoftTrigger.Checked = true;if (isGrabbing){bnTriggerExec.Enabled = true;}}}}else{bnContinuesMode.Checked = true;bnTriggerMode.Checked = false;}}}private void bnGetParam_Click(object sender, EventArgs e){GetTriggerMode();IFloatValue floatValue;int result = device.Parameters.GetFloatValue("ExposureTime", out floatValue);if (result == MvError.MV_OK){tbExposure.Text = floatValue.CurValue.ToString("F1");}result = device.Parameters.GetFloatValue("Gain", out floatValue);if (result == MvError.MV_OK){tbGain.Text = floatValue.CurValue.ToString("F1");}result = device.Parameters.GetFloatValue("ResultingFrameRate", out floatValue);if (result == MvError.MV_OK){tbFrameRate.Text = floatValue.CurValue.ToString("F1");}IEnumValue enumValue;result = device.Parameters.GetEnumValue("PixelFormat", out enumValue);if (result == MvError.MV_OK){tbPixelFormat.Text = enumValue.CurEnumEntry.Symbolic;}}private void bnSetParam_Click(object sender, EventArgs e){try{float.Parse(tbExposure.Text);float.Parse(tbGain.Text);float.Parse(tbFrameRate.Text);}catch{ShowErrorMsg("Please enter correct type !", 0);return;}device.Parameters.SetEnumValue("ExposureAuto", 0);int result = device.Parameters.SetFloatValue("ExposureTime", float.Parse(tbExposure.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Gain Fail", result);}device.Parameters.SetEnumValue("GainAuto", 0);result = device.Parameters.SetFloatValue("Gain", float.Parse(tbGain.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Gain Fail !", result);}result = device.Parameters.SetBoolValue("AcquisitionFrameRateEnable", true);if (result != MvError.MV_OK){ShowErrorMsg("Set AcquisitionFrameRateEnable Fail !", result);}else{result = device.Parameters.SetFloatValue("AcquisitionFrameRate", float.Parse(tbFrameRate.Text));if (result != MvError.MV_OK){ShowErrorMsg("Set Frame Rate Fail !", result);}}}private void bnStopGrab_Click(object sender, EventArgs e){//标志位设为falseisGrabbing = false;receiveThread.Join();//停止采集int result = device.StreamGrabber.StopGrabbing();if (result != MvError.MV_OK){ShowErrorMsg("Stop Grabbing Fail !", result);}//控件操作SetCtrlWhenStopGrab();}private void SetCtrlWhenStopGrab(){bnStartGrab.Enabled = true;bnStopGrab.Enabled = false;cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;}private void bnTriggerExec_Click(object sender, EventArgs e){//触发命令int result = device.Parameters.SetCommandValue("TriggerSoftware");if (result != MvError.MV_OK){ShowErrorMsg("Trigger Software Fail !", result);}}private void cbSoftTrigger_CheckedChanged(object sender, EventArgs e){//触发源设为软触发if (cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Software");if (isGrabbing){bnTriggerExec.Enabled = true;}}if (!cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Line0");bnTriggerExec.Enabled = false;}}private void Form1_FormClosing(object sender, FormClosingEventArgs e){bnClose_Click(null, null);//反初始化SDKSystem.Finalize();}private void bnContinuesMode_CheckedChanged(object sender, EventArgs e){if (bnContinuesMode.Checked){device.Parameters.SetEnumValueByString("TriggerMode", "Off");cbSoftTrigger.Enabled = false;bnTriggerExec.Enabled = false;}}private void bnTriggerMode_CheckedChanged(object sender, EventArgs e){if (bnTriggerMode.Checked){//打开触发模式device.Parameters.SetEnumValueByString("TriggerMode", "On");if ((bool)cbSoftTrigger.Checked){device.Parameters.SetEnumValueByString("TriggerSource", "Software");if (isGrabbing){bnTriggerExec.Enabled = true;}}else{device.Parameters.SetEnumValueByString("TriggerSource", "Line0");}cbSoftTrigger.Enabled = true;cbSoftTrigger.Checked = true;}}public void ReciveThreadProcess(){IFrameOut frameOut = null;int result = MvError.MV_OK;while (isGrabbing){result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);if (result == MvError.MV_OK){device.ImageRender.DisplayOneFrame(pictureBoxHandle, frameOut.Image);device.StreamGrabber.FreeImageBuffer(frameOut);}}}public void ReciveThreadImage(){IFrameOut frameOut = null;int result = MvError.MV_OK;int windowWidth = hWindowControl1.Width;int windowHeight = hWindowControl1.Height;double windowAspect = (double)windowWidth / windowHeight;while (isGrabbing){result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);if (result == MvError.MV_OK){IImage image = frameOut.Image;int width = (int)image.Width;int height = (int)image.Height;double imageAspect = (double)width / height;int row1, col1, row2, col2;if (imageAspect > windowAspect){col1 = 0;col2 = width - 1;int newHeight = (int)(width / windowAspect);row1 = (width - newHeight) / 2;row2 = row1 + newHeight - 1;}else{row1 = 0;row2 = height - 1;int newWidth = (int)(height * windowAspect);col1 = (width - newWidth)/2;col2 = col1 + newWidth - 1;}hWindowControl1.HalconWindow.SetPart(row1, col1, row2, col2);IntPtr imagePtr = image.PixelDataPtr;Console.WriteLine(image.PixelType);if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_BayerBG8){HImage hImage = new HImage("byte",width,height,imagePtr);HObject rgbImage;HOperatorSet.CfaToRgb(hImage, out rgbImage, "bayer_bg", "bilinear");HOperatorSet.DispObj(rgbImage, hWindowControl1.HalconWindow);hImage.Dispose();rgbImage.Dispose();}}}}private void bnStartGrab_Click(object sender, EventArgs e){try{isGrabbing = true;pictureBoxHandle = displayArea.Handle;receiveThread = new Thread(ReciveThreadProcess);receiveThread.Start();receiveImage = new Thread(ReciveThreadImage);receiveImage.Start();}catch (Exception ex){MessageBox.Show("Start thread failed !" + ex.Message);return;}//开始采集int result = device.StreamGrabber.StartGrabbing();if (result != MvError.MV_OK){isGrabbing = false;receiveThread.Join();ShowErrorMsg("Start Grabbing Fail !", result);return;}SetCtrlWhenStartGrab();}private void SetCtrlWhenStartGrab(){bnStartGrab.Enabled = false;bnStopGrab.Enabled = true;if ((bool)bnTriggerMode.Checked){cbSoftTrigger.Enabled = true;if ((bool)cbSoftTrigger.Checked){bnTriggerExec.Enabled = true;}}}}
}


http://www.ppmy.cn/news/1543238.html

相关文章

说一说QWidget

目录 关于QWidget 作为界面组件时&#xff0c;你需要有印象的 1. 控制属性 2. 组件状态与交互属性 3. 外观和样式属性 4. 布局与子组件管理属性 5. 图标和光标属性 6. 大小策略属性 作为单独的窗体的属性 写Qt快两年了&#xff0c;也写过一些规模偏大的软件&#xff0c…

将.py文件生成.exe文件的方法

1、安装pyinstaller&#xff08;已有忽略&#xff09;&#xff1a;pip install pyinstaller 2、进入目标文件&#xff08;需要编译的文件&#xff09;目录 3、编译&#xff1a;pyinstaller --onefile xx.py 4、文件生成后的路径&#xff1a;在目标文件目录下创建一个名为dist的…

iOS 本地存储地址(位置)

前言: UserDefaults 存在沙盒的 Library --> Preferences--> .plist文件 CoreData 存在沙盒的 Library --> Application Support--> xx.sqlite 一个小型数据库里 (注:Application Support 这个文件夹已开始是没有的,只有当你写了存储代码,运行之后,目录里才会出…

ssm基于web的网络游戏交易平台信息管理系统的设计与实现+vue

系统包含&#xff1a;源码论文 所用技术&#xff1a;SpringBootVueSSMMybatisMysql 免费提供给大家参考或者学习&#xff0c;获取源码请私聊我 需要定制请私聊 目 录 目 录 III 第1章 绪论 1 1.1选题动因 1 1.2目的和意义 1 1.3论文结构安排 2 第2章 开发环境与技术 …

编程语言的设计模式

编程语言的设计模式是一种总结和抽象&#xff0c;帮助开发者应对常见的编程问题。以下是几种主要的设计模式&#xff1a; 1. 创建型模式 单例模式 (Singleton Pattern)&#xff1a;确保一个类只有一个实例&#xff0c;并提供一个全局访问点。工厂模式 (Factory Pattern)&…

Spring Boot框架中的IO

1. 文件资源的访问与管理 在 Spring Boot 中&#xff0c;资源文件的访问与管理是常见的操作需求&#xff0c;比如加载配置文件、读取静态文件或从外部文件系统读取文件。Spring 提供了多种方式来处理资源文件访问&#xff0c;包括通过 ResourceLoader、Value 注解以及 Applica…

怎么提取视频里的音频?关于提取视频里音频的几种方法

怎么提取视频里的音频&#xff1f;在数字媒体蓬勃发展的今天&#xff0c;视频已成为我们日常生活中不可或缺的一部分。从社交平台的短视频到在线视频课程&#xff0c;从音乐MV到电影片段&#xff0c;丰富多样的视频内容让我们随时随地享受到视听盛宴。然而&#xff0c;有时我们…

理解消息队列

消息队列&#xff08;Message Queue&#xff09;有下面四大作用&#xff1a; 解耦。几个业务系统之间可以通过 MQ 解耦&#xff0c;例如做数据同步数据的顺序性和可恢复性异步通讯缓冲能力 理解 MQ MQ 的前两个特点且不说&#xff0c;我们看看另外两个的。 异步通讯&#x…