466 lines
18 KiB
C#
466 lines
18 KiB
C#
using MvCameraControl;
|
||
using OpenCvSharp;
|
||
using System.Threading;
|
||
using System.Windows;
|
||
|
||
namespace PLCSharp.VVMs.Vision.Camera
|
||
{
|
||
/// <summary>
|
||
/// Hik相机
|
||
/// </summary>
|
||
public class HikCamera : CameraBase
|
||
{
|
||
/// <summary>
|
||
/// 相机
|
||
/// </summary>
|
||
public IDevice Camera { get; set; }
|
||
|
||
/// <summary>
|
||
/// Device信息
|
||
/// </summary>
|
||
public IDeviceInfo DeviceInfo { get; set; }
|
||
|
||
//private bool continuousAquisition = false;
|
||
|
||
private bool inited;
|
||
|
||
/// <summary>
|
||
/// 设置ExposureTime
|
||
/// </summary>
|
||
/// <returns>返回布尔值</returns>
|
||
public override bool SetExposureTime()
|
||
{
|
||
var nRet = Camera.Parameters.SetFloatValue("ExposureTime", (float)Params.ExposureTime);
|
||
if (nRet != MvError.MV_OK)
|
||
{
|
||
Log(ShowErrorMsg(nRet));
|
||
return false;
|
||
}
|
||
else
|
||
{
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置TriggerSource
|
||
/// </summary>
|
||
/// <returns>返回布尔值</returns>
|
||
public override bool SetTriggerSource()
|
||
{
|
||
var nRet = Camera.Parameters.SetEnumValue("TriggerSource", (uint)Params.TriggerSource);
|
||
|
||
if (nRet != MvError.MV_OK)
|
||
{
|
||
Log(ShowErrorMsg(nRet));
|
||
return false;
|
||
}
|
||
else
|
||
{
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 打开
|
||
/// </summary>
|
||
/// <returns>返回布尔值</returns>
|
||
public override bool Open()
|
||
{
|
||
if (inited)
|
||
{
|
||
SetExposureTime();
|
||
return true;
|
||
}
|
||
|
||
if (DeviceInfo == null) return false;
|
||
//ch: 创建设备 | en: Create device
|
||
Camera = DeviceFactory.CreateDevice(DeviceInfo);
|
||
// ch:打开设备 | en:Open device
|
||
int nRet = Camera.Open();
|
||
|
||
if (nRet != MvError.MV_OK)
|
||
{
|
||
Log(ShowErrorMsg(nRet));
|
||
Camera.Close();
|
||
return false;
|
||
}
|
||
else
|
||
{
|
||
// ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
|
||
|
||
|
||
int result;
|
||
if (Camera is IGigEDevice gigEDevice)
|
||
{
|
||
result = gigEDevice.GetOptimalPacketSize(out int optionPacketSize);
|
||
if (result != MvError.MV_OK)
|
||
{
|
||
ShowErrorMsg(result, "Warning: Get Packet Size failed!");
|
||
}
|
||
else
|
||
{
|
||
result = Camera.Parameters.SetIntValue("GevSCPSPacketSize", optionPacketSize);
|
||
if (result != MvError.MV_OK)
|
||
{
|
||
ShowErrorMsg(result, "Warning: Set Packet Size failed!");
|
||
}
|
||
}
|
||
}
|
||
|
||
_ = Camera.Parameters.GetIntValue("OffsetX", out IIntValue OffsetX);
|
||
_ = Camera.Parameters.GetIntValue("OffsetY", out IIntValue OffsetY);
|
||
_ = Camera.Parameters.GetIntValue("Width", out IIntValue Windth);
|
||
_ = Camera.Parameters.GetIntValue("Height", out IIntValue Height);
|
||
|
||
int offsetX = (int)OffsetX.CurValue;
|
||
int offsetY = (int)OffsetY.CurValue;
|
||
|
||
var width = (int)Windth.Max + offsetX;
|
||
var height = (int)Height.Max + offsetY;
|
||
|
||
FullRect = new(0, 0, width, height);
|
||
|
||
GetMinMaxExposureTime();
|
||
result = Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
|
||
|
||
result = Camera.Parameters.SetEnumValue("TriggerSource", (uint)Params.TriggerSource);
|
||
|
||
result = Camera.StreamGrabber.StartGrabbing();
|
||
if (result != MvError.MV_OK)
|
||
{
|
||
receiveThread?.Join();
|
||
Log(ShowErrorMsg(result, "Start Grabbing Fail!"));
|
||
return false;
|
||
}
|
||
// ch:开始采集 | en:Start Grabbing
|
||
try
|
||
{
|
||
receiveThread = new Thread(ReceiveThreadProcess)
|
||
{
|
||
IsBackground = true
|
||
};
|
||
receiveThread.Start();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show("Start thread failed!, " + ex.Message);
|
||
return false;
|
||
}
|
||
SetExposureTime();
|
||
inited = true;
|
||
return true;
|
||
}
|
||
}
|
||
|
||
private IFrameOut frameOut = null;
|
||
private Thread receiveThread = null; // ch:接收图像线程 | en: Receive image thread
|
||
private long _frameVersion; // 成功更新 Mat 的帧计数(Interlocked 原子访问)
|
||
private long _trigVersion; // 最近一次触发时的帧版本(Interlocked 原子访问)
|
||
|
||
/// <summary>
|
||
/// 接收Thread过程
|
||
/// </summary>
|
||
public void ReceiveThreadProcess()
|
||
{
|
||
while (true)
|
||
{
|
||
try
|
||
{
|
||
int result = Camera.StreamGrabber.GetImageBuffer(1000, out frameOut);
|
||
if (result == MvError.MV_OK)
|
||
{
|
||
try
|
||
{
|
||
var w = (int)frameOut.Image.Width;
|
||
var h = (int)frameOut.Image.Height;
|
||
|
||
if (frameOut.Image.PixelType == MvGvspPixelType.PixelType_Gvsp_Mono8)
|
||
{
|
||
// FromPixelData 是零拷贝浅包装,必须深拷贝后再释放 SDK 缓冲区,否则 Mat 数据悬空(use-after-free)
|
||
using var wrap = Mat.FromPixelData(h, w, MatType.CV_8U, frameOut.Image.PixelDataPtr);
|
||
Mat = wrap.Clone();
|
||
Interlocked.Increment(ref _frameVersion); // 仅在实际更新 Mat 后递增版本
|
||
}
|
||
else
|
||
{
|
||
// 其它格式(Bayer8/10/12、YUV422、RGB8、Mono10/12 等)每像素字节数与
|
||
// CV_8UC3/CV_8U 不匹配,直接浅包装会在 Clone 时越界读取 → 原生访问冲突,
|
||
// 进程直接退出、无托管异常可捕获(曾崩于 BayerRG8 + CV_8UC3)。
|
||
// 统一交给 SDK PixelTypeConverter 转成 BGR8,Bayer 插值由官方算法完成。
|
||
int cvRet = Camera.PixelTypeConverter.ConvertPixelType(
|
||
frameOut.Image, out var converted, MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
|
||
if (cvRet == MvError.MV_OK && converted != null)
|
||
{
|
||
using (converted) // 输出图像用完必须 Dispose,否则内存上涨
|
||
{
|
||
using var wrap = Mat.FromPixelData(
|
||
(int)converted.Height, (int)converted.Width,
|
||
MatType.CV_8UC3, converted.PixelDataPtr);
|
||
Mat = wrap.Clone();
|
||
Interlocked.Increment(ref _frameVersion); // 仅在实际更新 Mat 后递增版本
|
||
}
|
||
}
|
||
else
|
||
{
|
||
// 转换失败保留上一帧 Mat,不退出采集线程
|
||
System.Diagnostics.Debug.WriteLine($"[HikCamera] 像素转换失败: {cvRet}");
|
||
}
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
// 无论深拷贝成功与否都必须归还 SDK 缓冲区,否则 SDK 缓冲池耗尽
|
||
Camera.StreamGrabber.FreeImageBuffer(frameOut);
|
||
}
|
||
_imageReadyEvent.Set();
|
||
}
|
||
else
|
||
{
|
||
Thread.Sleep(1);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// 单帧处理异常不能杀死采集线程,否则拍照会永久超时
|
||
System.Diagnostics.Debug.WriteLine($"[HikCamera] 采集异常: {ex.Message}");
|
||
Thread.Sleep(10);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// SoftwareTrig
|
||
/// </summary>
|
||
public override void SoftwareTrig()
|
||
{
|
||
if (Open() == false) return;
|
||
// 清残留信号 + 记录触发时帧版本:保证后续 WaitOne 等到的是本次触发后的新帧,
|
||
// 而不是上一轮超时残留的信号(否则 WaitOne 会立即返回旧帧)
|
||
_imageReadyEvent.Reset();
|
||
_trigVersion = Interlocked.Read(ref _frameVersion);
|
||
_ = Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
|
||
_ = Camera.Parameters.SetEnumValue("TriggerSource", (uint)TriggerMethod.Software);
|
||
|
||
// ch:触发命令 | en:Trigger command
|
||
int result = Camera.Parameters.SetCommandValue("TriggerSoftware");
|
||
if (result != MvError.MV_OK)
|
||
{
|
||
ShowErrorMsg(result, "Trigger Software Fail!");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Trig
|
||
/// </summary>
|
||
public override void Trig()
|
||
{
|
||
if (Open() == false) return;
|
||
// 清残留信号 + 记录触发时帧版本:保证后续 WaitOne 等到的是本次触发后的新帧
|
||
_imageReadyEvent.Reset();
|
||
_trigVersion = Interlocked.Read(ref _frameVersion);
|
||
_ = Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
|
||
|
||
_ = Camera.Parameters.SetEnumValue("TriggerSource", (uint)Params.TriggerSource);
|
||
|
||
if (Params.TriggerSource == TriggerMethod.Software)
|
||
// ch:触发命令 | en:Trigger command
|
||
{
|
||
int result = Camera.Parameters.SetCommandValue("TriggerSoftware");
|
||
if (result != MvError.MV_OK)
|
||
{
|
||
ShowErrorMsg(result, "Trigger Software Fail!");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Continuous
|
||
/// </summary>
|
||
public override void Continuous()
|
||
{
|
||
if (Open() == false) return;
|
||
// ch:设置采集连续模式 | en:Set Continues Aquisition Mode
|
||
Camera.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
|
||
Camera.Parameters.SetEnumValueByString("TriggerMode", "Off");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 停止Continuous
|
||
/// </summary>
|
||
public override void StopContinuous()
|
||
{
|
||
if (inited == false) return;
|
||
|
||
Camera.Parameters.SetEnumValueByString("TriggerMode", "On");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 关闭
|
||
/// </summary>
|
||
public override void Close()
|
||
{
|
||
// ch:停止抓图 | en:Stop grab image
|
||
_ = Camera?.StreamGrabber.StopGrabbing();
|
||
// ch:关闭设备 | en:Close device
|
||
_ = Camera?.Close();
|
||
// ch:销毁设备 | en:Destroy device
|
||
Camera?.Dispose();
|
||
}
|
||
|
||
#region
|
||
|
||
/// <summary>
|
||
/// 获取最小最大曝光时间
|
||
/// </summary>
|
||
/// <summary>
|
||
/// 获取最小最大ExposureTime
|
||
/// </summary>
|
||
public void GetMinMaxExposureTime()
|
||
{
|
||
if (Camera == null) return;
|
||
Camera.Parameters.GetFloatValue("ExposureTime", out IFloatValue floatValue);
|
||
Params.MinExposureTime = floatValue.Min;
|
||
Params.MaxExposureTime = floatValue.Max > 2_000_000 ? 2_000_000 : floatValue.Max;
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region ROI
|
||
|
||
//为了加快拍照速度,这里做了一个取AOI的功能,如果每次都是取固定的AOI,建议使用此功能,如果每次的AOI不同,还是全部取回再截取,因为切换AOI需要时间。
|
||
/// <summary>
|
||
/// 矩形Seting
|
||
/// </summary>
|
||
public OpenCvSharp.Rect RectSeting { get; set; }
|
||
|
||
private OpenCvSharp.Rect FullRect;
|
||
private OpenCvSharp.Rect RectLast;
|
||
private OpenCvSharp.Rect ROIRectFomat;
|
||
|
||
private void FomatROI()
|
||
{
|
||
_ = Camera.Parameters.GetIntValue("OffsetX", out IIntValue OffsetX);
|
||
_ = Camera.Parameters.GetIntValue("OffsetY", out IIntValue OffsetY);
|
||
_ = Camera.Parameters.GetIntValue("Width", out IIntValue Windth);
|
||
_ = Camera.Parameters.GetIntValue("Height", out IIntValue Height);
|
||
|
||
ROIRectFomat.X = RectLast.X - RectLast.X % (int)OffsetX.CurValue;
|
||
ROIRectFomat.Y = RectLast.Y - RectLast.Y % (int)OffsetY.CurValue;
|
||
ROIRectFomat.Width = RectLast.Width - RectLast.Width % (int)Windth.CurValue;
|
||
ROIRectFomat.Height = RectLast.Height - RectLast.Height % (int)Height.CurValue;
|
||
ROIRectFomat.Width = ROIRectFomat.Width < 32 ? 32 : ROIRectFomat.Width;
|
||
ROIRectFomat.Height = ROIRectFomat.Height < 32 ? 32 : ROIRectFomat.Height;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置ROI
|
||
/// </summary>
|
||
public void SetROI()
|
||
{
|
||
if (RectSeting.Width == 0)
|
||
{
|
||
RectSeting = FullRect;
|
||
}
|
||
|
||
if (RectLast != RectSeting)
|
||
{
|
||
RectLast = RectSeting;
|
||
FomatROI();
|
||
_ = Camera.StreamGrabber.StopGrabbing();
|
||
_ = Camera.Parameters.SetIntValue("Width", 32);
|
||
_ = Camera.Parameters.SetIntValue("Height", 32);
|
||
_ = Camera.Parameters.SetIntValue("OffsetX", (uint)ROIRectFomat.Left);
|
||
_ = Camera.Parameters.SetIntValue("OffsetY", (uint)ROIRectFomat.Top);
|
||
_ = Camera.Parameters.SetIntValue("Height", 32);
|
||
_ = Camera.Parameters.SetIntValue("Width", (int)ROIRectFomat.Width);
|
||
_ = Camera.Parameters.SetIntValue("Height", (int)ROIRectFomat.Height);
|
||
_ = Camera.StreamGrabber.StartGrabbing();
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// WaitOne
|
||
/// </summary>
|
||
/// <param name="timeout">超时时间</param>
|
||
/// <returns>返回布尔值</returns>
|
||
public override bool WaitOne(int timeout)
|
||
{
|
||
// 帧版本校验:AutoResetEvent 的 Set 在无等待者时会残留信号,导致下次 WaitOne
|
||
// 立即返回旧帧。这里等待到"帧版本超过触发时记录的版本"才返回 true——
|
||
// 残留信号不会递增版本,会被跳过继续等待,直到真正的新帧或超时。
|
||
long target = Interlocked.Read(ref _trigVersion);
|
||
var deadline = Environment.TickCount64 + timeout;
|
||
while (true)
|
||
{
|
||
if (Interlocked.Read(ref _frameVersion) > target)
|
||
{
|
||
return true;
|
||
}
|
||
long remain = deadline - Environment.TickCount64;
|
||
if (remain <= 0)
|
||
{
|
||
return false;
|
||
}
|
||
_imageReadyEvent.WaitOne((int)Math.Min(200L, remain));
|
||
}
|
||
}
|
||
|
||
#region SDK
|
||
|
||
private static string ShowErrorMsg(int errorCode, string message = "")
|
||
{
|
||
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;
|
||
}
|
||
|
||
return errorMsg;
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
} |