通过百度网盘分享的文件:海康相机
链接:
提取码:1234
using MvCameraControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 相机取像_Winform_
{
public partial class Form1 : Form
{
readonly 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; // ch:是否正在取图 | en: Grabbing flag
bool isRecord = false; // ch:是否正在录像 | en: Video record flag
Thread receiveThread = null; // ch:接收图像线程 | en: Receive image thread
private IFrameOut frameForSave; // ch:获取到的帧信息, 用于保存图像 | en:Frame for save image
private readonly object saveImageLock = new object();
public Form1()
{
InitializeComponent();
// 重要允许跨线程访问
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 1.查找相机设备
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
RefreshDeviceList();
}
private void RefreshDeviceList()
{
// ch:创建设备列表 | en:Create Device List
cbDeviceList.Items.Clear();
int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
if (nRet != MvError.MV_OK)
{
MessageBox.Show("Enumerate devices fail!"+nRet);
return;
}
// ch:在窗体列表中显示设备名 | en:Display device name in the form list
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 + ")");
}
}
// ch:选择第一项 | en:Select the first item
if (deviceInfoList.Count != 0)
{
cbDeviceList.SelectedIndex = 0;
}
}
/// <summary>
/// 打开相机
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (deviceInfoList.Count == 0 || cbDeviceList.SelectedIndex == -1)
{
MessageBox.Show("No device, please select"+ 0);
return;
}
// ch:获取选择的设备信息 | en:Get selected device information
IDeviceInfo deviceInfo = deviceInfoList[cbDeviceList.SelectedIndex];
/*
* 重要
*/
try
{
// ch:打开设备 | en:Open device
device = DeviceFactory.CreateDevice(deviceInfo);
}
catch (Exception ex)
{
MessageBox.Show("Create Device fail!" + ex.Message);
return;
}
int result = device.Open();
if (result != MvError.MV_OK)
{
MessageBox.Show("Open Device fail!"+ result);
return;
}
//ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
if (device is IGigEDevice)
{
//ch: 转换为gigE设备 | en: Convert to Gige device
IGigEDevice gigEDevice = device as IGigEDevice;
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int optionPacketSize;
result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
if (result != MvError.MV_OK)
{
MessageBox.Show("Warning: Get Packet Size failed!"+ result);
}
else
{
result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
if (result != MvError.MV_OK)
{
MessageBox.Show("Warning: Set Packet Size failed!"+ result);
}
}
}
// ch:设置采集连续模式 | en:Set Continues Aquisition Mode
// 连续采图模式
device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
// 关闭触发模式
device.Parameters.SetEnumValueByString("TriggerMode", "Off");
// ch:控件操作 | en:Control operation
// ch:获取参数 | en:Get parameters
GetParam_Click();
}
private void GetParam_Click()
{
GetTriggerMode();
IFloatValue floatValue;
int result = device.Parameters.GetFloatValue("ExposureTime", out floatValue);
if (result == MvError.MV_OK)
{
MessageBox.Show("ExposureTime" + floatValue.CurValue.ToString("F1"));
}
result = device.Parameters.GetFloatValue("Gain", out floatValue);
if (result == MvError.MV_OK)
{
MessageBox.Show("Gain" + floatValue.CurValue.ToString("F1"));
}
result = device.Parameters.GetFloatValue("ResultingFrameRate", out floatValue);
if (result == MvError.MV_OK)
{
MessageBox.Show("ResultingFrameRate" + floatValue.CurValue.ToString("F1"));
}
}
/// <summary>
/// ch:获取触发模式 | en:Get Trigger Mode
/// </summary>
private void GetTriggerMode()
{
IEnumValue enumValue;
int result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);
if (result == MvError.MV_OK)
{
if (enumValue.CurEnumEntry.Symbolic == "On")
{
result = device.Parameters.GetEnumValue("TriggerSource", out enumValue);
if (result == MvError.MV_OK)
{
if (enumValue.CurEnumEntry.Symbolic == "TriggerSoftware")
{
}
}
}
else
{
}
}
}
/// <summary>
/// 设置参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
device.Parameters.SetEnumValue("ExposureAuto", 0);
int result = device.Parameters.SetFloatValue("ExposureTime", 1000);
if (result != MvError.MV_OK)
{
MessageBox.Show("Set Exposure Time Fail!"+ result);
}
device.Parameters.SetEnumValue("GainAuto", 0);
result = device.Parameters.SetFloatValue("Gain", 3);
if (result != MvError.MV_OK)
{
MessageBox.Show("Set Gain Fail!"+result);
}
}
/// <summary>
/// 取像
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
try
{
// ch:标志位置位true | en:Set position bit true
// 采图标志位
isGrabbing = true;
/*
* 重要
*/
receiveThread = new Thread(ReceiveThreadProcess);
receiveThread.Start();
}
catch (Exception ex)
{
MessageBox.Show("Start thread failed!, " + ex.Message);
throw;
}
// ch:开始采集 | en:Start Grabbing
int result = device.StreamGrabber.StartGrabbing();
if (result != MvError.MV_OK)
{
isGrabbing = false;
receiveThread.Join();
MessageBox.Show("Start Grabbing Fail!"+result);
return;
}
}
/// <summary>
/// 取像线程(最重要的地方)
/// </summary>
public void ReceiveThreadProcess()
{
int nRet;
Graphics graphics; // ch:使用GDI在pictureBox上绘制图像 | en:Display frame using a graphics
while (isGrabbing)
{
IFrameOut frameOut;
nRet = device.StreamGrabber.GetImageBuffer(1000, out frameOut);
if (MvError.MV_OK == nRet)
{
if (isRecord)
{
device.VideoRecorder.InputOneFrame(frameOut.Image);
}
lock (saveImageLock)
{
frameForSave = frameOut.Clone() as IFrameOut;
}
#if !GDI_RENDER
/*
* 重要
*/
device.ImageRender.DisplayOneFrame(pictureBox1.Handle, frameOut.Image);
#else
// 使用GDI绘制图像
try
{
using (Bitmap bitmap = frameOut.Image.ToBitmap())
{
if (graphics == null)
{
graphics = pictureBox1.CreateGraphics();
}
Rectangle srcRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
Rectangle dstRect = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
graphics.DrawImage(bitmap, dstRect, srcRect, GraphicsUnit.Pixel);
}
}
catch (Exception e)
{
device.StreamGrabber.FreeImageBuffer(frameOut);
MessageBox.Show(e.Message);
return;
}
#endif
device.StreamGrabber.FreeImageBuffer(frameOut);
}
else
{
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// ch:取流标志位清零 | en:Reset flow flag bit
//if (isGrabbing == true)
//{
// if (isRecord)
// {
// if (false == isGrabbing)
// {
// ShowErrorMsg("Not Start Grabbing", 0);
// return;
// }
// int result = device.VideoRecorder.StopRecord();
// if (result != MvError.MV_OK)
// {
// ShowErrorMsg("Stop Record Fail!", result);
// }
// isRecord = false;
// }
// // ch:标志位设为false | en:Set flag bit false
// isGrabbing = false;
// receiveThread.Join();
// // ch:停止采集 | en:Stop Grabbing
// int result = device.StreamGrabber.StopGrabbing();
// if (result != MvError.MV_OK)
// {
// ShowErrorMsg("Stop Grabbing Fail!", result);
// }
//}
// ch:关闭设备 | en:Close Device
if (device != null)
{
device.Close();
device.Dispose();
}
}
private void button7_Click(object sender, EventArgs e)
{
// ch:停止采集 | en:Stop Grabbing
int result = device.StreamGrabber.StopGrabbing();
if (result != MvError.MV_OK)
{
MessageBox.Show("Stop Grabbing Fail!"+result);
}
// ch:关闭设备 | en:Close Device
if (device != null)
{
device.Close();
device.Dispose();
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 保存图像
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button6_Click(object sender, EventArgs e)
{
int result;
try
{
ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
imageFormatInfo.FormatType = ImageFormatType.Bmp;
result = SaveImage(imageFormatInfo);
if (result != MvError.MV_OK)
{
MessageBox.Show("Save Image Fail!"+result);
return;
}
else
{
MessageBox.Show("Save Image Succeed!"+ 0);
}
}
catch (Exception ex)
{
MessageBox.Show("Save Image Failed, " + ex.Message);
return;
}
}
private int SaveImage(ImageFormatInfo imageFormatInfo)
{
if (frameForSave == null)
{
throw new Exception("No vaild image");
}
string imagePath = "Image_w" + frameForSave.Image.Width.ToString() + "_h" + frameForSave.Image.Height.ToString() + "_fn" + frameForSave.FrameNum.ToString() + "." + imageFormatInfo.FormatType.ToString();
lock (saveImageLock)
{
return device.ImageSaver.SaveImageToFile(imagePath, frameForSave.Image, imageFormatInfo, CFAMethod.Equilibrated);
}
}
}
}
using MvCameraControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 相机取像_Winform_
{
public partial class Form2 : Form
{
readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;
IDevice device = null;
List<IDeviceInfo> deviceInfos = new List<IDeviceInfo>();
bool isGrabbing = false;
Thread receiveThread = null;
// ch:用于从驱动获取到的帧信息 | en:Frame info that getting image from driver
IFrameOut frameForSave = null;
private readonly Object lockForSaveImage = new Object();
IEnumValue triggerSelector = null; // 触发选项
IEnumValue triggerMode = null; // 触发模式
IEnumValue triggerSource = null; // 触发源
IEnumValue pixelFormat = null; // 像素格式
IEnumValue imgCompressMode = null; // HB模式
IEnumValue preampGain = null; // 模拟增益
public Form2()
{
InitializeComponent();
// 允许跨线程访问控件
CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 搜索相机
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
UpdateDeviceList();
}
/// <summary>
/// ch:刷新设备列表 | en:Update devices list
/// </summary>
private void UpdateDeviceList()
{
// ch:枚举设备列表 | en:Enumerate Device List
cmbDeviceList.Items.Clear();
int result = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfos);
if (result != MvError.MV_OK)
{
MessageBox.Show("Enumerate devices fail!"+result);
return;
}
// ch:在窗体列表中显示设备名 | en:Display device name in the form list
for (int i = 0; i < deviceInfos.Count; i++)
{
IDeviceInfo deviceInfo = deviceInfos[i];
if (deviceInfo.UserDefinedName != "")
{
cmbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.UserDefinedName + " (" + deviceInfo.SerialNumber + ")");
}
else
{
cmbDeviceList.Items.Add(deviceInfo.TLayerType.ToString() + ": " + deviceInfo.ManufacturerName + " " + deviceInfo.ModelName + " (" + deviceInfo.SerialNumber + ")");
}
}
// ch:选择第一项 | en:Select the first item
if (deviceInfos.Count > 0)
{
cmbDeviceList.SelectedIndex = 0;
}
else
{
MessageBox.Show("No device"+ 0);
}
return;
}
/// <summary>
/// 打开相机
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (0 == deviceInfos.Count || -1 == cmbDeviceList.SelectedIndex)
{
MessageBox.Show("No device, please enumerate device"+0);
return;
}
// ch:获取选择的设备信息 | en:Get selected device information
IDeviceInfo deviceInfo = deviceInfos[cmbDeviceList.SelectedIndex];
try
{
// ch:打开设备 | en:Open device
/**
*
* 重要
*
* **/
device = DeviceFactory.CreateDevice(deviceInfo);
}
catch (Exception ex)
{
MessageBox.Show("Create Device fail!" + ex.Message);
return;
}
int result = device.Open();
if (result != MvError.MV_OK)
{
device.Dispose();
device = null;
MessageBox.Show("Open Device fail!"+result);
return;
}
//ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
if (device is IGigEDevice)
{
//ch: 转换为gigE设备 | en: Convert to Gige device
IGigEDevice gigEDevice = device as IGigEDevice;
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
int optionPacketSize;
result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
if (result != MvError.MV_OK)
{
MessageBox.Show("Warning: Get Packet Size failed!"+ result);
}
else
{
result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
if (result != MvError.MV_OK)
{
MessageBox.Show("Warning: Set Packet Size failed!"+result);
}
}
}
// ch:设置采集连续模式 | en:Set Continues Aquisition Mode
/*
* 重要
*/
device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
device.Parameters.SetEnumValueByString("TriggerMode", "Off");
// ch:获取参数 | en:Get parameters
//GetImageCompressionMode();
//GetPreampGain();
//GetTriggerMode();
//GetTriggerSelector();
//GetTriggerSource();
//GetPixelFormat();
GetParam_Click();
}
private void GetParam_Click()
{
// ch:获取曝光参数 | en:Get ExposureTime
IFloatValue exposureTime = null;
int result = device.Parameters.GetFloatValue("ExposureTime", out exposureTime);
if (result == MvError.MV_OK)
{
MessageBox.Show("获取曝光参数" + exposureTime.CurValue.ToString("F2"));
}
// ch:获取数字增益参数 | en:Get DigitalShift
IFloatValue digitalShift = null;
result = device.Parameters.GetFloatValue("DigitalShift", out digitalShift);
if (result == MvError.MV_OK)
{
MessageBox.Show("获取数字增益参数" + digitalShift.CurValue.ToString("F2"));
}
// ch:获取行频使能开关 | en:Get AcquisitionLineRateEnable
bool acqLineRateEnable = false;
result = device.Parameters.GetBoolValue("AcquisitionLineRateEnable", out acqLineRateEnable);
if (result == MvError.MV_OK)
{
MessageBox.Show("获取行频使能开关" + acqLineRateEnable.ToString());
}
// ch:获取行频设置值 | en:Get AcquisitionLineRate
IIntValue acqLineRate = null;
result = device.Parameters.GetIntValue("AcquisitionLineRate", out acqLineRate);
if (result == MvError.MV_OK)
{
MessageBox.Show("获取行频设置值" + acqLineRate.CurValue.ToString());
}
// ch:获取行频实际值 | en:Get ResultingLineRate
IIntValue resultLineRate = null;
result = device.Parameters.GetIntValue("ResultingLineRate", out resultLineRate);
if (result == MvError.MV_OK)
{
MessageBox.Show("获取行频设置值" + resultLineRate.CurValue.ToString());
}
}
/// <summary>
/// 设置相机参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 取像
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
// ch:标志位置位 true | en:Set position bit true
isGrabbing = true;
receiveThread = new Thread(ReceiveThreadProcess);
receiveThread.Start();
// ch:开始采集 | en:Start Grabbing
int result = device.StreamGrabber.StartGrabbing();
if (result != MvError.MV_OK)
{
isGrabbing = false;
receiveThread.Join();
MessageBox.Show("Start Grabbing Fail!"+result);
return;
}
}
/// <summary>
/// ch:接收图像线程 | en:Receive image thread process
/// </summary>
public void ReceiveThreadProcess()
{
IFrameOut frameOut = null;
int result = MvError.MV_OK;
while (isGrabbing)
{
result = device.StreamGrabber.GetImageBuffer(1000, out frameOut);
if (result == MvError.MV_OK)
{
// ch:保存图像数据用于保存图像文件 | en:Save frame info for save image
lock (lockForSaveImage)
{
frameForSave = frameOut.Clone() as IFrameOut;
}
// ch:渲染图像数据 | en:Display frame
device.ImageRender.DisplayOneFrame(pictureBox1.Handle, frameOut.Image);
// ch:释放帧信息 | en:Free frame info
device.StreamGrabber.FreeImageBuffer(frameOut);
}
else
{
}
}
}
private void button6_Click(object sender, EventArgs e)
{
int result;
try
{
ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
imageFormatInfo.FormatType = ImageFormatType.Bmp;
result = SaveImage(imageFormatInfo);
if (result != MvError.MV_OK)
{
MessageBox.Show("Save Image Fail!"+result);
return;
}
else
{
MessageBox.Show("Save Image Succeed!"+0);
}
}
catch (Exception ex)
{
MessageBox.Show("Save Image Failed, " + ex.Message);
return;
}
}
/// <summary>
/// ch:保存图像 | en:Save image
/// </summary>
/// <param name="imageFormatInfo">ch:图像格式信息 | en:Image format info </param>
/// <returns></returns>
private int SaveImage(ImageFormatInfo imageFormatInfo)
{
if (frameForSave == null)
{
throw new Exception("No vaild image");
}
string imagePath = "Image_w" + frameForSave.Image.Width.ToString() + "_h" + frameForSave.Image.Height.ToString() + "_fn" + frameForSave.FrameNum.ToString() + "." + imageFormatInfo.FormatType.ToString();
lock (lockForSaveImage)
{
return device.ImageSaver.SaveImageToFile(imagePath, frameForSave.Image, imageFormatInfo, CFAMethod.Equilibrated);
}
}
private void button7_Click(object sender, EventArgs e)
{
// ch:停止采集 | en:Stop Grabbing
int result = device.StreamGrabber.StopGrabbing();
if (result != MvError.MV_OK)
{
MessageBox.Show("Stop Grabbing Fail!"+result);
}
// ch:取流标志位清零 | en:Reset flow flag bit
if (isGrabbing == true)
{
isGrabbing = false;
receiveThread.Join();
}
// ch:关闭设备 | en:Close Device
if (device != null)
{
device.Close();
device.Dispose();
}
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容