InfraredLocate.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. using DbscanImplementation;
  2. using o0;
  3. using o0.Project;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Runtime.Serialization.Formatters;
  8. using System.Threading.Tasks;
  9. using UnityEngine;
  10. using UnityEngine.UI;
  11. using ZIM.Unity;
  12. using Color = UnityEngine.Color;
  13. using Debug = UnityEngine.Debug;
  14. namespace ZIM
  15. {
  16. public enum InfraredMatch
  17. {
  18. Nomatch = 0,
  19. Match0 = 1,
  20. Match1 = 2
  21. }
  22. // 支持2个红外点的识别
  23. public class InfraredLocate
  24. {
  25. public static object locker = new object();
  26. public static List<InfraredMatch> GetMatches(InfraredMatch im)
  27. {
  28. List<InfraredMatch> positions = new List<InfraredMatch>();
  29. InfraredMatch bit = InfraredMatch.Match0;
  30. while (bit <= im)
  31. {
  32. if ((im & bit) != 0)
  33. {
  34. positions.Add(bit);
  35. }
  36. bit = (InfraredMatch)((int)bit << 1);
  37. }
  38. return positions;
  39. }
  40. readonly float[] spotBrightness = new float[] { 0.93f, 0.5f }; // 亮点阈值
  41. int _samplingScale = 1;
  42. public int SamplingScale
  43. {
  44. get => _samplingScale;
  45. set
  46. {
  47. if (value <= 0)
  48. throw new InvalidOperationException();
  49. _samplingScale = value;
  50. PixelSpotArea.UpdateGridLength(value);
  51. }
  52. }
  53. //const float circleVariance = 30f;
  54. //const int brightAreaRadius = 30;
  55. //const int LeastBrightPoint = 10000;
  56. SLAMUVC.UVCManager.CameraInfo mCameraInfo;
  57. ScreenIdentification screenIdentification;
  58. InfraredSpotSettings infraredSpotSettings;
  59. //KMeans kMeans;
  60. PixelCheaker ScreenPixelCheaker;
  61. InfraredSpot[] InfraredSpots;
  62. public InfraredSpot GetSpot(InfraredMatch match)
  63. {
  64. switch (match)
  65. {
  66. case InfraredMatch.Match0:
  67. return InfraredSpots[0];
  68. case InfraredMatch.Match1:
  69. return InfraredSpots[1];
  70. default:
  71. return null;
  72. }
  73. }
  74. // 参数是 红外灯的亮度阈值,阈值越小能够检测到的亮度就越低
  75. public void SetBrightnessThreshold(float brightnessThreshold = 0.93f)
  76. {
  77. spotBrightness[0] = brightnessThreshold; spotBrightness[1] = (float)Math.Min(Math.Exp(1.5 * brightnessThreshold - 1.8), brightnessThreshold); // 周围泛光的亮度用指数函数直接算
  78. }
  79. public InfraredLocate(SLAMUVC.UVCManager.CameraInfo cameraInfo, ScreenIdentification infraredIdentification, InfraredSpotSettings infraredSpotSettings, PixelCheaker screenPixelCheaker)
  80. {
  81. this.mCameraInfo = cameraInfo;
  82. this.screenIdentification = infraredIdentification;
  83. this.infraredSpotSettings = infraredSpotSettings;
  84. this.ScreenPixelCheaker = screenPixelCheaker;
  85. //this.kMeans = new KMeans();
  86. //samplingScale = 2;
  87. }
  88. readonly int CheakFrame = 10;
  89. bool Infrared12Overlap = false;
  90. int cheakCounter = 0;
  91. public InfraredSpot[] UpdateSingle(Color[] cameraPixels)
  92. {
  93. // Debug.Log(cameraPixels.Length + ", " + screenIdentification.Screen.QuadRect + " -----------------");
  94. var spotArea = LocateToScreen(cameraPixels, screenIdentification.Screen.QuadRect);
  95. return MatchInfraredRaySingle(spotArea);
  96. }
  97. // New, 通过透视映射计算红外点的相对位置, 返回的红外点根据半径 从大到小排序
  98. public InfraredSpot[] Update(Color[] cameraPixels)
  99. {
  100. var spotArea = LocateToScreen(cameraPixels, screenIdentification.Screen.QuadRect);
  101. return MatchInfraredRay(spotArea);
  102. }
  103. // New, 返回由大到小排序的点
  104. public List<ISpotArea> LocateToScreen(Color[] pixels, Rect rect)
  105. {
  106. if (!screenIdentification.Screen.Active)
  107. rect = new Rect(0, 0, screenIdentification.Size.x, screenIdentification.Size.y);
  108. if (InfraredSpots == null)
  109. {
  110. InfraredSpots = new InfraredSpot[2] {
  111. new InfraredSpot(screenIdentification.Screen, InfraredMatch.Match0),
  112. new InfraredSpot(screenIdentification.Screen, InfraredMatch.Match1) };
  113. }
  114. //var watch = new System.Diagnostics.Stopwatch();
  115. //watch.Start();
  116. //var times = new List<double>() { 0.0 };
  117. (int x, int y) rectMin = ((int)rect.min.x / SamplingScale, (int)rect.min.y / SamplingScale);
  118. (int x, int y) rectMax = ((int)rect.max.x / SamplingScale, (int)rect.max.y / SamplingScale);
  119. var spotPoint = new List<Vector2>(100); // 预估的初始容量
  120. var brightPoint = new List<Vector2>(500);
  121. Parallel.For(rectMin.x, rectMax.x, (i) =>
  122. {
  123. var points0 = new List<Vector2>(rectMax.y - rectMin.y);
  124. var points1 = new List<Vector2>(rectMax.y - rectMin.y);
  125. for (int j = rectMin.y; j < rectMax.y; j++)
  126. {
  127. int ip = i * SamplingScale;
  128. int jp = j * SamplingScale;
  129. if (!screenIdentification.Screen.Active && ScreenPixelCheaker.OutArea2D(new Vector2(ip, jp), screenIdentification.Size))
  130. continue;
  131. var index = mCameraInfo.CoordToIndex(ip, jp);
  132. //var b = brightness[index];
  133. //var b = (int)Math.Round(ConvBrightness(brightness, (ip, jp)));
  134. var b = pixels[index].Brightness();
  135. if (b > spotBrightness[0])
  136. {
  137. points0.Add(new Vector2(ip, jp));
  138. }
  139. else if (b > spotBrightness[1])
  140. {
  141. points1.Add(new Vector2(ip, jp));
  142. }
  143. }
  144. lock (spotPoint)
  145. {
  146. spotPoint.AddRange(points0);
  147. brightPoint.AddRange(points1);
  148. }
  149. });
  150. //if (ScreenLocate.Main.DebugOnZIMDemo)
  151. {
  152. float maxPoints = 200; // 如果亮点太多,通过间隔采样控制亮点在一定数量以内
  153. if (spotPoint.Count > maxPoints)
  154. {
  155. SamplingScale = (int)Math.Ceiling(SamplingScale * Math.Sqrt(spotPoint.Count / maxPoints));
  156. return new List<ISpotArea>();
  157. }
  158. else if (SamplingScale > 1 && spotPoint.Count < maxPoints * 0.2f)
  159. {
  160. SamplingScale = Math.Max((int)Math.Ceiling(SamplingScale * Math.Sqrt(spotPoint.Count / maxPoints * 3)), 1);
  161. return new List<ISpotArea>();
  162. }
  163. }
  164. //times.Add(watch.ElapsedMilliseconds);
  165. //UnityEngine.Debug.Log("time1: " + (times[times.Count - 1] - times[times.Count - 2]));
  166. //Parallel.For(0, spotPoint.Count, (i) => spotPoint[i] = screenIdentification.Screen.TransformToScreen(spotPoint[i]));
  167. //Parallel.For(0, brightPoint.Count, (i) => brightPoint[i] = screenIdentification.Screen.TransformToScreen(brightPoint[i]));
  168. // 筛掉屏幕外的点
  169. if (screenIdentification.Screen.Active)
  170. {
  171. var temp0 = new List<Vector2>(spotPoint.Count);
  172. var temp1 = new List<Vector2>(spotPoint.Count);
  173. foreach (var p in spotPoint)
  174. {
  175. var pS = screenIdentification.Screen.TransformToScreen(p);
  176. if (screenIdentification.Screen.UVInScreen(pS))
  177. temp0.Add(p);
  178. }
  179. foreach (var p in brightPoint)
  180. {
  181. var pS = screenIdentification.Screen.TransformToScreen(p);
  182. if (screenIdentification.Screen.UVInScreen(pS))
  183. temp1.Add(p);
  184. }
  185. spotPoint = temp0;
  186. brightPoint = temp1;
  187. }
  188. //times.Add(watch.ElapsedMilliseconds);
  189. //UnityEngine.Debug.Log("time2: " + (times[times.Count - 1] - times[times.Count - 2]));
  190. // 聚类算法,得到结果
  191. if (spotPoint.Count > 0)
  192. {
  193. var db = Dbscan.Run(spotPoint, ZIM.Unity.ZIMMath.LengthManhattan, SamplingScale, 4);
  194. var spotArea = DbscanToSpotAreas(db, brightPoint);
  195. //var spotArea = PixelSpotArea.Cluster(spotPoint, brightPoint, screenIdentification.Screen.UVInScreen);
  196. //times.Add(watch.ElapsedMilliseconds);
  197. //UnityEngine.Debug.Log("time3: " + (times[times.Count - 1] - times[times.Count - 2]));
  198. //半径和中心按透视调整
  199. if (screenIdentification.Screen.Active)
  200. {
  201. foreach (var i in spotArea)
  202. {
  203. var center = i.Centroid;
  204. var offset1 = center + new Vector2(i.Radius, 0);
  205. var offset2 = center - new Vector2(i.Radius, 0);
  206. var offset3 = center + new Vector2(0, i.Radius);
  207. var offset4 = center - new Vector2(0, i.Radius);
  208. var transC = screenIdentification.Screen.TransformToScreen(i.Centroid);
  209. var transR = ((screenIdentification.Screen.TransformToScreen(offset1) - screenIdentification.Screen.TransformToScreen(offset2)).magnitude +
  210. (screenIdentification.Screen.TransformToScreen(offset3) - screenIdentification.Screen.TransformToScreen(offset4)).magnitude) / 4;
  211. //var r0 = i.Radius / mCameraInfo.CurrentWidth;
  212. //var r1 = transR / screenIdentification.Screen.UVSize.x;
  213. //i.Radius *= (float)Math.Pow(r1 / r0, 2); // 摄像机位置不同参数也可能不同
  214. i.Centroid = transC;
  215. i.Radius = transR;
  216. }
  217. }
  218. //times.Add(watch.ElapsedMilliseconds);
  219. //UnityEngine.Debug.Log("time4: " + (times[times.Count - 1] - times[times.Count - 2]));
  220. if (ScreenLocate.Main.DebugOnZIMDemo)
  221. DebugAreas(spotArea);
  222. return spotArea;
  223. //// 排序亮区
  224. //spotArea.Sort((a, b) => b.MaxRadius.CompareTo(a.MaxRadius));
  225. ////var areas = new SortedList<float, ISpotArea>(new DescendingComparer<float>());
  226. ////foreach (var i in spotArea)
  227. //// areas.Add(i.MaxRadius, i);
  228. //var result = new Vector2[spotArea.Count];
  229. //foreach (var i in spotArea.Index())
  230. // result[i] = spotArea[i].Center;
  231. //times.Add(watch.ElapsedMilliseconds);
  232. //UnityEngine.Debug.Log("time6: " + (times[times.Count - 1] - times[times.Count - 2]));
  233. //return result;
  234. }
  235. return new List<ISpotArea>();
  236. }
  237. private void DebugAreas(List<ISpotArea> areas)
  238. {
  239. var debugText = $"当前相机分辨率: {ScreenLocate.Main.CameraSize}";
  240. debugText += $"\r\nareas.Count: {areas.Count}";
  241. ISpotArea a0 = null; // 表示最大半径的区域
  242. ISpotArea a1 = null; // 表示第二大半径的区域
  243. foreach (var a in areas)
  244. {
  245. if (a0 == null || a.Radius > a0.Radius)
  246. {
  247. a1 = a0; // 更新第二大为之前最大
  248. a0 = a; // 更新最大为当前的
  249. }
  250. else if (a1 == null || a.Radius > a1.Radius)
  251. {
  252. a1 = a; // 更新第二大
  253. }
  254. }
  255. Texture2D texture = new Texture2D(ScreenLocate.Main.CameraSize.x, ScreenLocate.Main.CameraSize.y);
  256. Color[] blackPixels = new Color[texture.width * texture.height];
  257. for (int i = 0; i < blackPixels.Length; i++)
  258. blackPixels[i] = Color.black;
  259. texture.SetPixels(blackPixels);
  260. if (a0 != null)
  261. {
  262. foreach (var p in a0.Pixels0)
  263. texture.SetPixel((int)p.x, (int)p.y, Color.yellow);
  264. foreach (var p in a0.Pixels1)
  265. texture.SetPixel((int)p.x, (int)p.y, Color.white);
  266. debugText += $"\r\n最大的区域半径: {a0.Radius}";
  267. }
  268. if (a1 != null)
  269. {
  270. foreach (var p in a1.Pixels0)
  271. texture.SetPixel((int)p.x, (int)p.y, Color.green);
  272. foreach (var p in a1.Pixels1)
  273. texture.SetPixel((int)p.x, (int)p.y, Color.blue);
  274. debugText += $"\r\n第二大的区域半径: {a1.Radius}";
  275. }
  276. texture.Apply();
  277. ScreenLocate.DebugTexture(6, texture);
  278. ScreenLocate.Main.Info.transform.GetChild(0).GetComponent<Text>().text = debugText;
  279. }
  280. private List<ISpotArea> DbscanToSpotAreas(DbscanResult<Vector2> db, List<Vector2> brightPoint)
  281. {
  282. if (db.Clusters.Count == 0)
  283. return new List<ISpotArea>();
  284. // 用dbscan的结果创建SpotArea,先用高亮区算一遍半径
  285. var clusters = new List<ISpotArea>();
  286. var areaIncludeRadius = new List<(Vector2, float)>();
  287. foreach (var i in db.Clusters.Values)
  288. {
  289. var area = new PixelSpotArea_DbScan(i);
  290. areaIncludeRadius.Add((area.Centroid, area.Radius));
  291. clusters.Add(area);
  292. }
  293. foreach (var i in db.Noise)
  294. areaIncludeRadius.Add((i.Feature, 0));
  295. // 将泛光点添加到最近的area
  296. foreach (var i in brightPoint)
  297. {
  298. var index = FindNearestAreaIndex(i, areaIncludeRadius,out float nearestDistance);
  299. if (index >= 0 && index < clusters.Count && nearestDistance < PixelSpotArea.gridLength1)
  300. clusters[index].Pixels1.Add(i);
  301. }
  302. // 添加了泛光点后,重新计算半径
  303. foreach (var i in clusters)
  304. i.CalculateRadius();
  305. return clusters;
  306. }
  307. private int FindNearestAreaIndex(Vector2 a, List<(Vector2, float)> areas, out float nearestDistance)
  308. {
  309. nearestDistance = float.MaxValue;
  310. if (areas == null || areas.Count == 0)
  311. return -1;
  312. int nearestIndex = 0;
  313. nearestDistance = Vector2.Distance(a, areas[0].Item1) - areas[0].Item2;
  314. for (int i = 1; i < areas.Count; i++)
  315. {
  316. float distance = Vector2.Distance(a, areas[i].Item1) - areas[i].Item2;
  317. if (distance < nearestDistance)
  318. {
  319. nearestDistance = distance;
  320. nearestIndex = i;
  321. }
  322. }
  323. return nearestIndex;
  324. }
  325. InfraredSpot[] MatchInfraredRaySingle(List<ISpotArea> spotArea)
  326. {
  327. var matchedArea = new Dictionary<InfraredMatch, ISpotArea>() { { InfraredMatch.Match0, null } };
  328. var v0 = InfraredSpots[0].Verify(spotArea, matchedArea);
  329. if (v0)
  330. {
  331. // 每隔20帧检查异常
  332. //if (++cheakCounter >= CheakFrame)
  333. //{
  334. // var maxArea = spotArea.Max((a, b) => a.Radius.CompareTo(b.Radius));
  335. // cheakCounter = 0;
  336. // if (matchedArea[InfraredMatch.Match0] != maxArea)
  337. // {
  338. // InfraredSpots[0].Reset(); // 防止异常
  339. // }
  340. //}
  341. }
  342. else
  343. {
  344. if (spotArea.Count > 0)
  345. {
  346. matchedArea[InfraredMatch.Match0] = spotArea.Max((a, b) => a.Radius.CompareTo(b.Radius));
  347. }
  348. }
  349. foreach (var i in matchedArea)
  350. GetSpot(i.Key).Update(i.Value);
  351. return InfraredSpots;
  352. }
  353. InfraredSpot[] MatchInfraredRay(List<ISpotArea> spotArea)
  354. {
  355. var matchedArea = new Dictionary<InfraredMatch, ISpotArea>() { { InfraredMatch.Match0, null }, { InfraredMatch.Match1, null } };
  356. var v0 = InfraredSpots[0].Verify(spotArea, matchedArea);
  357. var v1 = InfraredSpots[1].Verify(spotArea, matchedArea);
  358. if (!Infrared12Overlap)
  359. {
  360. if (!v0 && !v1)
  361. {
  362. //Application.targetFrameRate = 1;
  363. //Debug.Log($"{Time.time}全失败 spotArea {spotArea.Count}");
  364. if (spotArea.Count == 0)
  365. {
  366. //InfraredSpots[0].UpdateByPredict();
  367. //InfraredSpots[1].UpdateByPredict();
  368. }
  369. else if (spotArea.Count == 1)
  370. {
  371. if (InfraredSpots[0].Predict != null && InfraredSpots[1].Predict == null)
  372. {
  373. matchedArea[InfraredMatch.Match0] = spotArea[0];
  374. //InfraredSpots[0].Update(spotArea[0]);
  375. //InfraredSpots[1].UpdateByPredict();
  376. }
  377. else if (InfraredSpots[1].Predict != null && InfraredSpots[0].Predict == null)
  378. {
  379. matchedArea[InfraredMatch.Match1] = spotArea[0];
  380. }
  381. else
  382. {
  383. if (spotArea[0].Radius > infraredSpotSettings.RadiusThreshold)
  384. {
  385. matchedArea[InfraredMatch.Match0] = spotArea[0];
  386. }
  387. else
  388. {
  389. matchedArea[InfraredMatch.Match1] = spotArea[0];
  390. }
  391. }
  392. }
  393. else
  394. {
  395. spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  396. matchedArea[InfraredMatch.Match0] = spotArea[0];
  397. matchedArea[InfraredMatch.Match1] = spotArea[1];
  398. }
  399. }
  400. else
  401. {
  402. ISpotArea select = null;
  403. ISpotArea selectOther = null;
  404. InfraredMatch oneFailed = InfraredMatch.Nomatch;
  405. if (!v0)
  406. {
  407. select = matchedArea[InfraredMatch.Match1];
  408. //InfraredSpots[1].Update(select);
  409. oneFailed = InfraredMatch.Match0;
  410. }
  411. else if (!v1)
  412. {
  413. select = matchedArea[InfraredMatch.Match0];
  414. //InfraredSpots[0].Update(select);
  415. oneFailed = InfraredMatch.Match1;
  416. }
  417. if (oneFailed != InfraredMatch.Nomatch)
  418. {
  419. //Debug.LogWarning($"{Time.time}成功1个 {oneFailed}");
  420. spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  421. foreach (var i in spotArea)
  422. {
  423. if (i != select)
  424. {
  425. selectOther = i;
  426. break;
  427. }
  428. }
  429. matchedArea[oneFailed] = selectOther;
  430. //if (selectOther == null)
  431. //{
  432. // GetSpot(oneFailed).UpdateByPredict();
  433. //}
  434. //else
  435. //{
  436. // GetSpot(oneFailed).Update(selectOther);
  437. //}
  438. }
  439. else
  440. {
  441. //Debug.LogWarning($"{Time.time}成功2个");
  442. if (matchedArea[InfraredMatch.Match0] == matchedArea[InfraredMatch.Match1])
  443. {
  444. // 重叠
  445. Infrared12Overlap = true;
  446. //if (spotArea.Count == 1)
  447. //{
  448. // Infrared12Overlap = true;
  449. // InfraredSpots[0].Update(spotArea[0]);
  450. // InfraredSpots[1].UpdateByPredict();
  451. // return InfraredSpots;
  452. //}
  453. //else
  454. //{
  455. // Infrared12Overlap = false;
  456. // spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  457. // InfraredSpots[0].Update(spotArea[0]);
  458. // InfraredSpots[1].Update(spotArea[1]);
  459. //}
  460. }
  461. else //if (matchedArea[InfraredMatch.Match1] != matchedArea[InfraredMatch.Match2])
  462. {
  463. //Infrared12Overlap = false;
  464. //InfraredSpots[0].Update(matchedArea[InfraredMatch.Match0]);
  465. //InfraredSpots[1].Update(matchedArea[InfraredMatch.Match1]);
  466. // 每隔20帧更新阈值
  467. if (++cheakCounter >= CheakFrame)
  468. {
  469. //Debug.Log($"{Time.time}更新阈值2个");
  470. var middle = (matchedArea[InfraredMatch.Match0].Radius + matchedArea[InfraredMatch.Match1].Radius) / 2;
  471. infraredSpotSettings.UpdateThreshold(middle);
  472. cheakCounter = 0;
  473. if (matchedArea[InfraredMatch.Match0].Radius < middle)
  474. {
  475. //Debug.Log($"{Time.time}大小异常");
  476. InfraredSpots[0].Reset(); // 防止异常
  477. InfraredSpots[1].Reset();
  478. }
  479. }
  480. }
  481. }
  482. }
  483. }
  484. if (Infrared12Overlap)
  485. {
  486. if (v0)
  487. {
  488. var overlapAera = matchedArea[InfraredMatch.Match0];
  489. (ISpotArea, float) split = (null, float.MaxValue);
  490. foreach (var i in spotArea)
  491. {
  492. if (i != overlapAera)
  493. {
  494. var distance = (i.Centroid - overlapAera.Centroid).magnitude;
  495. if (distance < overlapAera.Radius * 2 && distance < split.Item2)
  496. {
  497. split = (i, distance);
  498. }
  499. }
  500. }
  501. if (split.Item1 != null)
  502. {
  503. //InfraredSpots[0].Update(overlapAera);
  504. //InfraredSpots[1].Update(split.Item1);
  505. matchedArea[InfraredMatch.Match1] = split.Item1;
  506. InfraredSpots[1].Disappear = false;
  507. Infrared12Overlap = false;
  508. }
  509. else
  510. {
  511. if ((InfraredSpots[1].Predict.Value - overlapAera.Centroid).magnitude > overlapAera.Radius / 2)
  512. InfraredSpots[1].Disappear = true;
  513. //InfraredSpots[0].Update(overlapAera);
  514. if (InfraredSpots[1].Predict == null || InfraredSpots[1].Disappear)
  515. {
  516. //InfraredSpots[1].Update(overlapAera);
  517. matchedArea[InfraredMatch.Match1] = overlapAera;
  518. InfraredSpots[1].Predict = null;
  519. }
  520. else
  521. {
  522. matchedArea[InfraredMatch.Match1] = null;
  523. //InfraredSpots[1].UpdateByPredict();
  524. }
  525. //if (++cheakCounter >= 20 * cheakFrame)
  526. //{
  527. // cheakCounter = 0;
  528. // InfraredSpots[1].Reset();
  529. // Infrared12Overlap = false;
  530. //}
  531. }
  532. }
  533. else
  534. {
  535. //InfraredSpots[0].UpdateByPredict();
  536. //InfraredSpots[1].UpdateByPredict();
  537. matchedArea[InfraredMatch.Match1] = null;
  538. }
  539. }
  540. foreach (var i in matchedArea)
  541. GetSpot(i.Key).Update(i.Value);
  542. return InfraredSpots;
  543. }
  544. // 亮度图是64位整形,返回卷积后的均值是float
  545. float ConvBrightness(int[] pixels, (int x, int y) point, int kernel_size = 3)
  546. {
  547. var sum = 0f;
  548. for (int i = point.x - kernel_size / 2; i <= point.x + kernel_size / 2; i++)
  549. {
  550. for (int j = point.y - kernel_size / 2; j <= point.y + kernel_size / 2; j++)
  551. {
  552. var index = mCameraInfo.CoordToIndex(i, j);
  553. if (index > 0 && index < pixels.Length) // 超出边缘不计算
  554. sum += pixels[index];
  555. }
  556. }
  557. return sum / (kernel_size * kernel_size);
  558. }
  559. public List<Vector2> GetOld(int[] brightness) // 取整后的亮度图
  560. {
  561. return LocateOld(brightness, new Rect(0, 0, mCameraInfo.CurrentWidth, mCameraInfo.CurrentHeight));
  562. }
  563. public List<Vector2> LocateOld(int[] brightness, Rect rect)
  564. {
  565. var brightPixelDic = new Dictionary<float, List<Vector2>>();
  566. (int x, int y) origin = ((int)rect.min.x + 1, (int)rect.min.y + 1);
  567. Parallel.For(origin.x / SamplingScale, (origin.x + (int)rect.width) / SamplingScale, (i) =>
  568. {
  569. for (int j = origin.y / SamplingScale; j < (origin.y + rect.height) / SamplingScale; j++)
  570. {
  571. int ip = i * SamplingScale;
  572. int jp = j * SamplingScale;
  573. var index = mCameraInfo.CoordToIndex(ip, jp);
  574. //var b = brightness[index];
  575. //var b = (int)Math.Round(ConvBrightness(brightness, (ip, jp)));
  576. var b = ConvBrightness(brightness, (ip, jp), 3);
  577. if (b > 32)
  578. {
  579. lock (brightPixelDic)
  580. {
  581. if (brightPixelDic.TryGetValue(b, out List<Vector2> list))
  582. list.Add(new Vector2(ip, jp));
  583. else
  584. brightPixelDic.Add(b, new List<Vector2> { new Vector2(ip, jp) });
  585. }
  586. }
  587. }
  588. });
  589. //Parallel.For(0, pixels.Length / 7, (i) =>
  590. //{
  591. // i = i * 7;
  592. // var b = getBrightness(pixels[i]);
  593. // if (b >= maxBrightness)
  594. // {
  595. // lock (brightSpots)
  596. // {
  597. // if (b != maxBrightness)
  598. // brightSpots.Clear();
  599. // brightSpots.Add(indexToVector2(i));
  600. // }
  601. // maxBrightness = b;
  602. // }
  603. //});
  604. if (brightPixelDic.Count > 0)
  605. {
  606. // 取亮度最高的像素
  607. var keys = brightPixelDic.Keys.ToList();
  608. var maxIndex = o0.o0.MaxIndex(keys);
  609. //keys.Sort((a, b) => -a.CompareTo(b));
  610. var brightPixels = new List<Vector2>();
  611. for (int i = 0; i < Math.Min(1, keys.Count); i++)
  612. brightPixels.AddRange(brightPixelDic[keys[maxIndex]]);
  613. //Debug.Log("max brightness: " + keys[maxIndex]);
  614. //Debug.Log("brightPixels.Count: " + brightPixels.Count);
  615. //var testTexture = new Texture2D((int)_textureSize.x, (int)_textureSize.y);
  616. //testTexture.wrapMode = TextureWrapMode.Clamp;
  617. //testTexture.filterMode = FilterMode.Point;
  618. //foreach (var i in brightPixels)
  619. // testTexture.SetPixel((int)i.x, (int)i.y, Color.black);
  620. //testTexture.Apply();
  621. //testImage.texture = testTexture;
  622. var brightArea = new List<PixelCircleArea>() { new PixelCircleArea(brightPixels.First()) };
  623. for (int i = 1; i < brightPixels.Count; i++)
  624. {
  625. var p = brightPixels[i];
  626. var grid = PixelArea.GetGrid(p);
  627. var join = new SortedList<int, PixelCircleArea>();
  628. for (int j = 0; j < brightArea.Count; j++)
  629. {
  630. var area = brightArea[j];
  631. if (area.Include(grid))
  632. join.Add(j, area);
  633. }
  634. if (join.Count == 0)
  635. brightArea.Add(new PixelCircleArea(p));
  636. else if (join.Count == 1)
  637. join.First().Value.Add(p, grid);
  638. else
  639. {
  640. var combine = new PixelCircleArea(join.Values);
  641. combine.Add(p, grid);
  642. brightArea.Add(combine);
  643. for (int j = join.Count - 1; j >= 0; j--)
  644. brightArea.RemoveAt(join.ElementAt(j).Key);
  645. }
  646. //foreach (var j in brightArea)
  647. //{
  648. // var offset = (p - j.Center);
  649. // if (offset.magnitude < brightAreaRadius) // 距离近的并入该区域
  650. // {
  651. // j.Pixels.Add(p);
  652. // j.Center += offset / j.Pixels.Count;
  653. // join = true;
  654. // break;
  655. // }
  656. //}
  657. //if (!join)
  658. // brightArea.Add(new PixelArea(p));
  659. }
  660. //var sum = new Vector2(0, 0);
  661. //foreach (var i in brightPixels)
  662. //{
  663. // sum += i;
  664. //}
  665. //var middle = sum/brightPixels.Count;
  666. //Debug.Log("brightArea.Count: " + brightArea.Count);
  667. //if (brightArea.Count <= 1)
  668. // return brightArea.FirstOrDefault().Center;
  669. //PixelArea maxBrightArea = brightArea.First();
  670. //float maxCircleBrightness = 10000f;
  671. var CircleAreas = new List<PixelCircleArea>();
  672. for (int i = 0; i < brightArea.Count; i++)
  673. {
  674. var area = brightArea[i];
  675. var value = area.CircleBrightness(out float variance, brightness, ConvBrightness, 3);
  676. //Debug.Log(counter + "Variance: " + variance);
  677. //Debug.Log(counter + "CircleBrightness: " + value);
  678. //Debug.Log(counter + "CircleRadius: " + area.MaxRadius);
  679. if (variance < 30)
  680. {
  681. CircleAreas.Add(area);
  682. }
  683. //if (maxCircleBrightness == 10000f)
  684. //{
  685. // maxCircleBrightness = value;
  686. // maxBrightArea = area;
  687. //}
  688. //else if (maxCircleBrightness < value || (maxCircleBrightness == value && area.Pixels.Count > maxBrightArea.Pixels.Count))
  689. //{
  690. // maxCircleBrightness = value;
  691. // maxBrightArea = area;
  692. //}
  693. }
  694. //Debug.Log("CricleBrightness: " + maxCircleBrightness);
  695. //Debug.Log(counter + "CircleAreas: " + CircleAreas.Count);
  696. //counter++;
  697. if (CircleAreas.Count == 0)
  698. return null;
  699. if (CircleAreas.Count == 1)
  700. return new List<Vector2> { CircleAreas[0].Center };
  701. CircleAreas.Sort((a, b) => b.MaxRadius.CompareTo(a.MaxRadius));
  702. return new List<Vector2> { CircleAreas[0].Center, CircleAreas[1].Center };
  703. }
  704. return null;
  705. }
  706. //(int max, int second) MaxAreaIndex(Color[] pixels, List<PixelArea> list)
  707. //{
  708. // var maxValue = float.MinValue;
  709. // var secondValue = float.MinValue;
  710. // var max = 0;
  711. // var second = 0;
  712. // foreach (var i in list.Index())
  713. // {
  714. // var value = list[i].TotalBrightness(pixels, camera.Vector2ToIndex, samplingScale * 2);
  715. // if (value > maxValue)
  716. // {
  717. // maxValue = value;
  718. // max = i;
  719. // }
  720. // else if (maxValue > secondValue)
  721. // {
  722. // secondValue = value;
  723. // second = i;
  724. // }
  725. // }
  726. // return (max, second);
  727. //}
  728. //float CricleVariance(int[] pixels, PixelArea area, int kernel_size = 3)
  729. //{
  730. // var hash = new HashSet<(int, int)>();
  731. // foreach (var (cos,sin) in angleMathList)
  732. // {
  733. // var x = (int)Math.Round(area.Center.x + (area.MaxRadius + PixelArea.gridLength * 4) * cos);
  734. // var y = (int)Math.Round(area.Center.y + (area.MaxRadius + PixelArea.gridLength * 4) * sin);
  735. // hash.Add((x, y));
  736. // }
  737. // var avg = 0f;
  738. // foreach (var p in hash)
  739. // {
  740. // var value = ConvBrightness(pixels, p, kernel_size);
  741. // avg += value;
  742. // }
  743. // return avg / hash.Count;
  744. //}
  745. //class PixelArea
  746. //{
  747. // public static int gridLength;
  748. // public static (int x, int y) gridSize;
  749. // public static (int x, int y) GetGrid(Vector2 v)
  750. // {
  751. // var m = (int)(v.x / gridLength);
  752. // var n = (int)(v.y / gridLength);
  753. // return (m, n);
  754. // }
  755. // public Vector2 Center;
  756. // public List<Vector2> Pixels;
  757. // public PixelArea(Vector2 location)
  758. // {
  759. // this.Center = location;
  760. // this.Pixels = new List<Vector2> { location };
  761. // }
  762. //}
  763. }
  764. }