ProcessingAlgorithm_CCDShuLi.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using MvCameraControl;
  2. using MvvmScaffoldFrame48.DLL.ConfigTools;
  3. using MvvmScaffoldFrame48.DLL.LogTools;
  4. using MvvmScaffoldFrame48.DLL.SystemTools;
  5. using MvvmScaffoldFrame48.DLL.ThreadManager;
  6. using MvvmScaffoldFrame48.Model.StorageModel.ImageAlgorithm.ShuLI;
  7. using MvvmScaffoldFrame48.Model.StorageModel.Configs;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics;
  11. using System.Drawing;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MvvmScaffoldFrame48.DLL.ImageAlgorithm
  17. {
  18. public class ProcessingAlgorithm_CCDShuLi : IImageProcessingAlgorithmHikVision
  19. {
  20. private List<ActiveObjectClassModel> activeObjects = new List<ActiveObjectClassModel>(); // 当前跟踪中的物体
  21. private List<ActiveObjectClassModel> lostObjects = new List<ActiveObjectClassModel>();
  22. private List<ActiveObjectClassModel> historyActiveObjects = new List<ActiveObjectClassModel>(); // 历史物体
  23. BoundRectangleClass BoundRectangle = new BoundRectangleClass();
  24. private long currentLine = 0; //行数记录
  25. private int ObjectNum = 0;
  26. private int ChannelWidth = 0;//每个区域的宽度
  27. public int HistoryNum { get { return _HistoryNum; } }
  28. private int _HistoryNum = 0;
  29. public int HistoryOkNum { get { return _HistoryOkNum; } }
  30. private int _HistoryOkNum = 0;
  31. public int HistoryNgNum { get { return _HistoryNgNum; } }
  32. private int _HistoryNgNum = 0;
  33. private ShuLiConfigClassModel shuLiConfig = new ShuLiConfigClassModel();
  34. public List<int> ChannelsRoi { get { return _ChannelsRoi; } }
  35. private List<int> _ChannelsRoi = new List<int>();
  36. private bool IsPrintLightOnError = false;
  37. public string AlgorithmName => "ProcessingAlgorithm_CCDShuLi";
  38. public void Configure(string parameters)
  39. {
  40. var parameter = XMLReadWrite.DeserializeFromString<ShuLiConfigClassModel>(parameters);
  41. if (parameter != null)
  42. {
  43. shuLiConfig = parameter;
  44. }
  45. }
  46. public object GetParameters()
  47. {
  48. return shuLiConfig;
  49. }
  50. public string GetSaveJson()
  51. {
  52. return XMLReadWrite.SerializeToString(shuLiConfig);
  53. }
  54. public object ProcessImage(IFrameOut imageData, int cameraId)
  55. {
  56. bool result = ProcessImageSequence(imageData, out List<ActiveObjectClassModel> resultValue);
  57. if (result)
  58. {
  59. return resultValue;
  60. }
  61. else
  62. {
  63. return null;
  64. }
  65. }
  66. /// <summary>
  67. /// 处理图像序列的主入口
  68. /// </summary>
  69. /// <param name="image">图像像素数据</param>
  70. /// <param name="ImageWidth">图像宽</param>
  71. /// <param name="currentLine">当前行数</param>
  72. /// <returns>检测到的物体总数</returns>
  73. public bool ProcessImageSequence(IFrameOut image,out List<ActiveObjectClassModel> resultValue)
  74. {
  75. bool result = false;
  76. for (int i = 0; i < image.Image.Height; i++)
  77. {
  78. ProcessLine(image, i);
  79. currentLine += 1;
  80. }
  81. //识别到结果并输出
  82. // 清理超时未更新的物体
  83. lostObjects = activeObjects
  84. .Where(o => (currentLine - o.LastSeenLine) > shuLiConfig.MAX_GAP || (o.LastSeenLine - o.StartLine) > shuLiConfig.MAX_Idetify_Height)
  85. .ToList();
  86. lostObjects.ForEach(o => activeObjects.Remove(o));
  87. resultValue = new List<ActiveObjectClassModel>();
  88. // 有物体转变为活跃物体,返回值转为true
  89. if (lostObjects.Count > 0)
  90. {
  91. foreach (var item in lostObjects)
  92. {
  93. //噪点判定
  94. if (item.Area < shuLiConfig.NoiseFilter_Threshold)
  95. {
  96. item.StateCode = 9;
  97. //LOG.log(string.Format("噪点过滤,噪点面积:{0}", item.Area), 6);
  98. continue;
  99. }
  100. //转为历史物体,添加缺少的参数
  101. item.Num = Interlocked.Increment(ref ObjectNum);
  102. //item.ChannelNO = ActiveChannel(item);
  103. item.EndCheckTime = DateTime.Now;
  104. item.MaxLength = GetActionMaxLength(item.RowsData);
  105. item.PictureEndReadTime = TimeStampTools.FromUnixTimestamp((long)image.HostTimeStamp);
  106. var QutuYanshiTime = (DateTime.Now - item.PictureEndReadTime).TotalMilliseconds;
  107. if (QutuYanshiTime > 30)
  108. {
  109. Console.WriteLine($"结果输出延时超过了30ms,耗时{QutuYanshiTime}");
  110. }
  111. if ((item.LastSeenLine - item.StartLine) > shuLiConfig.MAX_Idetify_Height)
  112. {
  113. item.StateCode = 7;
  114. }
  115. else if (shuLiConfig.PandingCode != -1)
  116. {
  117. if (item.StateCode != -1)
  118. {
  119. if (item.StateCode == 8)
  120. {
  121. //TxtLog.log(string.Format("颗粒编号{0}:疑似叠片或缺损", item.Num));
  122. }
  123. }
  124. else if (item.Area < shuLiConfig.MinArea
  125. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 1))
  126. {
  127. item.StateCode = 5;
  128. }
  129. else if (item.Area > shuLiConfig.MaxArea
  130. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 1))
  131. {
  132. item.StateCode = 6;
  133. }
  134. else if (item.MaxLength < shuLiConfig.MIN_Object_LENGTH
  135. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 0))
  136. {
  137. item.StateCode = 2;
  138. }
  139. else if (item.MaxLength > shuLiConfig.MAX_Object_LENGTH
  140. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 0))
  141. {
  142. item.StateCode = 1;
  143. }
  144. else
  145. {
  146. item.StateCode = 0;
  147. }
  148. }
  149. resultValue.Add(item);
  150. }
  151. if (resultValue.Count > 0)
  152. {
  153. result = true;
  154. }
  155. }
  156. else
  157. {
  158. resultValue.Clear();
  159. }
  160. // 累加到总数并从活跃物体转移到历史物体
  161. resultValue.ForEach(o => TryAdd(historyActiveObjects, o, 2500));
  162. return result;
  163. }
  164. /// <summary>
  165. /// 处理单行像素数据
  166. /// 返回值为false的时候无活跃物体转变为历史物体
  167. /// 返回值为true的时候有活跃物体转变为历史物体
  168. /// </summary>
  169. /// <param name="image">当前行像素数组</param>
  170. private bool ProcessLine(IFrameOut imagedata, int RowNo)
  171. {
  172. Stopwatch stopwatch = Stopwatch.StartNew();
  173. bool result = false;
  174. // 步骤1:检测当前行的有效区域
  175. var currentRegions = FindValidRegions(imagedata.Image, RowNo);
  176. if (currentRegions.Count == 1)
  177. {
  178. if (currentRegions[0].End - (currentRegions[0]).Start + 1 == imagedata.Image.Width)
  179. {
  180. if (!IsPrintLightOnError)
  181. {
  182. //FaultLog.RecordLogMessage("当前行有效区域为整行,检查视野和光源", 5);
  183. IsPrintLightOnError = true;
  184. }
  185. return false;
  186. }
  187. }
  188. IsPrintLightOnError = false;
  189. stopwatch.Stop();
  190. if (stopwatch.ElapsedMilliseconds > 1)
  191. {
  192. //FaultLog.RecordErrorMessage($"ShuLiClass-ProcessLine:图像连通域检测超时,此次识别耗时:{stopwatch.Elapsed}");
  193. }
  194. stopwatch.Restart();
  195. //lock (_lockObj)
  196. //{
  197. foreach (var region in currentRegions)
  198. {
  199. // 查找全部可合并的活跃物体(有重叠+在允许间隔内)
  200. var matcheds = activeObjects.Where(o =>
  201. IsOverlapping(o, region) &&
  202. (currentLine - o.LastSeenLine - 1) <= shuLiConfig.MAX_GAP).ToList();
  203. //当有多个可合并的活跃物体时,将多个物体合并
  204. if (matcheds.Count >= 2)
  205. {
  206. // 合并有效区域队列
  207. var CopeRowsData = new List<RowStartEndColModel>();
  208. matcheds.ForEach(o => CopeRowsData = CopeRowsData.Concat(o.RowsData).ToList());
  209. // 合并有效区域并保存在新的区域中
  210. var MergeMatched = new ActiveObjectClassModel
  211. {
  212. MinStartCol = matcheds.Min(o => o.MinStartCol),
  213. MaxEndCol = matcheds.Max(o => o.MaxEndCol),
  214. StartLine = matcheds.Min(o => o.StartLine),
  215. LastSeenLine = matcheds.Max(o => o.LastSeenLine),
  216. LastSeenLineStartCol = matcheds.Min(o => o.LastSeenLineStartCol),
  217. LastSeenLineEndCol = matcheds.Max(o => o.LastSeenLineEndCol),
  218. StartCheckTime = matcheds.Min(o => o.StartCheckTime),
  219. EndCheckTime = matcheds.Max(o => o.EndCheckTime),
  220. PictureStartReadTime = matcheds.Min(o=>o.PictureStartReadTime),
  221. Area = matcheds.Sum(o => o.Area),
  222. RowsData = CopeRowsData,
  223. ImageWidth = matcheds.FirstOrDefault().ImageWidth,
  224. //StateCode = 8
  225. };
  226. // 从活跃区域中删除被合并的区域
  227. matcheds.ForEach(o => activeObjects.Remove(o));
  228. // 保存新的区域到活跃区域中
  229. activeObjects.Add(MergeMatched);
  230. }
  231. // 搜获可用且可合并的活跃区域
  232. var matched = activeObjects.FirstOrDefault(o =>
  233. IsOverlapping(o, region) &&
  234. (currentLine - o.LastSeenLine - 1) <= shuLiConfig.MAX_GAP);
  235. if (matched != null)
  236. {
  237. // 合并区域:扩展物体边界并更新状态
  238. matched.MinStartCol = Math.Min(matched.MinStartCol, region.Start);
  239. matched.MaxEndCol = Math.Max(matched.MaxEndCol, region.End);
  240. matched.Area += region.End - region.Start + 1;
  241. matched.LastSeenLine = currentLine;
  242. matched.RowsData.Add(new RowStartEndColModel
  243. {
  244. StartCol = region.Start,
  245. EndCol = region.End,
  246. RowsCol = currentLine,
  247. });
  248. matched.LastSeenLineStartCol = region.Start;
  249. matched.LastSeenLineEndCol = region.End;
  250. }
  251. else
  252. {
  253. // 创建新物体(首次出现的区域)
  254. activeObjects.Add(new ActiveObjectClassModel
  255. {
  256. MinStartCol = region.Start,
  257. MaxEndCol = region.End,
  258. StartLine = currentLine,
  259. LastSeenLine = currentLine,
  260. LastSeenLineStartCol = region.Start,
  261. LastSeenLineEndCol = region.End,
  262. StartCheckTime = DateTime.Now,
  263. PictureStartReadTime = TimeStampTools.FromUnixTimestamp((long)imagedata.HostTimeStamp),
  264. Area = region.End - region.Start + 1,
  265. ImageWidth = shuLiConfig.ImageWidth,
  266. RowsData = new List<RowStartEndColModel> {
  267. new RowStartEndColModel {
  268. StartCol = region.Start,
  269. EndCol = region.End,
  270. RowsCol = currentLine,
  271. }
  272. }
  273. });
  274. }
  275. }
  276. //}
  277. stopwatch.Stop();
  278. if (stopwatch.ElapsedMilliseconds > 1)
  279. {
  280. //FaultLog.RecordErrorMessage($"ShuLiClass-ProcessLine:图像区域合并超时,此次识别耗时:{stopwatch.Elapsed}");
  281. }
  282. currentRegions.Clear();
  283. return result;
  284. }
  285. List<ValidRegionModel> regions = new List<ValidRegionModel>();
  286. /// <summary>
  287. /// 检测有效物体区域(横向连续黑色像素段)
  288. /// </summary>
  289. /// <param name="line">当前行像素数组</param>
  290. /// <returns>有效区域列表(起始/结束位置)</returns>
  291. private List<ValidRegionModel> FindValidRegions(IImage image, int RowNo)
  292. {
  293. regions.Clear();
  294. int start = -1; // 当前区域起始标记
  295. int end = -1;
  296. // 遍历所有像素列
  297. if (shuLiConfig.IsIdentifyRoiOpen)
  298. {
  299. for (int i = (int)image.Width * RowNo + shuLiConfig.IdentifyStartX; i < (int)image.Width * RowNo + shuLiConfig.IdentifyStopX; i++)
  300. {
  301. if (image.PixelData[i] < shuLiConfig.RegionThreshold) // 发现黑色像素
  302. {
  303. if (start == -1) start = i % (int)image.Width; // 开始新区域
  304. }
  305. else if (start != -1) // 遇到白色像素且存在进行中的区域
  306. {
  307. end = (i - 1) % (int)image.Width;
  308. // 检查区域宽度是否达标
  309. if (end - start >= shuLiConfig.NoiseFilter_Threshold)
  310. {
  311. regions.Add(new ValidRegionModel()
  312. {
  313. Start = start,
  314. End = end
  315. }); // 记录有效区域
  316. }
  317. start = -1; // 重置区域标记
  318. end = -1;
  319. }
  320. }
  321. }
  322. else
  323. {
  324. for (int i = (int)image.Width * RowNo; i < (int)image.Width * (RowNo + 1); i++)
  325. {
  326. if (image.PixelData[i] < shuLiConfig.RegionThreshold) // 发现黑色像素
  327. {
  328. if (start == -1) start = i % (int)image.Width; // 开始新区域
  329. }
  330. else if (start != -1) // 遇到白色像素且存在进行中的区域
  331. {
  332. end = (i - 1) % (int)image.Width;
  333. // 检查区域宽度是否达标
  334. if (end - start >= shuLiConfig.NoiseFilter_Threshold)
  335. {
  336. regions.Add(new ValidRegionModel()
  337. {
  338. Start = start,
  339. End = end
  340. }); // 记录有效区域
  341. }
  342. start = -1; // 重置区域标记
  343. end = -1;
  344. }
  345. }
  346. }
  347. // 处理行尾未闭合的区域
  348. if (start != -1 && image.Width - start >= shuLiConfig.NoiseFilter_Threshold)
  349. {
  350. regions.Add(new ValidRegionModel()
  351. {
  352. Start = start,
  353. End = (int)image.Width - 1
  354. });
  355. }
  356. return regions;
  357. }
  358. /// <summary>
  359. /// 判断区域重叠(与活跃物体的横向坐标重叠检测)
  360. /// </summary>
  361. /// <param name="obj">活跃物体</param>
  362. /// <param name="region">当前区域</param>
  363. /// <returns>是否发生重叠</returns>
  364. private bool IsOverlapping(ActiveObjectClassModel obj, ValidRegionModel region)
  365. {
  366. // 判断区域是否不相交的逆条件
  367. return !(region.End < obj.LastSeenLineStartCol || region.Start > obj.LastSeenLineEndCol);
  368. }
  369. /// <summary>
  370. /// 历史数据队列添加数据
  371. /// </summary>
  372. /// <param name="list">历史数据队列</param>
  373. /// <param name="item">添加的数据</param>
  374. /// <param name="maxSize">队列最大数据量</param>
  375. /// <returns></returns>
  376. private bool TryAdd(List<ActiveObjectClassModel> list, ActiveObjectClassModel item, int maxSize)
  377. {
  378. list.Add(item);
  379. Interlocked.Increment(ref _HistoryNum);
  380. if(item.StateCode == 0)
  381. {
  382. Interlocked.Increment(ref _HistoryOkNum);
  383. }
  384. else
  385. {
  386. Interlocked.Increment(ref _HistoryNgNum);
  387. }
  388. if (list.Count > maxSize)
  389. {
  390. list.Remove(list[list.Count - maxSize]);
  391. }
  392. return true;
  393. }
  394. /// <summary>
  395. /// 获取结果最长长边
  396. /// </summary>
  397. /// <param name="Rows"></param>
  398. /// <returns></returns>
  399. private double GetActionMaxLength(List<RowStartEndColModel> Rows)
  400. {
  401. //外轮廓点集
  402. List<Point> points = Rows.Select(o => new Point(o.StartCol, (int)o.RowsCol)).ToList();
  403. points.AddRange(Rows.Select(o => new Point(o.EndCol, (int)o.RowsCol)).ToList());
  404. //获取凸包点集
  405. points = BoundRectangle.ConvexHull(points);
  406. //获取凸包长度最长的外接矩形
  407. var result = BoundRectangle.RotatingCalipers(points);
  408. if (result != null)
  409. {
  410. return result.Height;
  411. }
  412. else
  413. {
  414. return 0;
  415. }
  416. }
  417. /// <summary>
  418. /// 通道区域判定
  419. /// </summary>
  420. /// <param name="activeObject"></param>
  421. /// <returns></returns>
  422. private int ActiveChannel(ActiveObjectClassModel activeObject)
  423. {
  424. int result = -1;
  425. int StartChannel = activeObject.MinStartCol / ChannelWidth;
  426. int EndChannel = activeObject.MaxEndCol / ChannelWidth;
  427. if (StartChannel == EndChannel)
  428. {
  429. result = StartChannel;
  430. }
  431. else if (EndChannel - StartChannel > 1)
  432. {
  433. Console.WriteLine("ActiveChannel-Error");
  434. //error
  435. }
  436. else
  437. {
  438. result = _ChannelsRoi[StartChannel] - activeObject.MinStartCol > activeObject.MaxEndCol - _ChannelsRoi[StartChannel] ? StartChannel : EndChannel;
  439. }
  440. return result;
  441. }
  442. }
  443. }