CameraGroup.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // CameraGroup.cs 相机组线程管理类,控制相机采集和识别的线程运行,开放有算法的接口
  2. using MvCameraControl;
  3. using MvvmScaffoldFrame48.DLL.CameraTools;
  4. using MvvmScaffoldFrame48.Model.ResultModel;
  5. using MvvmScaffoldFrame48.Model.StorageModel.SystemConfig;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MvvmScaffoldFrame48.DLL.ThreadManager
  12. {
  13. /// <summary>
  14. /// 相机组配置和状态管理类
  15. /// 管理单个相机的采集和处理线程及相关资源
  16. /// </summary>
  17. public class CameraGroup
  18. {
  19. #region 变量与实例
  20. //相机线程的休眠时间,默认为0,即不休眠。在采集节拍没有那么高时,增加此值降低性能消耗
  21. private int CameraSleepTime = 0;
  22. //相机
  23. public HikCamera Camera { get; set; }
  24. //相机ID
  25. public int CameraId { get; set; }
  26. //是否运行中
  27. public bool IsRunning { get; set; }
  28. //相机处理线程
  29. public Task CameraTask { get; set; }
  30. //图像处理线程
  31. public Task ProcessingTask { get; set; }
  32. //图像队列
  33. public ConcurrentQueue<IImage> ImageQueue { get; set; }
  34. //信号量
  35. public SemaphoreSlim QueueSemaphore { get; set; }
  36. //取消令牌
  37. public CancellationTokenSource CancellationTokenSource { get; set; }
  38. // 图像处理算法(接口方式)
  39. public IImageProcessingAlgorithmHikVision ImageProcessor { get; set; }
  40. // 结果发送事件,当图像处理完成时触发
  41. public event EventHandler<CameraProcessEventArgsResultModel> ProcessResultAvailable;
  42. // 参数配置
  43. public CameraProcessConfigModel Configuration { get; set; }
  44. #endregion
  45. #region 公共方法
  46. /// <summary>
  47. /// 启动相机组(包括采集和处理线程)
  48. /// </summary>
  49. public void Start()
  50. {
  51. if (Camera == null)
  52. {
  53. Console.WriteLine($"相机 {CameraId} 未初始化");
  54. return;
  55. }
  56. if (Camera.Device == null)
  57. {
  58. Console.WriteLine($"相机 {CameraId} 未初始化");
  59. return;
  60. }
  61. if (Camera.Device.IsConnected == false)
  62. {
  63. Console.WriteLine($"相机 {CameraId} 未打开");
  64. return;
  65. }
  66. if (IsRunning)
  67. return;
  68. // 根据配置加载算法
  69. LoadAlgorithmFromConfiguration();
  70. Camera.FrameGrabbedEvent += CameraCaptureLoop;
  71. //Camera.StartReceiveFuntion();
  72. Camera.StartReceiveFuntionSetFrameGrabedEvent();
  73. // 重置取消令牌
  74. CancellationTokenSource = new CancellationTokenSource();
  75. var token = CancellationTokenSource.Token;
  76. // 启动相机采集线程
  77. //CameraTask = Task.Factory.StartNew(() => CameraCaptureLoop(token),
  78. // token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  79. // 启动图像处理线程
  80. ProcessingTask = Task.Factory.StartNew(() => ImageProcessingbatchLoop(token),
  81. token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  82. IsRunning = true;
  83. Console.WriteLine($"相机组 {CameraId} 已启动");
  84. }
  85. /// <summary>
  86. /// 停止相机组
  87. /// </summary>
  88. public async void Stop()
  89. {
  90. if (!IsRunning)
  91. return;
  92. // 发送取消信号
  93. CancellationTokenSource.Cancel();
  94. // 等待线程完成
  95. try
  96. {
  97. if (CameraTask != null)
  98. await CameraTask;
  99. if (ProcessingTask != null)
  100. await ProcessingTask;
  101. }
  102. catch (OperationCanceledException)
  103. {
  104. // 正常取消,忽略异常
  105. }
  106. IsRunning = false;
  107. Camera.StopReceiveFuntionSetFrameGrabedEvent();
  108. Console.WriteLine($"相机组 {CameraId} 已停止");
  109. }
  110. /// <summary>
  111. /// 更新算法参数
  112. /// </summary>
  113. /// <param name="parameters">新参数</param>
  114. public void UpdateAlgorithmParameters(object parameters)
  115. {
  116. if (ImageProcessor != null && parameters != null)
  117. {
  118. string parametersjson = ImageProcessor.GetSaveJson();
  119. ImageProcessor.Configure(parametersjson);
  120. // 更新配置
  121. if (Configuration != null)
  122. {
  123. Configuration.AlgorithmParameters = parametersjson;
  124. }
  125. Console.WriteLine($"相机 {CameraId} 算法参数已更新");
  126. }
  127. }
  128. #endregion
  129. #region 私有方法
  130. /// <summary>
  131. /// 设置图像处理算法
  132. /// </summary>
  133. /// <param name="algorithmName">算法名称</param>
  134. private void SetProcessingAlgorithm(string algorithmName, string parameters = null)
  135. {
  136. if (string.IsNullOrEmpty(algorithmName))
  137. {
  138. ImageProcessor = null;
  139. return;
  140. }
  141. try
  142. {
  143. // 根据算法名称创建实例(这里可以使用简单的工厂方法或反射)
  144. ImageProcessor = ImageProcessingAlgorithmHikVisionFactory.CreateAlgorithm(algorithmName);
  145. // 配置参数
  146. if (parameters != null && ImageProcessor != null)
  147. {
  148. ImageProcessor.Configure(parameters);
  149. }
  150. Console.WriteLine($"相机 {CameraId} 成功设置算法: {algorithmName}");
  151. }
  152. catch (Exception ex)
  153. {
  154. Console.WriteLine($"相机 {CameraId} 设置算法 {algorithmName} 失败: {ex.Message}");
  155. }
  156. }
  157. /// <summary>
  158. /// 根据配置动态加载算法
  159. /// </summary>
  160. private void LoadAlgorithmFromConfiguration()
  161. {
  162. if (Configuration != null && !string.IsNullOrEmpty(Configuration.ProcessingAlgorithmName))
  163. {
  164. SetProcessingAlgorithm(Configuration.ProcessingAlgorithmName, Configuration.AlgorithmParameters);
  165. }
  166. else
  167. {
  168. // 使用默认算法(无参数)
  169. SetProcessingAlgorithm("Default");
  170. }
  171. }
  172. /// <summary>
  173. /// 加载相机配置
  174. /// </summary>
  175. private void LoadCameraConfiguration()
  176. {
  177. if(Configuration != null&& !string.IsNullOrEmpty(Configuration.CameraParameters))
  178. {
  179. }
  180. }
  181. /// <summary>
  182. /// 发送处理结果到通信线程的方法
  183. /// 多个线程可以共用此方法
  184. /// </summary>
  185. /// <param name="resultData">处理结果数据</param>
  186. private void SendProcessResult(object resultData)
  187. {
  188. var eventArgs = new CameraProcessEventArgsResultModel
  189. {
  190. CameraId = this.CameraId,
  191. ResultData = resultData,
  192. Timestamp = DateTime.Now
  193. };
  194. // 触发事件,通知订阅者有新的处理结果
  195. ProcessResultAvailable?.Invoke(this, eventArgs);
  196. }
  197. /// <summary>
  198. /// 图像处理实现
  199. /// </summary>
  200. private void ProcessImage(IImage imageData, int cameraId)
  201. {
  202. object resultData = null;
  203. try
  204. {
  205. // 优先使用接口方式的算法
  206. if (ImageProcessor != null)
  207. {
  208. resultData = ImageProcessor.ProcessImage(imageData, cameraId);
  209. }
  210. // 如果都没有设置,则使用默认处理
  211. else
  212. {
  213. Console.WriteLine($"相机 {CameraId} 未加载算法");
  214. // 默认处理逻辑
  215. }
  216. if(resultData!=null)
  217. {
  218. // 发送处理结果
  219. SendProcessResult(resultData);
  220. }
  221. // 输出处理结果
  222. }
  223. catch (Exception ex)
  224. {
  225. Console.WriteLine($"相机 {CameraId} 图像处理错误: {ex.Message}");
  226. // 发送错误结果
  227. }
  228. }
  229. #endregion
  230. #region 线程主体方法
  231. /// <summary>
  232. /// 相机采集循环
  233. /// </summary>
  234. private async void CameraCaptureLoop(CancellationToken token)
  235. {
  236. //int frameCount = 0;
  237. try
  238. {
  239. while (!token.IsCancellationRequested)
  240. {
  241. // 模拟相机图像采集(无休眠,持续采集)
  242. if (Camera.GetOnceImage(out IFrameOut imageData))
  243. {
  244. // 将图像放入队列
  245. ImageQueue.Enqueue(imageData.Image.Clone() as IImage);
  246. double QuTuYanshi = (DateTime.Now - FromUnixTimestamp((long)imageData.HostTimeStamp)).TotalMilliseconds;
  247. //Console.WriteLine($"相机 {CameraId} 采集到图像,帧号{imageData.FrameNum}");
  248. if(QuTuYanshi > 12)
  249. {
  250. Console.WriteLine($"识别落后时间{QuTuYanshi}");
  251. }
  252. QueueSemaphore.Release(); // 通知处理线程有新数据
  253. imageData.Dispose();
  254. }
  255. // 这里不添加休眠,保持最大帧率采集
  256. await Task.Delay(CameraSleepTime);
  257. }
  258. }
  259. catch (OperationCanceledException)
  260. {
  261. // 线程被取消,正常退出
  262. }
  263. catch (Exception ex)
  264. {
  265. Console.WriteLine($"相机 {CameraId} 采集异常: {ex.Message}");
  266. }
  267. }
  268. /// <summary>
  269. /// 相机回调取图
  270. /// 与循环取图二选一
  271. /// </summary>
  272. /// <param name="sender"></param>
  273. /// <param name="e"></param>
  274. private void CameraCaptureLoop(object sender, FrameGrabbedEventArgs e)
  275. {
  276. try
  277. {
  278. // 将图像放入队列
  279. ImageQueue.Enqueue(e.FrameOut.Image.Clone() as IImage);
  280. double QuTuYanshi = (DateTime.Now - FromUnixTimestamp((long)e.FrameOut.HostTimeStamp)).TotalMilliseconds;
  281. //Console.WriteLine($"相机 {CameraId} 采集到图像,帧号{imageData.FrameNum}");
  282. if (QuTuYanshi > 12)
  283. {
  284. Console.WriteLine($"识别落后时间{QuTuYanshi}");
  285. }
  286. QueueSemaphore.Release(); // 通知处理线程有新数据
  287. e.FrameOut.Dispose();
  288. }
  289. catch (Exception ex)
  290. {
  291. Console.WriteLine($"相机 {CameraId} 采集异常: {ex.Message}");
  292. }
  293. }
  294. /// <summary>
  295. /// 图像处理循环
  296. /// 适用取图频率不高的处理,或者处理速度远快于取图速度的方法
  297. /// </summary>
  298. private async void ImageProcessingLoop(CancellationToken token)
  299. {
  300. try
  301. {
  302. while (!token.IsCancellationRequested)
  303. {
  304. // 等待图像数据
  305. await QueueSemaphore.WaitAsync(token);
  306. // 从队列获取图像
  307. if (ImageQueue.TryDequeue(out IImage imageData))
  308. {
  309. // 执行图像处理逻辑
  310. ProcessImage(imageData, CameraId);
  311. imageData.Dispose();
  312. // 可以根据队列长度决定是否短暂休眠以避免过度占用CPU
  313. if (ImageQueue.Count == 0)
  314. {
  315. await Task.Delay(1, token); // 短暂让出CPU
  316. }
  317. }
  318. }
  319. }
  320. catch (OperationCanceledException)
  321. {
  322. // 线程被取消,正常退出
  323. }
  324. catch (Exception ex)
  325. {
  326. Console.WriteLine($"相机 {CameraId} 处理异常: {ex.Message}");
  327. }
  328. }
  329. /// <summary>
  330. /// 图像处理循环-引入批处理
  331. /// 处理速度与取图速度的差不多的时候
  332. /// </summary>
  333. /// <param name="token"></param>
  334. private async void ImageProcessingbatchLoop(CancellationToken token)
  335. {
  336. const int batchSize = 5; // 每批处理的最大图像数量
  337. var batch = new List<IImage>(batchSize); // 存储当前批次的图像
  338. try
  339. {
  340. while (!token.IsCancellationRequested)
  341. {
  342. // 等待至少一张图像数据
  343. await QueueSemaphore.WaitAsync(token);
  344. // 收集一批图像(严格按队列顺序)
  345. while (batch.Count < batchSize && ImageQueue.TryDequeue(out IImage imageData))
  346. {
  347. batch.Add(imageData);
  348. if (ImageQueue.Count > 0)
  349. {
  350. QueueSemaphore.Release(); // 提前释放信号量,唤醒其他等待线程
  351. }
  352. }
  353. // 顺序处理当前批次的所有图像
  354. foreach (var image in batch)
  355. {
  356. ProcessImage(image, CameraId); // 严格按顺序执行处理逻辑
  357. image.Dispose(); // 处理完成后立即释放资源
  358. }
  359. // 清空当前批次,准备下一轮处理
  360. batch.Clear();
  361. // 如果队列为空,短暂休眠以避免过度占用CPU
  362. if (ImageQueue.Count == 0)
  363. {
  364. await Task.Delay(1, token); // 固定短时间休眠
  365. }
  366. }
  367. }
  368. catch (OperationCanceledException)
  369. {
  370. // 线程被取消,正常退出
  371. }
  372. catch (Exception ex)
  373. {
  374. Console.WriteLine($"相机 {CameraId} 处理异常: {ex.Message}");
  375. }
  376. }
  377. #endregion
  378. public DateTime FromUnixTimestamp(long timestamp, bool isMilliseconds = false)
  379. {
  380. try
  381. {
  382. // 如果未指定单位,尝试自动检测
  383. if (!isMilliseconds)
  384. {
  385. // 如果时间戳看起来像毫秒级(13位数字)
  386. if (timestamp.ToString().Length > 10)
  387. {
  388. isMilliseconds = true;
  389. }
  390. }
  391. if (isMilliseconds)
  392. {
  393. // 验证毫秒级时间戳范围
  394. const long minMilliTimestamp = -62135596800000; // 0001-01-01 00:00:00 UTC
  395. const long maxMilliTimestamp = 253402300799999; // 9999-12-31 23:59:59 UTC
  396. if (timestamp < minMilliTimestamp || timestamp > maxMilliTimestamp)
  397. {
  398. throw new ArgumentOutOfRangeException(nameof(timestamp),
  399. "毫秒级时间戳超出有效范围");
  400. }
  401. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp);
  402. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  403. }
  404. else
  405. {
  406. // 验证秒级时间戳范围
  407. const long minTimestamp = -62135596800;
  408. const long maxTimestamp = 253402300799;
  409. if (timestamp < minTimestamp || timestamp > maxTimestamp)
  410. {
  411. throw new ArgumentOutOfRangeException(nameof(timestamp),
  412. "秒级时间戳超出有效范围");
  413. }
  414. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
  415. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  416. }
  417. }
  418. catch (ArgumentOutOfRangeException)
  419. {
  420. throw;
  421. }
  422. catch (Exception ex)
  423. {
  424. throw new ArgumentException($"无法转换时间戳 {timestamp}: {ex.Message}", ex);
  425. }
  426. }
  427. }
  428. }