| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672 |
- using IvfTl.Control.Entity.GlobalEnums;
- using System.Drawing;
- using System.Runtime.ExceptionServices;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Cryptography;
- using System.Text;
- namespace ivf_tl_CameraHelper
- {
- /// <summary>
- /// 相机助手类
- /// </summary>
- public class Camera
- {
- public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
- public event Action<DateTime, string, LogEnum> HouseLogEvent;
- private int index = 0;
- private int width = 0;
- private int height = 0;
- private int exposure = 0;
- public int camnums = 0;
- [MarshalAs(UnmanagedType.LPTStr)]
- public string NumBer = "";
- /// <summary>
- /// MVC数字相机的索引号(从0开始),用于指定要进行初始化操作的相机。
- /// </summary>
- public int Index { get { return index; } }
- /// <summary>
- /// 图像宽度
- /// </summary>
- public int Width { get { return width; } }
- /// <summary>
- /// 图像高度
- /// </summary>
- public int Height { get { return height; } }
- /// <summary>
- /// 曝光时间(单位:100us)
- /// </summary>
- public int Exposure { get { return exposure; } }
- /// <summary>
- /// CCD是否加载
- /// </summary>
- public bool IsInit { get; set; } = false;
- /// <summary>
- /// CCD是否开启
- /// </summary>
- public bool IsStart { get; set; } = false;
- /// <summary>
- /// 图像字节数组
- /// </summary>
- public byte[] SourceBuffer //{ get; private set; }
- {
- get
- {
- byte[] sourceBuffer = new byte[this.width * this.height * 3];
- Marshal.Copy(pDest, sourceBuffer, 0, sourceBuffer.Length);
- return sourceBuffer;
- }
- }
- public byte[] SaveRgbData = new byte[3];
- public void UpdataSourceBuffer()
- {
- //SourceBuffer = new byte[this.width * this.height * 3];
- //Marshal.Copy(pDest, SourceBuffer, 0, SourceBuffer.Length);
- }
- /// <summary>
- /// 获取相机对应得序列号
- /// </summary>
- /// <returns></returns>
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- public int GetNumbet()
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- StringBuilder strSerial = new StringBuilder(125);
- result = MVCAPI.MV_Usb2GetSerial(this.hImager, strSerial);
- NumBer = strSerial.ToString();
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, "获取序列号", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 获取一张图像
- /// </summary>
- //public BitmapImage BitmapImage
- //{
- // get
- // {
- // Bitmap bitmap = new Bitmap(this.width, this.height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
- // System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
- // Marshal.Copy(this.SourceBuffer, 0, bmpData.Scan0, this.SourceBuffer.Length);
- // bitmap.UnlockBits(bmpData);
- // bitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
- // BitmapImage bitmapImage = new BitmapImage();
- // using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
- // {
- // bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
- // bitmapImage.BeginInit();
- // bitmapImage.StreamSource = ms;
- // bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
- // bitmapImage.EndInit();
- // bitmapImage.Freeze();
- // }
- // return bitmapImage;
- // }
- //}
- /// <summary>
- /// 结构体
- /// </summary>
- private CapInfoStruct capInfoStruct = new CapInfoStruct();
- /// <summary>
- /// 由MV_Usb2Init返回的MVC设备句柄
- /// </summary>
- public IntPtr hImager;
- /// <summary>
- /// 回传的图像字节数组
- /// </summary>
- private IntPtr pDest;
- public Camera(int index, int width, int height, int exposure)
- {
- this.index = index;
- this.width = width;
- this.height = height;
- this.exposure = exposure;
- pDest = Marshal.AllocCoTaskMem(this.width * this.height * 3);
- }
- public Camera(CameraModel model)
- {
- this.index = model.Index;
- this.width = model.Width;
- this.height = model.Height;
- this.exposure = model.Exposure;
- pDest = Marshal.AllocCoTaskMem(this.width * this.height * 3);
- }
- /// <summary>
- /// 初使化相机[注:执行init()之后立即执行SetOpMode()以开启像捕捉 2021.11.11]
- /// </summary>
- /// <returns></returns>
- public int Init()
- {
- try
- {
- byte[] mGain = new byte[3];
- mGain[0] = Convert.ToByte(25);
- mGain[1] = Convert.ToByte(14);
- mGain[2] = Convert.ToByte(25);
- byte Control = Convert.ToByte(04);
- capInfoStruct.Buffer = Marshal.AllocCoTaskMem(this.width * this.height * 3);
- capInfoStruct.Width = this.width;
- capInfoStruct.Height = this.height;
- capInfoStruct.HorizontalOffset = 0;
- capInfoStruct.VerticalOffset = 0;
- capInfoStruct.Exposure = this.exposure;
- capInfoStruct.Gain = mGain;
- capInfoStruct.Control = Control;
- var result = InitCamera(this);
- if (result == 0) this.IsInit = true;
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机初始化", null, LogEnum.RunException);
- return -2;
- }
- }
- public bool DisPose()
- {
- try
- {
- Marshal.FreeCoTaskMem(capInfoStruct.Buffer);
- Marshal.FreeCoTaskMem(pDest);
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机释放内存", null, LogEnum.RunException);
- return false;
- }
- }
- public int Usb2Start(IntPtr mControlPtr, int left, int top, int width, int height)
- {
- var nRetValue = MVCAPI.MV_Usb2Start(hImager, "MVC Camera Preview", MVCAPI.WS_CHILD | MVCAPI.WS_VISIBLE, left, top, width, height, mControlPtr, 0, (int)System.Threading.ThreadPriority.Highest, (int)System.Threading.ThreadPriority.Highest);
- return nRetValue;
- }
- public int Usb2Stop()
- {
- var nRetValue = MVCAPI.MV_Usb2Stop(hImager);
- return nRetValue;
- }
- public int Usb2StartCapture()
- {
- try
- {
- var nRetValue = MVCAPI.MV_Usb2StartCapture(hImager, true);
- return nRetValue;
- }
- catch (Exception)
- {
- return -1;
- }
- }
- public int Usb2StopCapture()
- {
- try
- {
- var nRetValue = MVCAPI.MV_Usb2StartCapture(hImager, false);
- return nRetValue;
- }
- catch (Exception)
- {
- return -1;
- }
- }
- /// <summary>
- /// 多个方法共同锁
- /// </summary>
- private static readonly object locker = new object();
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- private int InitCamera(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- //MVC2000
- result = MVCAPI.MV_Usb2Init("MVC2000", out camera.index, ref camera.capInfoStruct, out camera.hImager);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{camera.index}号相机初始化", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 卸载相机
- /// </summary>
- /// <returns></returns>
- public int UnInit()
- {
- try
- {
- this.IsInit = false;
- var result = UnInit(this);
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机卸载", null, LogEnum.RunException);
- return -1;
- }
- }
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- private int UnInit(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- result = MVCAPI.MV_Usb2Uninit(ref hImager);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{camera.index}号相机卸载", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 设置摄像头的采集模式为连续采集模式
- /// </summary>
- /// <returns></returns>
- public int SetOpMode()
- {
- try
- {
- if (this.IsInit == false) return -1;
- var result = SetOpMode(this);
- this.IsStart = result == 0;
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机设置采集模式", null, LogEnum.RunException);
- return -1;
- }
- }
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- private int SetOpMode(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- result = MVCAPI.MV_Usb2SetOpMode(camera.hImager, 0, false);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{camera.index}号相机设置采集模式", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 抓取一张图像
- /// </summary>
- /// <returns>返回该图字节数组</returns>
- public int GetRgbData()
- {
- try
- {
- if (this.IsStart == false) return -1;
- return GetRgbData(this);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机抓图", null, LogEnum.RunException);
- return -2;
- }
- }
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- private int GetRgbData(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- result = MVCAPI.MV_Usb2GetRgbData(camera.hImager, ref camera.capInfoStruct, camera.pDest);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{camera.index}号相机抓图", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 抓取一张图像
- /// </summary>
- /// <returns>返回该图字节数组</returns>
- public int GetRawData()
- {
- if (this.IsStart == false) return -1;
- return GetRawData(this);
- }
- private int GetRawData(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- result = MVCAPI.MV_Usb2GetRawData(camera.hImager, ref camera.capInfoStruct);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机抓图", null, LogEnum.RunException);
- return -2;
- }
- }
- public int GetCamNum()
- {
- try
- {
- if (this.IsStart == false) return -1;
- int nRetValue = -1;
- nRetValue = MVCAPI.MV_Usb2GetNumberDevicesEX(out camnums);
- if (nRetValue == 0) return camnums;
- ExceptionLogEvent?.Invoke(new Exception($"{index}号相机获取相机数量失败"), $"{index}号相机获取相机数量", null, LogEnum.RunException);
- return nRetValue;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机获取相机数量", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 抓取一张图像
- /// </summary>
- /// <returns>返回该图字节数组</returns>
- public int RawToRgb()
- {
- if (this.IsStart == false) return -1;
- return RawToRgb(this);
- }
- private int RawToRgb(Camera camera)
- {
- try
- {
- int result = -1;
- lock (locker)
- {
- result = MVCAPI.MV_Usb2ConvertRawToRgb(camera.hImager, camera.capInfoStruct.Buffer, camera.width, camera.height, camera.pDest);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机RawToRgb", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 设置相机参数
- /// </summary>
- /// <param name="model"></param>
- /// <returns></returns>
- public int SetPartOfCapInfo(int Exposure)
- {
- return SetPartOfCapInfo(this, Exposure);
- }
- [HandleProcessCorruptedStateExceptions]
- [SecurityCritical]
- public int SetPartOfCapInfo(Camera camera, int Exposure)
- {
- try
- {
- int result;
- capInfoStruct.Exposure = Exposure;
- //this.width = model.Width;
- //this.height = model.Height;
- //capInfoStruct.Gain[0] = Convert.ToByte(model.Red);
- //capInfoStruct.Gain[1] = Convert.ToByte(model.Green);
- //capInfoStruct.Gain[2] = Convert.ToByte(model.Blue);
- //capInfoStruct.HorizontalOffset = model.HorizontalOffset;
- //capInfoStruct.VerticalOffset = model.VerticalOffset;
- //capInfoStruct.Exposure = model.Exposure;
- //capInfoStruct.Width = this.width;
- //capInfoStruct.Height = this.height;
- //capInfoStruct.Buffer = Marshal.AllocCoTaskMem(this.width * this.height);
- //pDest = Marshal.AllocCoTaskMem(this.width * this.height * 3);
- lock (locker)
- {
- result = MVCAPI.MV_Usb2SetPartOfCapInfo(hImager, ref capInfoStruct);
- }
- return result;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{camera.index}号相机设置参数", null, LogEnum.RunException);
- return -2;
- }
- }
- /// <summary>
- /// 保存当前缓存中的原图
- /// </summary>
- /// <param name="fullName"></param>
- /// <returns></returns>
- public bool SaveBmpPic(string fullName)
- {
- bool result = false;
- try
- {
- //位图对象
- System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
- this.width,
- this.height,
- System.Drawing.Imaging.PixelFormat.Format24bppRgb);
- //图像数据
- System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(
- new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
- System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
- Marshal.Copy(this.SourceBuffer, 0, bmpData.Scan0, this.SourceBuffer.Length);
- //解锁
- bitmap.UnlockBits(bmpData);
- //翻转
- bitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
- //保存
- bitmap.Save(fullName);
- result = true;
- }
- catch
- {
- return result;
- }
- return result;
- }
- public bool SaveJPG(string fullName)
- {
- MemoryStream memoryStream = null;
- FileStream fs = null;
- bool success = false;
- try
- {
- memoryStream = new MemoryStream(this.SourceBuffer);
- fs = new FileStream(fullName, FileMode.OpenOrCreate);
- memoryStream.WriteTo(fs);
- success = true;
- }
- catch (Exception ex)
- {
- success = false;
- }
- finally
- {
- if (fs != null)
- {
- fs.Close();
- fs.Dispose();
- }
- if (memoryStream != null)
- {
- memoryStream.Close();
- memoryStream.Dispose();
- }
- }
- return success;
- }
- public byte[] LastSourceBufferHash { get; set; }
- public void SavePreMem()
- {
- try
- {
- LastSourceBufferHash = GetHash(SourceBuffer);
- //var aa = SourceBuffer;
- //LastSourceBuffer = new byte[aa.Length];
- //Buffer.BlockCopy(aa, 0, LastSourceBuffer, 0, aa.Length);
- //HouseLogEvent?.Invoke(DateTime.Now, $"{index}号相机保存后的数据比较 [{aa.SequenceEqual(LastSourceBuffer)}]", LogEnum.HouseRunRecord);
- //HouseLogEvent?.Invoke(DateTime.Now, $"{index}号相机保存数据记录开始 [{ByteToHexStr(SaveRgbData)}]", LogEnum.HouseRunRecord);
- //SaveRgbData[0] = aa[0];
- //SaveRgbData[1] = aa[aa.Length / 2];
- //SaveRgbData[2] = aa[aa.Length - 1];
- //HouseLogEvent?.Invoke(DateTime.Now, $"{index}号相机保存数据记录结束 [{ByteToHexStr(SaveRgbData)}]", LogEnum.HouseRunRecord);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机保存数据", null, LogEnum.RunException);
- }
- }
- public bool CheckRgbData()
- {
- try
- {
- //var aa = SourceBuffer;
- byte[] SourceBufferHash = GetHash(SourceBuffer);
- if (LastSourceBufferHash.SequenceEqual(SourceBufferHash))
- {
- return false;
- }
- LastSourceBufferHash = new byte[SourceBufferHash.Length];
- Buffer.BlockCopy(SourceBufferHash, 0, LastSourceBufferHash, 0, SourceBufferHash.Length);
- return true;
- //if (SourceBuffer.SequenceEqual(LastSourceBuffer))
- //{
- // return false;
- //}
- //return true;
- //var aa = SourceBuffer;
- //if (SaveRgbData[0] == aa[0] && SaveRgbData[1] == aa[aa.Length / 2] && SaveRgbData[2] == aa[aa.Length - 1])
- //{
- // return false;
- //}
- //return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{index}号相机校验拍照数据", null, LogEnum.RunException);
- return false;
- }
- }
- public string ByteToHexStr(byte[] bytes)
- {
- string returnStr = "";
- if (bytes != null)
- {
- for (int i = 0; i < bytes.Length; i++)
- {
- returnStr += bytes[i].ToString("X2") + " ";
- }
- }
- return returnStr;
- }
- public byte[] GetHash(byte[] bytes)
- {
- return SHA256.HashData(bytes);
- }
- }
- }
|