CameraGroup.cs 20 KB

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