| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021 |
- using Cognex.VisionPro;
- using Microsoft.Win32;
- using netDxf.Entities;
- using NPOI.POIFS.Crypt.Dsig;
- using NPOI.SS.Formula;
- using NPOI.SS.Formula.Eval;
- using SciCamera.Net;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web.Configuration;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Interfaces;
- using TeamAAS_VP.Models;
- namespace TeamAAS_VP.Core.Cameras
- {
- public class OptCamera : ICamera, INotifyPropertyChanged
- {
- #region 字段
- private Thread m_hReceiveThread;
- // 用于序列化对同一相机实例的操作,防止同一实例被并发操作
- //private readonly SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
- // 用于保护状态变量(例如 IsGrabbing)的并发访问
- private readonly object _stateLock = new object();
- private TaskCompletionSource<ICogImage> _tcs;
- #endregion
- #region 属性
- public CameraBrand CameraBrand { get => CameraBrand.Opt; }
- public string Name { get; private set; }
- public Guid ID { get; private set; }
- public int Index { get; set; }
- public string ManufacturerName { get; private set; }
- public bool IsFindByIp { get; private set; }
- public string ModelName { get; private set; }
- public string SerialNumber { get; private set; }
- public string CameraIp { get; private set; }
- public CameraType CameraType { get; private set; }
- SciCam mvCameraAcq;
- public SciCam.SCI_DEVICE_INFO CameraInfo { get; private set; }
- public UInt32 ImageWidth { get; private set; }
- public UInt32 ImageHeight { get; private set; }
- public SciCam.SciCamPixelType PixelType { get; private set; }
- private bool _IsGrabbing;
- /// <summary>
- /// 正在采集
- /// </summary>
- public bool IsGrabbing
- {
- get { return _IsGrabbing; }
- private set { SetProperty(ref _IsGrabbing, value); }
- }
- private ICogImage _Image;
- public ICogImage Image
- {
- get { return _Image; }
- private set { SetProperty(ref _Image, value); }
- }
- public bool IsConnected { get; private set; }
- private bool IsHaveCamera = false;
- /// <summary>
- /// 采集用时
- /// </summary>
- public TimeSpan TotalTime { get; private set; }
- /// <summary>
- /// 错误信息
- /// </summary>
- public string ErrorMessage { get; private set; }
- //当前的图像采集模式
- public SciCam.SciCamGrabStrategy CurrentGrabStrategy { get; private set; } = SciCam.SciCamGrabStrategy.SciCam_GrabStrategy_Latest;
- #endregion
- #region 事件
- public event Action<ICogImage, TimeSpan, string> ImageCallbackEvent;
- public event Action<Guid, bool> CameraConnectChangedEvent;
- #endregion
- public OptCamera(Guid id, int index, string name, string serialNumber, string cameraip, bool isFindByIp)
- {
- ID = id;
- Name = serialNumber;
- Index = index;
- CameraIp = cameraip;
- SerialNumber = serialNumber;
- IsFindByIp = isFindByIp;
- mvCameraAcq = new SciCam();
- SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
- uint nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return;
- }
- for (int i = 0; i < stDeviceList.count; i++)
- {
- SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
- SciCam.SciCamTLType devTlType = device.tlType;
- if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
- {
- SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
- uint ip1 = gigeDevInfo.ip;
- int nIp1 = (int)(ip1 & 0x000000ff);
- int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
- int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
- int nIp4 = (int)((ip1 & 0xff000000) >> 24);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- if (IsFindByIp)
- {
- if (CameraIp == ip)
- {
- ManufacturerName = gigeDevInfo.manufactureName;
- ModelName = gigeDevInfo.modelName;
- SerialNumber = gigeDevInfo.serialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- else
- {
- if (string.Equals(gigeDevInfo.serialNumber, serialNumber))
- {
- ManufacturerName = gigeDevInfo.manufactureName;
- ModelName = gigeDevInfo.modelName;
- SerialNumber = gigeDevInfo.serialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- }
- IsConnected = false;
- }
- #region 方法
- /// <summary>
- /// 获取设备
- /// </summary>
- /// <returns></returns>
- public static CameraInfo[] GetDevices()
- {
- List<CameraInfo> cameras = new List<CameraInfo>();
- try
- {
- if (!CheckSoftwareInstalled().isInstalled)
- {
- LogHelper.WriteLogInfo("未安装OPT");
- return cameras.ToArray();
- }
- SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
- uint nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return cameras.ToArray();
- }
- for (int i = 0; i < stDeviceList.count; i++)
- {
- SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
- SciCam.SciCamTLType devTlType = device.tlType;
- if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
- {
- SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
- uint ip1 = gigeDevInfo.ip;
- int nIp1 = (int)(ip1 & 0x000000ff);
- int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
- int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
- int nIp4 = (int)((ip1 & 0xff000000) >> 24);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- cameras.Add(new CameraInfo()
- {
- CameraNo = i + 1,
- CameraName = gigeDevInfo.name,
- CameraBrand = CameraBrand.Opt,
- CameraType = CameraType.GIGE,
- ManufacturerName = gigeDevInfo.manufactureName,
- Model = gigeDevInfo.modelName,
- SerialNumber = gigeDevInfo.serialNumber,
- CameraIp = ip,
- IsFindByIp = true,
- });
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("搜索OPT相机列表时出错!", ex);
- }
- return cameras.ToArray();
- }
- /// <summary>
- /// 检查相机软件是否安装
- /// </summary>
- /// <returns></returns>
- public static (bool isInstalled, string version) CheckSoftwareInstalled()
- {
- //string softwareName = "OPT Camera Viewer";
- //string softwareVersion = "4.0.0.3";
- //string[] registryPaths = new[]
- //{
- // @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
- // @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
- //};
- //foreach (var path in registryPaths)
- //{
- // using (RegistryKey key = Registry.LocalMachine.OpenSubKey(path))
- // {
- // if (key == null) continue;
- // foreach (string subKeyName in key.GetSubKeyNames())
- // {
- // using (RegistryKey subKey = key.OpenSubKey(subKeyName))
- // {
- // string displayName = subKey.GetValue("DisplayName")?.ToString();
- // if (displayName != null && displayName.ToUpper().Trim() == softwareName.ToUpper())
- // {
- // string version = subKey.GetValue("DisplayVersion")?.ToString();
- // Version v1 = new Version(version);
- // Version v2 = new Version(softwareVersion);
- // if (v1 >= v2)
- // {
- // return (true, version);
- // }
- // else
- // {
- // return (false, version);
- // }
- // }
- // }
- // }
- // }
- //}
- //return (false, "");
- return (true, "4.0.0.3"); // TODO: Opt相机不检查软件安装
- }
- /// <summary>
- /// 打开相机
- /// </summary>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public bool OpenDevice()
- {
- //_operationSemaphore.Wait();
- uint nReVal = SciCam.SCI_CAMERA_OK;
- try
- {
- if (!IsHaveCamera)
- {
- mvCameraAcq = new SciCam();
- SciCam.SCI_DEVICE_INFO_LIST stDeviceList = new SciCam.SCI_DEVICE_INFO_LIST(); //设备列表
- nReVal = SciCam.DiscoveryDevices(ref stDeviceList, (uint)(SciCam.SciCamTLType.SciCam_TLType_Gige));
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return false;
- }
- for (int i = 0; i < stDeviceList.count; i++)
- {
- SciCam.SCI_DEVICE_INFO device = stDeviceList.pDevInfo[i];
- SciCam.SciCamTLType devTlType = device.tlType;
- if (devTlType == SciCam.SciCamTLType.SciCam_TLType_Gige)
- {
- SciCam.SCI_DEVICE_GIGE_INFO gigeDevInfo = (SciCam.SCI_DEVICE_GIGE_INFO)SciCam.ByteToStruct(device.info.gigeInfo, typeof(SciCam.SCI_DEVICE_GIGE_INFO));
- uint ip1 = gigeDevInfo.ip;
- int nIp1 = (int)(ip1 & 0x000000ff);
- int nIp2 = (int)((ip1 & 0x0000ff00) >> 8);
- int nIp3 = (int)((ip1 & 0x00ff0000) >> 16);
- int nIp4 = (int)((ip1 & 0xff000000) >> 24);
- string ip = string.Format("{0}.{1}.{2}.{3}", nIp1, nIp2, nIp3, nIp4);
- if (IsFindByIp)
- {
- if (CameraIp == ip)
- {
- ManufacturerName = gigeDevInfo.manufactureName;
- ModelName = gigeDevInfo.modelName;
- SerialNumber = gigeDevInfo.serialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- else
- {
- if (string.Equals(gigeDevInfo.serialNumber, SerialNumber))
- {
- ManufacturerName = gigeDevInfo.manufactureName;
- ModelName = gigeDevInfo.modelName;
- SerialNumber = gigeDevInfo.serialNumber;
- CameraType = CameraType.GIGE;
- CameraInfo = device;
- IsHaveCamera = true;
- break;
- }
- }
- }
- }
- if (!IsHaveCamera)
- {
- throw new Exception("没有发现相机");
- }
- }
- SciCam.SCI_DEVICE_INFO sCI_DEVICE_INFO = CameraInfo;
- nReVal = mvCameraAcq.CreateDevice(ref sCI_DEVICE_INFO);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- Console.WriteLine("Creat Device Fail! nRet:{0}", nReVal);
- throw new Exception("Creat Device Fail!");
- }
- // ch:打开设备 | en:Open device
- nReVal = mvCameraAcq.OpenDevice();
- // ch:设置触发模式为off | en:Set trigger mode as off
- nReVal = mvCameraAcq.SetEnumValueByStringEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerMode", "On");
- nReVal = mvCameraAcq.SetEnumValueByString("TriggerSource", "Software");
- // ch:注册事件回调 | en:Register event callback
- //nReVal = mvCameraAcq.RegisterPayloadCallBack(new SciCam.fnOnPayloadDelegate(ImageCallBack), IntPtr.Zero, true);
- // ch:设置采集策略 | en:Set Grab Strategy
- nReVal = mvCameraAcq.SetGrabStrategy(CurrentGrabStrategy);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- Console.WriteLine("Register Event CallBack fail! nRet {0}", nReVal);
- }
- if (!IsConnected)
- {
- CameraConnectChangedEvent?.Invoke(ID, true);
- }
- mvCameraAcq.SetGrabTimeout(5000);
- IsConnected = mvCameraAcq.IsDeviceOpen();
- if (IsConnected)
- {
- mvCameraAcq.StartGrabbing();
- }
- return IsConnected;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 打开相机异步
- /// </summary>
- /// <returns></returns>
- public Task<bool> OpenDeviceAsync()
- {
- return Task.Run(() =>
- {
- return OpenDevice();
- });
- }
- /// <summary>
- /// 关闭相机
- /// </summary>
- public void CloseDevice()
- {
- // ch:关闭设备 | en:Close Device
- //_operationSemaphore.Wait();
- try
- {
- mvCameraAcq?.StopGrabbing();
- mvCameraAcq?.CloseDevice();
- mvCameraAcq?.DeleteDevice();
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 采集单张图片
- /// </summary>
- /// <param name="lastImageOnly">true:采集一张新图像,false:返回最后一张图像</param>
- /// <returns></returns>
- public ICogImage Grab(bool lastImageOnly = true)
- {
- //_operationSemaphore.Wait();
- uint nReVal = SciCam.SCI_CAMERA_OK;
- IntPtr payload = IntPtr.Zero;
- try
- {
- Stopwatch sw = Stopwatch.StartNew();
- for (int i = 0; i < 5; i++)
- {
- try
- {
- if (!mvCameraAcq.IsDeviceOpen())
- {
- OpenDevice();
- }
- // 重置TaskCompletionSource
- //_tcs?.TrySetCanceled();
- //_tcs = new TaskCompletionSource<ICogImage>();
- // 注册取消令牌
- //CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(2000000); // 2秒超时
- //cancellationTokenSource.Token.Register(() => _tcs.TrySetCanceled());
- // 触发图像采集
- // ch:发送软触发命令 | en:Send Trigger Software command
- nReVal = mvCameraAcq.SetCommandValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, "TriggerSoftware");
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- nReVal = mvCameraAcq.Grab(ref payload);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- Image = GetConvertedInfo(payload);
- mvCameraAcq.FreePayload(payload);
- //nReVal = mvCameraAcq.StopGrabbing();
- TotalTime = sw.Elapsed;
- ErrorMessage = $"{i + 1}";
- return Image;
- }
- else
- {
- //nReVal = mvCameraAcq.FreePayload(payload);
- //nReVal = mvCameraAcq.StopGrabbing();
- //_operationSemaphore.Release();
- CloseDevice();
- OpenDevice();
- ErrorMessage = "图像采集失败!";
- }
- }
- else
- {
- //nReVal = mvCameraAcq.FreePayload(payload);
- //nReVal = mvCameraAcq.StopGrabbing();
- //_operationSemaphore.Release();
- CloseDevice();
- OpenDevice();
- ErrorMessage = "软触发失败!";
- }
- }
- catch (Exception ex)
- {
- //_operationSemaphore.Release();
- CloseDevice();
- OpenDevice();
- ErrorMessage = ex.Message;
- }
- }
- if (IsConnected)
- {
- IsConnected = false;
- CameraConnectChangedEvent?.Invoke(ID, false);
- }
- return null;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- // ch:采集回调接口 | en:Grab Callback interface
- void ImageCallBack(IntPtr payload, IntPtr tag)
- {
- try
- {
- if (payload == IntPtr.Zero) return;
- uint nReVal = SciCam.SCI_CAMERA_OK;
- SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE attribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
- nReVal = SciCam.PayloadGetAttribute(payload, ref attribute);
- if (nReVal != SciCam.SCI_CAMERA_OK || !attribute.isComplete)
- {
- Console.WriteLine("Failed to get image attributes or frame is incomplete! nRet:{0}", nReVal);
- _tcs?.TrySetException(new Exception($"Failed to get image attributes or frame is incomplete! nRet: {nReVal}"));
- }
- else
- {
- Image = GetConvertedInfo(payload);
- //ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- //Console.WriteLine("Get One Frame: Width[{0}], Height[{1}], nFrameNum[{2}]",
- //attribute.imgAttr.width, attribute.imgAttr.height, attribute.frameID);
- // 收到图像时完成任务
- _tcs?.TrySetResult(Image);
- }
- }
- catch (Exception ex)
- {
- _tcs?.TrySetException(new Exception($"相机采集错误: {ex.Message}"));
- }
- }
- /// <summary>
- /// 开始采集图像
- /// </summary>
- public void StartGrabbing()
- {
- lock (_stateLock)
- {
- if (IsGrabbing)
- return;
- IsGrabbing = true;
- }
- m_hReceiveThread = new Thread(GetStreamThreadProc) { IsBackground = true };
- m_hReceiveThread.Start();
- }
- /// <summary>
- /// 停止采集图像
- /// </summary>
- public void StopGrabbing()
- {
- try
- {
- lock (_stateLock)
- {
- IsGrabbing = false;
- }
- if (m_hReceiveThread != null)
- {
- m_hReceiveThread.Abort();
- m_hReceiveThread = null;
- }
- }
- catch (Exception)
- {
- }
- }
- /// <summary>
- /// 设置曝光时间
- /// </summary>
- /// <param name="ExposureTime"></param>
- /// <returns></returns>
- public bool SetExposureTime(float ExposureTime)
- {
- try
- {
- if (!mvCameraAcq.IsDeviceOpen())
- return false;
- string[] nodeName = new string[]{
- "ExposureTime",
- "ExposureTimeAbs",
- "ExposureTimeRaw"};
- uint nReVal = SciCam.SCI_CAMERA_OK;
- for (int i = 0; i < nodeName.Count(); i++)
- {
- nReVal = mvCameraAcq.SetIntValue(nodeName[i], (int)ExposureTime);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- nReVal = mvCameraAcq.SetFloatValue(nodeName[i], ExposureTime);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- break;
- }
- }
- else
- {
- break;
- }
- }
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return false;
- }
- return true;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 获取曝光时间
- /// </summary>
- /// <returns></returns>
- public float GetExposureTime()
- {
- //_operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.IsDeviceOpen())
- return 0;
- uint nReVal = SciCam.SCI_CAMERA_OK;
- string[] nodeName = new string[]
- {
- "ExposureTime",
- "ExposureTimeAbs",
- "ExposureTimeRaw"
- };
- for (int i = 0; i < nodeName.Count(); i++)
- {
- SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
- nReVal = mvCameraAcq.GetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref iNodeVal);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
- nReVal = mvCameraAcq.GetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref fNodeVal);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- return Convert.ToSingle(fNodeVal.dVal);
- }
- }
- else
- {
- return Convert.ToSingle(iNodeVal.nVal);
- }
- }
- return 0;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 设置增益
- /// </summary>
- /// <param name="Gain"></param>
- /// <returns></returns>
- public bool SetGain(float Gain)
- {
- //_operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.IsDeviceOpen())
- return false;
- uint nReVal = SciCam.SCI_CAMERA_OK;
- string[] nodeName = new string[]
- {
- "Gain",
- "GainRaw"
- };
- for (int i = 0; i < nodeName.Count(); i++)
- {
- nReVal = mvCameraAcq.SetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], (int)Gain);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- nReVal = mvCameraAcq.SetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], Gain);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- return true;
- }
- }
- else
- {
- return true;
- }
- }
- return false;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- /// <summary>
- /// 获取增益
- /// </summary>
- /// <returns></returns>
- public float GetGain()
- {
- //_operationSemaphore.Wait();
- try
- {
- if (!mvCameraAcq.IsDeviceOpen())
- return 0;
- uint nReVal = SciCam.SCI_CAMERA_OK;
- string[] nodeName = new string[]
- {
- "Gain",
- "GainRaw"
- };
- for (int i = 0; i < nodeName.Count(); i++)
- {
- SciCam.SCI_NODE_VAL_INT iNodeVal = new SciCam.SCI_NODE_VAL_INT();
- nReVal = mvCameraAcq.GetIntValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref iNodeVal);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- SciCam.SCI_NODE_VAL_FLOAT fNodeVal = new SciCam.SCI_NODE_VAL_FLOAT();
- nReVal = mvCameraAcq.GetFloatValueEx(SciCam.SciCamDeviceXmlType.SciCam_DeviceXml_Camera, nodeName[i], ref fNodeVal);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- return Convert.ToSingle(fNodeVal.dVal);
- }
- }
- else
- {
- return Convert.ToSingle(iNodeVal.nVal);
- }
- }
- return 0;
- }
- finally
- {
- //_operationSemaphore.Release();
- }
- }
- private void GetStreamThreadProc()
- {
- while (IsGrabbing)
- {
- try
- {
- Grab(false);
- ImageCallbackEvent?.Invoke(Image, TotalTime, ErrorMessage);
- }
- catch (Exception)
- {
- }
- Thread.Sleep(10);
- }
- IsGrabbing = false;
- }
- private ICogImage GetConvertedInfo(IntPtr payload)
- {
- if (payload == IntPtr.Zero)
- {
- return null;
- }
- SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE payloadAttribute = new SciCam.SCI_CAM_PAYLOAD_ATTRIBUTE();
- uint nReVal = SciCam.PayloadGetAttribute(payload, ref payloadAttribute);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return null;
- }
- bool imgIsComplete = payloadAttribute.isComplete;
- SciCam.SciCamPayloadMode payloadMode = payloadAttribute.payloadMode;
- SciCam.SciCamPixelType imgPixelType = payloadAttribute.imgAttr.pixelType;
- ulong imgWidth = payloadAttribute.imgAttr.width;
- ulong imgHeight = payloadAttribute.imgAttr.height;
- ulong framID = payloadAttribute.frameID;
- if (!imgIsComplete || payloadMode != SciCam.SciCamPayloadMode.SciCam_PayloadMode_2D)
- {
- return null;
- }
- IntPtr imgData = IntPtr.Zero;
- nReVal = SciCam.PayloadGetImage(payload, ref imgData);
- if (nReVal != SciCam.SCI_CAMERA_OK)
- {
- return null;
- }
- long destImgSize = 0;
- if (imgPixelType == SciCam.SciCamPixelType.Mono1p ||
- imgPixelType == SciCam.SciCamPixelType.Mono2p ||
- imgPixelType == SciCam.SciCamPixelType.Mono4p ||
- imgPixelType == SciCam.SciCamPixelType.Mono8s ||
- imgPixelType == SciCam.SciCamPixelType.Mono8 ||
- imgPixelType == SciCam.SciCamPixelType.Mono10 ||
- imgPixelType == SciCam.SciCamPixelType.Mono10p ||
- imgPixelType == SciCam.SciCamPixelType.Mono12 ||
- imgPixelType == SciCam.SciCamPixelType.Mono12p ||
- imgPixelType == SciCam.SciCamPixelType.Mono14 ||
- imgPixelType == SciCam.SciCamPixelType.Mono16 ||
- imgPixelType == SciCam.SciCamPixelType.Mono10Packed ||
- imgPixelType == SciCam.SciCamPixelType.Mono12Packed ||
- imgPixelType == SciCam.SciCamPixelType.Mono14p)
- {
- nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, IntPtr.Zero, ref destImgSize, true);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
- try
- {
- nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.Mono8, destImg, ref destImgSize, true);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- byte[] bBitmap = new byte[destImgSize];
- Marshal.Copy(destImg, bBitmap, 0, (int)destImgSize);
- Bitmap bitMap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
- System.Drawing.Imaging.BitmapData bitmapData = bitMap.LockBits(new Rectangle(0, 0, (int)imgWidth, (int)imgHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
- Marshal.Copy(bBitmap, 0, bitmapData.Scan0, (int)destImgSize);
- bitMap.UnlockBits(bitmapData);
- //设置调色板
- System.Drawing.Imaging.ColorPalette palette = bitMap.Palette;
- for (int i = 0; i < 256; i++)
- {
- palette.Entries[i] = Color.FromArgb(i, i, i);
- }
- bitMap.Palette = palette;
- //显示图片
- return TransformICogImage((uint)imgHeight, (uint)imgWidth, destImg, SciCam.SciCamPixelType.Mono8);
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- Marshal.FreeHGlobal(destImg);
- }
- }
- }
- else
- {
- nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, IntPtr.Zero, ref destImgSize, true);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- IntPtr destImg = Marshal.AllocHGlobal((int)destImgSize);
- try
- {
- nReVal = SciCam.PayloadConvertImage(ref payloadAttribute.imgAttr, imgData, SciCam.SciCamPixelType.RGB8, destImg, ref destImgSize, true);
- if (nReVal == SciCam.SCI_CAMERA_OK)
- {
- IntPtr pTemp = IntPtr.Zero;
- Byte[] byteArrImageData = new Byte[imgWidth * imgHeight * 3];
- unsafe
- {
- byte* pBufForSaveImage = (byte*)destImg;
- UInt32 nSupWidth = ((UInt32)imgWidth + (UInt32)3) & 0xfffffffc;
- for (int nRow = 0; nRow < (int)imgHeight; nRow++)
- {
- for (int col = 0; col < (int)imgWidth; col++)
- {
- byteArrImageData[nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col)];
- byteArrImageData[(int)imgWidth * (int)imgHeight + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 1)];
- byteArrImageData[(int)imgWidth * (int)imgHeight * 2 + nRow * nSupWidth + col] = pBufForSaveImage[nRow * (int)imgWidth * 3 + (3 * col + 2)];
- }
- }
- pTemp = Marshal.UnsafeAddrOfPinnedArrayElement(byteArrImageData, 0);
- }
- //显示图片
- return TransformICogImage((uint)imgHeight, (uint)imgWidth, pTemp, SciCam.SciCamPixelType.RGB8);
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- Marshal.FreeHGlobal(destImg);
- }
- }
- }
- return null;
- }
- private ICogImage TransformICogImage(UInt32 nHeight, UInt32 nWidth, IntPtr pImageBuf, SciCam.SciCamPixelType enPixelType)
- {
- try
- {
- ICogImage image;
- if (enPixelType == SciCam.SciCamPixelType.Mono8)
- {
- CogImage8Root cogImage8Root = new CogImage8Root();
- cogImage8Root.Initialize((Int32)nWidth, (Int32)nHeight, pImageBuf, (Int32)nWidth, null);
- CogImage8Grey cogImage8Grey = new CogImage8Grey();
- cogImage8Grey.SetRoot(cogImage8Root);
- image = cogImage8Grey.ScaleImage((int)nWidth, (int)nHeight);
- System.GC.Collect();
- return image;
- }
- else
- {
- CogImage8Root image0 = new CogImage8Root();
- IntPtr ptr0 = new IntPtr(pImageBuf.ToInt64());
- image0.Initialize((int)nWidth, (int)nHeight, ptr0, (int)nWidth, null);
- CogImage8Root image1 = new CogImage8Root();
- IntPtr ptr1 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight);
- image1.Initialize((int)nWidth, (int)nHeight, ptr1, (int)nWidth, null);
- CogImage8Root image2 = new CogImage8Root();
- IntPtr ptr2 = new IntPtr(pImageBuf.ToInt64() + nWidth * nHeight * 2);
- image2.Initialize((int)nWidth, (int)nHeight, ptr2, (int)nWidth, null);
- CogImage24PlanarColor colorImage = new CogImage24PlanarColor();
- //colorImage.SetRoots(image0, image1, image2);
- colorImage.SetRoots(image2, image1, image0);
- image = colorImage.ScaleImage((int)nWidth, (int)nHeight);
- System.GC.Collect();
- return image;
- }
- }
- catch (System.Exception)
- {
- return null;
- }
- }
- #endregion
- #region 属性通知
- /// <summary>
- /// Occurs when a property value changes.
- /// </summary>
- public event PropertyChangedEventHandler PropertyChanged;
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Checks if a property already matches a desired value. Sets the property and
- /// notifies listeners only when necessary.
- /// </summary>
- /// <typeparam name="T">Type of the property.</typeparam>
- /// <param name="storage">Reference to a property with both getter and setter.</param>
- /// <param name="value">Desired value for the property.</param>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers that
- /// support CallerMemberName.</param>
- /// <param name="onChanged">Action that is called after the property value has been changed.</param>
- /// <returns>True if the value was changed, false if the existing value matched the
- /// desired value.</returns>
- protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null)
- {
- if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
- storage = value;
- onChanged?.Invoke();
- RaisePropertyChanged(propertyName);
- return true;
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="propertyName">Name of the property used to notify listeners. This
- /// value is optional and can be provided automatically when invoked from compilers
- /// that support <see cref="CallerMemberNameAttribute"/>.</param>
- protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
- {
- OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
- }
- /// <summary>
- /// Raises this object's PropertyChanged event.
- /// </summary>
- /// <param name="args">The PropertyChangedEventArgs</param>
- protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
- {
- PropertyChanged?.Invoke(this, args);
- }
- #endregion
- }
- }
|