ProcessingAlgorithm_CCDShuLi.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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.ProcessingConfig;
  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. //FaultLog.RecordLogMessage("ShuLiClass-ProcessLine:非颗粒,视野异常", 3);
  115. //TxtLog.log(string.Format("ShuLiClass-ProcessLine:非颗粒,视野异常"), 6);
  116. //Console.WriteLine("ShuLiClass-ProcessLine:非颗粒,视野异常");
  117. }
  118. else if (shuLiConfig.PandingCode != -1)
  119. {
  120. if (item.StateCode != -1)
  121. {
  122. if (item.StateCode == 8)
  123. {
  124. //TxtLog.log(string.Format("颗粒编号{0}:疑似叠片或缺损", item.Num));
  125. }
  126. }
  127. else if (item.Area < shuLiConfig.MinArea
  128. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 1))
  129. {
  130. item.StateCode = 5;
  131. //TxtLog.log(string.Format("颗粒编号{0}:面积过小", item.Num));
  132. //Console.WriteLine("颗粒编号{0}:面积过小", item.Num);
  133. }
  134. else if (item.Area > shuLiConfig.MaxArea
  135. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 1))
  136. {
  137. item.StateCode = 6;
  138. //TxtLog.log(string.Format("颗粒编号{0}:面积过大", item.Num));
  139. //Console.WriteLine("颗粒编号{0}:面积过大", item.Num);
  140. }
  141. else if (item.MaxLength < shuLiConfig.MIN_Object_LENGTH
  142. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 0))
  143. {
  144. item.StateCode = 2;
  145. //TxtLog.log(string.Format("颗粒编号{0}:超短粒", item.Num));
  146. //Console.WriteLine("颗粒编号{0}:超短粒", item.Num);
  147. }
  148. else if (item.MaxLength > shuLiConfig.MAX_Object_LENGTH
  149. && (shuLiConfig.PandingCode == 2 || shuLiConfig.PandingCode == 0))
  150. {
  151. item.StateCode = 1;
  152. //TxtLog.log(string.Format("颗粒编号{0}:超长粒", item.Num));
  153. //Console.WriteLine("颗粒编号{0}:超长粒", item.Num);
  154. }
  155. else
  156. {
  157. item.StateCode = 0;
  158. //TxtLog.log(string.Format("颗粒编号{0}:正常粒", item.Num));
  159. //Console.WriteLine("颗粒编号{0}:正常粒", item.Num);
  160. }
  161. }
  162. resultValue.Add(item);
  163. }
  164. if (resultValue.Count > 0)
  165. {
  166. result = true;
  167. //LOG.log(string.Format("识别完成,首个颗粒编号:{0},颗粒数量:{1}", OneActive[0].Num, OneActive.Count), 6);
  168. //触发回调事件
  169. //Task.Run(() =>
  170. //{
  171. // OnWorkCompleted(OneActive);
  172. //});
  173. //ThreadPool.QueueUserWorkItem(_ => OnWorkCompleted(OneActive));
  174. }
  175. }
  176. else
  177. {
  178. resultValue.Clear();
  179. }
  180. // 累加到总数并从活跃物体转移到历史物体
  181. resultValue.ForEach(o => TryAdd(historyActiveObjects, o, 2500));
  182. return result;
  183. }
  184. /// <summary>
  185. /// 处理单行像素数据
  186. /// 返回值为false的时候无活跃物体转变为历史物体
  187. /// 返回值为true的时候有活跃物体转变为历史物体
  188. /// </summary>
  189. /// <param name="image">当前行像素数组</param>
  190. private bool ProcessLine(IFrameOut imagedata, int RowNo)
  191. {
  192. Stopwatch stopwatch = Stopwatch.StartNew();
  193. bool result = false;
  194. // 步骤1:检测当前行的有效区域
  195. var currentRegions = FindValidRegions(imagedata.Image, RowNo);
  196. if (currentRegions.Count == 1)
  197. {
  198. if (currentRegions[0].End - (currentRegions[0]).Start + 1 == imagedata.Image.Width)
  199. {
  200. if (!IsPrintLightOnError)
  201. {
  202. //FaultLog.RecordLogMessage("当前行有效区域为整行,检查视野和光源", 5);
  203. IsPrintLightOnError = true;
  204. }
  205. return false;
  206. }
  207. }
  208. IsPrintLightOnError = false;
  209. stopwatch.Stop();
  210. if (stopwatch.ElapsedMilliseconds > 1)
  211. {
  212. //FaultLog.RecordErrorMessage($"ShuLiClass-ProcessLine:图像连通域检测超时,此次识别耗时:{stopwatch.Elapsed}");
  213. }
  214. stopwatch.Restart();
  215. //lock (_lockObj)
  216. //{
  217. foreach (var region in currentRegions)
  218. {
  219. // 查找全部可合并的活跃物体(有重叠+在允许间隔内)
  220. var matcheds = activeObjects.Where(o =>
  221. IsOverlapping(o, region) &&
  222. (currentLine - o.LastSeenLine - 1) <= shuLiConfig.MAX_GAP).ToList();
  223. //当有多个可合并的活跃物体时,将多个物体合并
  224. if (matcheds.Count >= 2)
  225. {
  226. // 合并有效区域队列
  227. var CopeRowsData = new List<RowStartEndColModel>();
  228. matcheds.ForEach(o => CopeRowsData = CopeRowsData.Concat(o.RowsData).ToList());
  229. // 合并有效区域并保存在新的区域中
  230. var MergeMatched = new ActiveObjectClassModel
  231. {
  232. MinStartCol = matcheds.Min(o => o.MinStartCol),
  233. MaxEndCol = matcheds.Max(o => o.MaxEndCol),
  234. StartLine = matcheds.Min(o => o.StartLine),
  235. LastSeenLine = matcheds.Max(o => o.LastSeenLine),
  236. LastSeenLineStartCol = matcheds.Min(o => o.LastSeenLineStartCol),
  237. LastSeenLineEndCol = matcheds.Max(o => o.LastSeenLineEndCol),
  238. StartCheckTime = matcheds.Min(o => o.StartCheckTime),
  239. EndCheckTime = matcheds.Max(o => o.EndCheckTime),
  240. PictureStartReadTime = matcheds.Min(o=>o.PictureStartReadTime),
  241. Area = matcheds.Sum(o => o.Area),
  242. RowsData = CopeRowsData,
  243. ImageWidth = matcheds.FirstOrDefault().ImageWidth,
  244. //StateCode = 8
  245. };
  246. // 从活跃区域中删除被合并的区域
  247. matcheds.ForEach(o => activeObjects.Remove(o));
  248. // 保存新的区域到活跃区域中
  249. activeObjects.Add(MergeMatched);
  250. }
  251. // 搜获可用且可合并的活跃区域
  252. var matched = activeObjects.FirstOrDefault(o =>
  253. IsOverlapping(o, region) &&
  254. (currentLine - o.LastSeenLine - 1) <= shuLiConfig.MAX_GAP);
  255. if (matched != null)
  256. {
  257. // 合并区域:扩展物体边界并更新状态
  258. matched.MinStartCol = Math.Min(matched.MinStartCol, region.Start);
  259. matched.MaxEndCol = Math.Max(matched.MaxEndCol, region.End);
  260. matched.Area += region.End - region.Start + 1;
  261. matched.LastSeenLine = currentLine;
  262. matched.RowsData.Add(new RowStartEndColModel
  263. {
  264. StartCol = region.Start,
  265. EndCol = region.End,
  266. RowsCol = currentLine,
  267. });
  268. matched.LastSeenLineStartCol = region.Start;
  269. matched.LastSeenLineEndCol = region.End;
  270. }
  271. else
  272. {
  273. // 创建新物体(首次出现的区域)
  274. activeObjects.Add(new ActiveObjectClassModel
  275. {
  276. MinStartCol = region.Start,
  277. MaxEndCol = region.End,
  278. StartLine = currentLine,
  279. LastSeenLine = currentLine,
  280. LastSeenLineStartCol = region.Start,
  281. LastSeenLineEndCol = region.End,
  282. StartCheckTime = DateTime.Now,
  283. PictureStartReadTime = TimeStampTools.FromUnixTimestamp((long)imagedata.HostTimeStamp),
  284. Area = region.End - region.Start + 1,
  285. ImageWidth = shuLiConfig.ImageWidth,
  286. RowsData = new List<RowStartEndColModel> {
  287. new RowStartEndColModel {
  288. StartCol = region.Start,
  289. EndCol = region.End,
  290. RowsCol = currentLine,
  291. }
  292. }
  293. });
  294. }
  295. }
  296. //}
  297. stopwatch.Stop();
  298. if (stopwatch.ElapsedMilliseconds > 1)
  299. {
  300. //FaultLog.RecordErrorMessage($"ShuLiClass-ProcessLine:图像区域合并超时,此次识别耗时:{stopwatch.Elapsed}");
  301. }
  302. currentRegions.Clear();
  303. return result;
  304. }
  305. List<ValidRegionModel> regions = new List<ValidRegionModel>();
  306. /// <summary>
  307. /// 检测有效物体区域(横向连续黑色像素段)
  308. /// </summary>
  309. /// <param name="line">当前行像素数组</param>
  310. /// <returns>有效区域列表(起始/结束位置)</returns>
  311. private List<ValidRegionModel> FindValidRegions(IImage image, int RowNo)
  312. {
  313. regions.Clear();
  314. int start = -1; // 当前区域起始标记
  315. int end = -1;
  316. // 遍历所有像素列
  317. if (shuLiConfig.IsIdentifyRoiOpen)
  318. {
  319. for (int i = (int)image.Width * RowNo + shuLiConfig.IdentifyStartX; i < (int)image.Width * RowNo + shuLiConfig.IdentifyStopX; i++)
  320. {
  321. if (image.PixelData[i] < shuLiConfig.RegionThreshold) // 发现黑色像素
  322. {
  323. if (start == -1) start = i % (int)image.Width; // 开始新区域
  324. }
  325. else if (start != -1) // 遇到白色像素且存在进行中的区域
  326. {
  327. end = (i - 1) % (int)image.Width;
  328. // 检查区域宽度是否达标
  329. if (end - start >= shuLiConfig.NoiseFilter_Threshold)
  330. {
  331. regions.Add(new ValidRegionModel()
  332. {
  333. Start = start,
  334. End = end
  335. }); // 记录有效区域
  336. }
  337. start = -1; // 重置区域标记
  338. end = -1;
  339. }
  340. }
  341. }
  342. else
  343. {
  344. for (int i = (int)image.Width * RowNo; i < (int)image.Width * (RowNo + 1); i++)
  345. {
  346. if (image.PixelData[i] < shuLiConfig.RegionThreshold) // 发现黑色像素
  347. {
  348. if (start == -1) start = i % (int)image.Width; // 开始新区域
  349. }
  350. else if (start != -1) // 遇到白色像素且存在进行中的区域
  351. {
  352. end = (i - 1) % (int)image.Width;
  353. // 检查区域宽度是否达标
  354. if (end - start >= shuLiConfig.NoiseFilter_Threshold)
  355. {
  356. regions.Add(new ValidRegionModel()
  357. {
  358. Start = start,
  359. End = end
  360. }); // 记录有效区域
  361. }
  362. start = -1; // 重置区域标记
  363. end = -1;
  364. }
  365. }
  366. }
  367. // 处理行尾未闭合的区域
  368. if (start != -1 && image.Width - start >= shuLiConfig.NoiseFilter_Threshold)
  369. {
  370. regions.Add(new ValidRegionModel()
  371. {
  372. Start = start,
  373. End = (int)image.Width - 1
  374. });
  375. }
  376. return regions;
  377. }
  378. /// <summary>
  379. /// 判断区域重叠(与活跃物体的横向坐标重叠检测)
  380. /// </summary>
  381. /// <param name="obj">活跃物体</param>
  382. /// <param name="region">当前区域</param>
  383. /// <returns>是否发生重叠</returns>
  384. private bool IsOverlapping(ActiveObjectClassModel obj, ValidRegionModel region)
  385. {
  386. // 判断区域是否不相交的逆条件
  387. return !(region.End < obj.LastSeenLineStartCol || region.Start > obj.LastSeenLineEndCol);
  388. }
  389. /// <summary>
  390. /// 历史数据队列添加数据
  391. /// </summary>
  392. /// <param name="list">历史数据队列</param>
  393. /// <param name="item">添加的数据</param>
  394. /// <param name="maxSize">队列最大数据量</param>
  395. /// <returns></returns>
  396. private bool TryAdd(List<ActiveObjectClassModel> list, ActiveObjectClassModel item, int maxSize)
  397. {
  398. list.Add(item);
  399. Interlocked.Increment(ref _HistoryNum);
  400. if(item.StateCode == 0)
  401. {
  402. Interlocked.Increment(ref _HistoryOkNum);
  403. }
  404. else
  405. {
  406. Interlocked.Increment(ref _HistoryNgNum);
  407. }
  408. if (list.Count > maxSize)
  409. {
  410. list.Remove(list[list.Count - maxSize]);
  411. }
  412. return true;
  413. }
  414. /// <summary>
  415. /// 获取结果最长长边
  416. /// </summary>
  417. /// <param name="Rows"></param>
  418. /// <returns></returns>
  419. private double GetActionMaxLength(List<RowStartEndColModel> Rows)
  420. {
  421. //外轮廓点集
  422. List<Point> points = Rows.Select(o => new Point(o.StartCol, (int)o.RowsCol)).ToList();
  423. points.AddRange(Rows.Select(o => new Point(o.EndCol, (int)o.RowsCol)).ToList());
  424. //获取凸包点集
  425. points = BoundRectangle.ConvexHull(points);
  426. //获取凸包长度最长的外接矩形
  427. var result = BoundRectangle.RotatingCalipers(points);
  428. if (result != null)
  429. {
  430. return result.Height;
  431. }
  432. else
  433. {
  434. return 0;
  435. }
  436. }
  437. /// <summary>
  438. /// 通道区域判定
  439. /// </summary>
  440. /// <param name="activeObject"></param>
  441. /// <returns></returns>
  442. private int ActiveChannel(ActiveObjectClassModel activeObject)
  443. {
  444. int result = -1;
  445. int StartChannel = activeObject.MinStartCol / ChannelWidth;
  446. int EndChannel = activeObject.MaxEndCol / ChannelWidth;
  447. if (StartChannel == EndChannel)
  448. {
  449. result = StartChannel;
  450. }
  451. else if (EndChannel - StartChannel > 1)
  452. {
  453. Console.WriteLine("ActiveChannel-Error");
  454. //error
  455. }
  456. else
  457. {
  458. result = _ChannelsRoi[StartChannel] - activeObject.MinStartCol > activeObject.MaxEndCol - _ChannelsRoi[StartChannel] ? StartChannel : EndChannel;
  459. }
  460. return result;
  461. }
  462. }
  463. }