CameraClass.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using CCDCount.MODEL.CameraClass;
  2. using CCDCount.MODEL.ConfigModel;
  3. using LogClass;
  4. using MvCameraControl;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. namespace CCDCount.DLL
  14. {
  15. public class CameraClass
  16. {
  17. #region 常量
  18. readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
  19. | DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice
  20. | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;
  21. #endregion
  22. #region 变量
  23. private List<IDeviceInfo> CamList; // 相机列表
  24. private IDevice device = null; // 相机实例
  25. private ConcurrentQueue<IFrameOut> FrameOuts = new ConcurrentQueue<IFrameOut>();
  26. private long lastframeNum = -1;
  27. public int CamereNo { get { return _cameraNo; } }
  28. public int ImageNum { get { return FrameOuts.Count; }}
  29. private int _cameraNo = -1;
  30. private string cameraName = string.Empty;
  31. #endregion
  32. #region 公共方法
  33. /// <summary>
  34. /// 获取相机列表
  35. /// </summary>
  36. /// <param name="CamList"></param>
  37. /// <returns></returns>
  38. public void GetCameraList(out List<CameraInfoClass> CameraInfoList)
  39. {
  40. CamList = new List<IDeviceInfo>();
  41. CameraInfoList = new List<CameraInfoClass>();
  42. int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out CamList);
  43. if (nRet != MvError.MV_OK)
  44. {
  45. return;
  46. }
  47. else
  48. {
  49. //输出相机名称及SN码以方便选择设备
  50. foreach (var item in CamList)
  51. {
  52. CameraInfoList.Add(new CameraInfoClass
  53. {
  54. //DeviceName = item.UserDefinedName == "" ? item.ModelName : item.UserDefinedName,
  55. DeviceName = item.ModelName,
  56. DeviceSN = item.SerialNumber,
  57. });
  58. }
  59. }
  60. return;
  61. }
  62. /// <summary>
  63. /// 更新相机列表
  64. /// </summary>
  65. public void UpdateCameraList()
  66. {
  67. CamList = new List<IDeviceInfo>();
  68. int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out CamList);
  69. if (nRet != MvError.MV_OK)
  70. {
  71. Console.WriteLine("相机列表更新失败");
  72. return;
  73. }
  74. }
  75. /// <summary>
  76. /// 加载指定相机
  77. /// </summary>
  78. /// <param name="DeviceSN"></param>
  79. public bool LoadCamereDevice(CameraConfig DeviceConfig)
  80. {
  81. bool Blresult = false;
  82. if (device != null && device.IsConnected)
  83. {
  84. device.Close();
  85. device.Dispose();
  86. }
  87. UpdateCameraList();
  88. List<IDeviceInfo> deviceInfos = CamList.Where(o => o.SerialNumber == DeviceConfig.CameraSNNum).ToList();
  89. if(deviceInfos.Count == 0) return Blresult;
  90. IDeviceInfo deviceInfo = deviceInfos.First();
  91. try
  92. {
  93. // 打开设备
  94. device = DeviceFactory.CreateDevice(deviceInfo);
  95. }
  96. catch (Exception ex)
  97. {
  98. FaultLog.RecordErrorMessage("Create Device fail!" + DeviceConfig.CameraSNNum + ":" + ex.Message);
  99. return Blresult;
  100. }
  101. int result = device.Open();
  102. if (result != MvError.MV_OK)
  103. {
  104. FaultLog.RecordErrorMessage("Open Device fail!" + DeviceConfig.CameraSNNum + ":" + result);
  105. return Blresult;
  106. }
  107. // 判断是否为gige设备
  108. if (device is IGigEDevice)
  109. {
  110. // 转换为gigE设备
  111. IGigEDevice gigEDevice = device as IGigEDevice;
  112. // 探测网络最佳包大小(只对GigE相机有效)
  113. result = gigEDevice.GetOptimalPacketSize(out int optionPacketSize);
  114. if (result != MvError.MV_OK)
  115. {
  116. //Log("Warning: Get Packet Size failed!", result);
  117. }
  118. else
  119. {
  120. result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
  121. if (result != MvError.MV_OK)
  122. {
  123. //Log("Warning: Set Packet Size failed!", result);
  124. }
  125. }
  126. }
  127. //判断是否从配置文件读取的参数,是则设置参数,否则加载相机默认参数
  128. if(DeviceConfig.IsLoadCanfig)
  129. {
  130. //设置从配置文件读取的参数
  131. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  132. _cameraNo = DeviceConfig.CamerNo;
  133. if (DeviceConfig.CameraName != deviceModelName.CurValue)
  134. device.Parameters.SetStringValue("DeviceUserID", DeviceConfig.CameraName);
  135. device.Parameters.SetFloatValue("ExposureTime", DeviceConfig.ExposureTimeValue);
  136. device.Parameters.SetIntValue("AcquisitionLineRate", DeviceConfig.AcquistionLineRateValue);
  137. device.Parameters.GetIntValue("Height", out IIntValue height);
  138. device.Parameters.SetIntValue("Height", height.Min);
  139. device.Parameters.SetIntValue("Width", DeviceConfig.Width);
  140. device.Parameters.SetIntValue("OffsetX", DeviceConfig.OffsetX);
  141. }
  142. // 设置采集连续模式
  143. device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
  144. device.Parameters.SetEnumValueByString("TriggerMode", "Off");
  145. Blresult = true;
  146. return Blresult;
  147. }
  148. /// <summary>
  149. /// 重新加载指定相机
  150. /// </summary>
  151. /// <param name="CameraSN"></param>
  152. /// <returns></returns>
  153. public bool ReLoadCameraDevice(string CameraSN)
  154. {
  155. bool Blresult = false;
  156. if(device!=null && device.IsConnected)
  157. {
  158. device.Close();
  159. device.Dispose();
  160. }
  161. UpdateCameraList();
  162. List<IDeviceInfo> deviceInfos = CamList.Where(o => o.SerialNumber == CameraSN).ToList();
  163. if (deviceInfos.Count == 0) return Blresult;
  164. IDeviceInfo deviceInfo = deviceInfos.First();
  165. try
  166. {
  167. // 打开设备
  168. device = DeviceFactory.CreateDevice(deviceInfo);
  169. Blresult = true;
  170. }
  171. catch (Exception ex)
  172. {
  173. FaultLog.RecordErrorMessage("Create Device fail!" + CameraSN + ":" + ex.Message);
  174. return Blresult;
  175. }
  176. int result = device.Open();
  177. if (result != MvError.MV_OK)
  178. {
  179. Blresult = false;
  180. FaultLog.RecordErrorMessage("Open Device fail!" + CameraSN + ":" + result);
  181. return Blresult;
  182. }
  183. // 判断是否为gige设备
  184. if (device is IGigEDevice)
  185. {
  186. // 转换为gigE设备
  187. IGigEDevice gigEDevice = device as IGigEDevice;
  188. // 探测网络最佳包大小(只对GigE相机有效)
  189. result = gigEDevice.GetOptimalPacketSize(out int optionPacketSize);
  190. if (result != MvError.MV_OK)
  191. {
  192. //Log("Warning: Get Packet Size failed!", result);
  193. }
  194. else
  195. {
  196. result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
  197. if (result != MvError.MV_OK)
  198. {
  199. //Log("Warning: Set Packet Size failed!", result);
  200. }
  201. }
  202. }
  203. return Blresult;
  204. }
  205. /// <summary>
  206. /// 重新加载相机参数
  207. /// </summary>
  208. /// <param name="RecameraConfig"></param>
  209. /// <returns></returns>
  210. public bool ReLoadCameraConfig(CameraConfig RecameraConfig)
  211. {
  212. bool Blresult = false;
  213. if (device != null && device.IsConnected)
  214. {
  215. //设置从配置文件读取的参数
  216. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  217. _cameraNo = RecameraConfig.CamerNo;
  218. if (RecameraConfig.CameraName != deviceModelName.CurValue)
  219. device.Parameters.SetStringValue("DeviceUserID", RecameraConfig.CameraName);
  220. device.Parameters.SetFloatValue("ExposureTime", RecameraConfig.ExposureTimeValue);
  221. device.Parameters.SetIntValue("AcquisitionLineRate", RecameraConfig.AcquistionLineRateValue);
  222. device.Parameters.GetIntValue("Height", out IIntValue height);
  223. device.Parameters.SetIntValue("Height", height.Min);
  224. device.Parameters.SetIntValue("Width", RecameraConfig.Width);
  225. device.Parameters.SetIntValue("OffsetX", RecameraConfig.OffsetX);
  226. // 设置采集连续模式
  227. device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
  228. device.Parameters.SetEnumValueByString("TriggerMode", "Off");
  229. Blresult = true;
  230. }
  231. return Blresult;
  232. }
  233. /// <summary>
  234. /// 开启相机采集
  235. /// </summary>
  236. public bool StartCamera()
  237. {
  238. return StartReceiveFuntion();
  239. }
  240. /// <summary>
  241. /// 关闭相机采集
  242. /// </summary>
  243. public void StopCamera()
  244. {
  245. StopReceiveFuntion();
  246. //StopEventGetImage();
  247. }
  248. /// <summary>
  249. /// 释放相机资源
  250. /// </summary>
  251. public void DisPoseCamera()
  252. {
  253. if (device != null)
  254. {
  255. int result = device.StreamGrabber.StopGrabbing();
  256. device.Close();
  257. device.Dispose();
  258. if (result != MvError.MV_OK)
  259. {
  260. LOG.log(("Stop Grabbing Fail!", result));
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// 获取一次图片
  266. /// </summary>
  267. /// <param name="IFrameData"></param>
  268. /// <returns></returns>
  269. public bool GetOnceImage(out IFrameOut IFrameData)
  270. {
  271. bool result = false;
  272. int BRet = device.StreamGrabber.GetImageBuffer(1000, out IFrameData);
  273. if (BRet == 0 && IFrameData != null) result = true;
  274. else return result;
  275. if (lastframeNum == -1)
  276. {
  277. lastframeNum = IFrameData.FrameNum;
  278. }
  279. else if (lastframeNum == IFrameData.FrameNum - 1)
  280. {
  281. lastframeNum = IFrameData.FrameNum;
  282. }
  283. else
  284. {
  285. //丢帧记录
  286. LOG.log(string.Format("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  287. IFrameData.Image.Width, IFrameData.Image.Height, IFrameData.FrameNum - 1, lastframeNum), 6);
  288. Console.WriteLine("lost frame: Width[{0}] , Height[{1}] , FrameNum[{2}] ,Frevous[{3}]",
  289. IFrameData.Image.Width, IFrameData.Image.Height, IFrameData.FrameNum - 1, lastframeNum);
  290. lastframeNum = IFrameData.FrameNum;
  291. }
  292. return result;
  293. }
  294. /// <summary>
  295. /// 获取相机图像尺寸信息
  296. /// </summary>
  297. /// <returns></returns>
  298. public CameraImageSizeClass GetCamereImageSize()
  299. {
  300. CameraImageSizeClass cameraImageSize =new CameraImageSizeClass();
  301. if(device != null)
  302. {
  303. device.Parameters.GetIntValue("Width", out IIntValue PixWidth);
  304. device.Parameters.GetIntValue("Height", out IIntValue PixHeight);
  305. cameraImageSize.Height = (int)PixHeight.CurValue;
  306. cameraImageSize.Width = (int)PixWidth.CurValue;
  307. }
  308. return cameraImageSize;
  309. }
  310. /// <summary>
  311. /// 获取当前相机的参数生成Config信息
  312. /// </summary>
  313. /// <returns></returns>
  314. public CameraConfig GetConfigValue()
  315. {
  316. CameraConfig result;
  317. device.Parameters.GetFloatValue("ExposureTime", out IFloatValue exposureTime);
  318. device.Parameters.GetIntValue("AcquisitionLineRate", out IIntValue acquisitionLineRate);
  319. device.Parameters.GetIntValue("OffsetX", out IIntValue offsetX);
  320. device.Parameters.GetIntValue("Width", out IIntValue pixWidth);
  321. device.Parameters.GetStringValue("DeviceUserID", out IStringValue deviceUserID);
  322. device.Parameters.GetStringValue("DeviceModelName", out IStringValue deviceModelName);
  323. device.Parameters.GetStringValue("DeviceSerialNumber", out IStringValue deviceSerialNumber);
  324. result = new CameraConfig()
  325. {
  326. CameraSNNum = deviceSerialNumber.CurValue,
  327. ExposureTimeValue = exposureTime.CurValue,
  328. AcquistionLineRateValue = (int)acquisitionLineRate.CurValue,
  329. Width = (int)pixWidth.CurValue,
  330. OffsetX = (int)offsetX.CurValue,
  331. CameraName = deviceUserID.CurValue,
  332. DeviceName = deviceModelName.CurValue,
  333. CamerNo = _cameraNo
  334. };
  335. return result;
  336. }
  337. /// <summary>
  338. /// 保存参数
  339. /// </summary>
  340. public void SaveConfig()
  341. {
  342. CameraConfig camerasConfig = null;
  343. if (!Directory.Exists(".\\Config\\")) Directory.CreateDirectory(".\\Config\\");
  344. XmlStorage.SerializeToXml(camerasConfig, ".\\Config\\CameraConfig.xml");
  345. }
  346. public bool IsLoadCamera()
  347. {
  348. return device != null;
  349. }
  350. public bool IsConnectCamera()
  351. {
  352. if (device == null) return false;
  353. else
  354. {
  355. return device.IsConnected;
  356. }
  357. }
  358. #endregion
  359. #region 私有方法
  360. /// <summary>
  361. /// 开启采集
  362. /// </summary>
  363. private bool StartReceiveFuntion()
  364. {
  365. bool result = false;
  366. try
  367. {
  368. if(device == null) return result;
  369. device.StreamGrabber.SetImageNodeNum(10);
  370. device.StreamGrabber.StartGrabbing();
  371. result = true;
  372. }
  373. catch (Exception ex)
  374. {
  375. FaultLog.RecordErrorMessage("Start thread failed!, " + ex.Message);
  376. throw;
  377. }
  378. return result;
  379. }
  380. /// <summary>
  381. /// 关闭采集
  382. /// </summary>
  383. private void StopReceiveFuntion()
  384. {
  385. try
  386. {
  387. if (device == null) return;
  388. int ret = device.StreamGrabber.StopGrabbing();
  389. if (ret != MvError.MV_OK)
  390. {
  391. FaultLog.RecordErrorMessage($"Stop grabbing failed:{ret:x8}");
  392. return;
  393. }
  394. }
  395. catch (Exception ex)
  396. {
  397. FaultLog.RecordErrorMessage("Stop thread failed!, " + ex.Message);
  398. throw;
  399. }
  400. }
  401. #endregion
  402. }
  403. }