InfraredLocate.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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>(200); // 预估的初始容量
  120. var brightPoint = new List<Vector2>(1000);
  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. if (spotPoint.Count > 500) // 如果亮点太多,控制亮点数量在500左右
  153. {
  154. SamplingScale = (int)Math.Ceiling(SamplingScale * Math.Sqrt(spotPoint.Count / 500.0));
  155. return new List<ISpotArea>();
  156. }
  157. else if (SamplingScale > 1 && spotPoint.Count < 100)
  158. {
  159. SamplingScale = Math.Max((int)Math.Ceiling(SamplingScale * Math.Sqrt(spotPoint.Count / 200.0)), 1);
  160. return new List<ISpotArea>();
  161. }
  162. }
  163. //times.Add(watch.ElapsedMilliseconds);
  164. //UnityEngine.Debug.Log("time1: " + (times[times.Count - 1] - times[times.Count - 2]));
  165. // 所有点映射到屏幕空间
  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. var temp0 = new List<Vector2>(spotPoint.Count);
  170. var temp1 = new List<Vector2>(spotPoint.Count);
  171. foreach (var p in spotPoint)
  172. {
  173. if (screenIdentification.Screen.UVInScreen(p))
  174. temp0.Add(p);
  175. }
  176. foreach (var p in brightPoint)
  177. {
  178. if (screenIdentification.Screen.UVInScreen(p))
  179. temp1.Add(p);
  180. }
  181. spotPoint = temp0;
  182. brightPoint = temp1;
  183. if (spotPoint.Count > 0)
  184. {
  185. //times.Add(watch.ElapsedMilliseconds);
  186. //UnityEngine.Debug.Log("time2: " + (times[times.Count - 1] - times[times.Count - 2]));
  187. var db = Dbscan.Run(spotPoint, ZIM.Unity.ZIMMath.LengthManhattan, SamplingScale, 4);
  188. var spotArea = DbscanToSpotAreas(db, brightPoint);
  189. //var spotArea = PixelSpotArea.Cluster(spotPoint, brightPoint, screenIdentification.Screen.UVInScreen);
  190. if (ScreenLocate.Main.DebugOnZIMDemo)
  191. DebugAreas(spotArea);
  192. //Debug.Log("db: " + db.Clusters.Count);
  193. //Debug.Log("db noise: " + db.Noise.Count);
  194. //foreach (var i in spotArea)
  195. //{
  196. // Debug.Log("i.Radius" + i.Radius);
  197. //}
  198. //times.Add(watch.ElapsedMilliseconds);
  199. //UnityEngine.Debug.Log("time3: " + (times[times.Count - 1] - times[times.Count - 2]));
  200. return spotArea;
  201. //半径再按透视修正一遍,降低一点常规角度下反射的影响
  202. //foreach (var i in spotArea)
  203. //{
  204. // var r0 = i.Radius / 2 / mCameraInfo.CurrentWidth;
  205. // var center = i.Centroid;
  206. // var offset1 = center + new Vector2(i.Radius / 2, 0);
  207. // var offset2 = center - new Vector2(i.Radius / 2, 0);
  208. // var offset3 = center + new Vector2(0, i.Radius / 2);
  209. // var offset4 = center - new Vector2(0, i.Radius / 2);
  210. // var transR = ((screenIdentification.Screen.TransformToScreen(offset1) - screenIdentification.Screen.TransformToScreen(offset2)).magnitude +
  211. // (screenIdentification.Screen.TransformToScreen(offset3) - screenIdentification.Screen.TransformToScreen(offset4)).magnitude) / 4;
  212. // var r1 = transR / screenIdentification.Screen.UVSize.x;
  213. // //Debug.Log(r1 / r0);
  214. // i.Radius *= (float)Math.Pow(r1 / r0, 2); // 摄像机位置不同参数也可能不同
  215. //}
  216. //if (spotArea.Count == 1)
  217. //Debug.Log($"{spotArea[0].MaxRadius}");
  218. //return spotArea;
  219. //// 排序亮区
  220. //spotArea.Sort((a, b) => b.MaxRadius.CompareTo(a.MaxRadius));
  221. ////var areas = new SortedList<float, ISpotArea>(new DescendingComparer<float>());
  222. ////foreach (var i in spotArea)
  223. //// areas.Add(i.MaxRadius, i);
  224. //var result = new Vector2[spotArea.Count];
  225. //foreach (var i in spotArea.Index())
  226. // result[i] = spotArea[i].Center;
  227. //times.Add(watch.ElapsedMilliseconds);
  228. //UnityEngine.Debug.Log("time6: " + (times[times.Count - 1] - times[times.Count - 2]));
  229. //return result;
  230. }
  231. return new List<ISpotArea>();
  232. }
  233. private void DebugAreas(List<ISpotArea> areas)
  234. {
  235. var debugText = $"当前相机分辨率: {ScreenLocate.Main.CameraSize}";
  236. debugText += $"\r\nareas.Count: {areas.Count}";
  237. ISpotArea a0 = null; // 表示最大半径的区域
  238. ISpotArea a1 = null; // 表示第二大半径的区域
  239. foreach (var a in areas)
  240. {
  241. if (a0 == null || a.Radius > a0.Radius)
  242. {
  243. a1 = a0; // 更新第二大为之前最大
  244. a0 = a; // 更新最大为当前的
  245. }
  246. else if (a1 == null || a.Radius > a1.Radius)
  247. {
  248. a1 = a; // 更新第二大
  249. }
  250. }
  251. Texture2D texture = new Texture2D(ScreenLocate.Main.CameraSize.x, ScreenLocate.Main.CameraSize.y);
  252. Color[] blackPixels = new Color[texture.width * texture.height];
  253. for (int i = 0; i < blackPixels.Length; i++)
  254. blackPixels[i] = Color.black;
  255. texture.SetPixels(blackPixels);
  256. if (a0 != null)
  257. {
  258. foreach (var p in a0.Pixels0)
  259. texture.SetPixel((int)p.x, (int)p.y, Color.yellow);
  260. foreach (var p in a0.Pixels1)
  261. texture.SetPixel((int)p.x, (int)p.y, Color.white);
  262. debugText += $"\r\n最大的区域半径: {a0.Radius}";
  263. }
  264. if (a1 != null)
  265. {
  266. foreach (var p in a1.Pixels0)
  267. texture.SetPixel((int)p.x, (int)p.y, Color.green);
  268. foreach (var p in a1.Pixels1)
  269. texture.SetPixel((int)p.x, (int)p.y, Color.blue);
  270. debugText += $"\r\n第二大的区域半径: {a1.Radius}";
  271. }
  272. texture.Apply();
  273. ScreenLocate.DebugTexture(6, texture);
  274. ScreenLocate.Main.Info.transform.GetChild(0).GetComponent<Text>().text = debugText;
  275. }
  276. private List<ISpotArea> DbscanToSpotAreas(DbscanResult<Vector2> db, List<Vector2> brightPoint)
  277. {
  278. if (db.Clusters.Count == 0)
  279. return new List<ISpotArea>();
  280. // 用dbscan的结果创建SpotArea,先用高亮区算一遍半径
  281. var clusters = new List<ISpotArea>();
  282. var areaIncludeRadius = new List<(Vector2, float)>();
  283. foreach (var i in db.Clusters.Values)
  284. {
  285. var area = new PixelSpotArea_DbScan(i);
  286. areaIncludeRadius.Add((area.Centroid, area.Radius));
  287. clusters.Add(area);
  288. }
  289. foreach (var i in db.Noise)
  290. areaIncludeRadius.Add((i.Feature, 0));
  291. // 将泛光点添加到最近的area
  292. foreach (var i in brightPoint)
  293. {
  294. var index = FindNearestAreaIndex(i, areaIncludeRadius,out float nearestDistance);
  295. if (index >= 0 && index < clusters.Count && nearestDistance < PixelSpotArea.gridLength1)
  296. clusters[index].Pixels1.Add(i);
  297. }
  298. // 添加了泛光点后,重新计算半径
  299. foreach (var i in clusters)
  300. i.CalculateRadius();
  301. return clusters;
  302. }
  303. private int FindNearestAreaIndex(Vector2 a, List<(Vector2, float)> areas, out float nearestDistance)
  304. {
  305. nearestDistance = float.MaxValue;
  306. if (areas == null || areas.Count == 0)
  307. return -1;
  308. int nearestIndex = 0;
  309. nearestDistance = Vector2.Distance(a, areas[0].Item1) - areas[0].Item2;
  310. for (int i = 1; i < areas.Count; i++)
  311. {
  312. float distance = Vector2.Distance(a, areas[i].Item1) - areas[i].Item2;
  313. if (distance < nearestDistance)
  314. {
  315. nearestDistance = distance;
  316. nearestIndex = i;
  317. }
  318. }
  319. return nearestIndex;
  320. }
  321. InfraredSpot[] MatchInfraredRaySingle(List<ISpotArea> spotArea)
  322. {
  323. var matchedArea = new Dictionary<InfraredMatch, ISpotArea>() { { InfraredMatch.Match0, null } };
  324. var v0 = InfraredSpots[0].Verify(spotArea, matchedArea);
  325. if (v0)
  326. {
  327. // 每隔20帧检查异常
  328. //if (++cheakCounter >= CheakFrame)
  329. //{
  330. // var maxArea = spotArea.Max((a, b) => a.Radius.CompareTo(b.Radius));
  331. // cheakCounter = 0;
  332. // if (matchedArea[InfraredMatch.Match0] != maxArea)
  333. // {
  334. // InfraredSpots[0].Reset(); // 防止异常
  335. // }
  336. //}
  337. }
  338. else
  339. {
  340. if (spotArea.Count > 0)
  341. {
  342. matchedArea[InfraredMatch.Match0] = spotArea.Max((a, b) => a.Radius.CompareTo(b.Radius));
  343. }
  344. }
  345. foreach (var i in matchedArea)
  346. GetSpot(i.Key).Update(i.Value);
  347. return InfraredSpots;
  348. }
  349. InfraredSpot[] MatchInfraredRay(List<ISpotArea> spotArea)
  350. {
  351. var matchedArea = new Dictionary<InfraredMatch, ISpotArea>() { { InfraredMatch.Match0, null }, { InfraredMatch.Match1, null } };
  352. var v0 = InfraredSpots[0].Verify(spotArea, matchedArea);
  353. var v1 = InfraredSpots[1].Verify(spotArea, matchedArea);
  354. if (!Infrared12Overlap)
  355. {
  356. if (!v0 && !v1)
  357. {
  358. //Application.targetFrameRate = 1;
  359. //Debug.Log($"{Time.time}全失败 spotArea {spotArea.Count}");
  360. if (spotArea.Count == 0)
  361. {
  362. //InfraredSpots[0].UpdateByPredict();
  363. //InfraredSpots[1].UpdateByPredict();
  364. }
  365. else if (spotArea.Count == 1)
  366. {
  367. if (InfraredSpots[0].Predict != null && InfraredSpots[1].Predict == null)
  368. {
  369. matchedArea[InfraredMatch.Match0] = spotArea[0];
  370. //InfraredSpots[0].Update(spotArea[0]);
  371. //InfraredSpots[1].UpdateByPredict();
  372. }
  373. else if (InfraredSpots[1].Predict != null && InfraredSpots[0].Predict == null)
  374. {
  375. matchedArea[InfraredMatch.Match1] = spotArea[0];
  376. }
  377. else
  378. {
  379. if (spotArea[0].Radius > infraredSpotSettings.RadiusThreshold)
  380. {
  381. matchedArea[InfraredMatch.Match0] = spotArea[0];
  382. }
  383. else
  384. {
  385. matchedArea[InfraredMatch.Match1] = spotArea[0];
  386. }
  387. }
  388. }
  389. else
  390. {
  391. spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  392. matchedArea[InfraredMatch.Match0] = spotArea[0];
  393. matchedArea[InfraredMatch.Match1] = spotArea[1];
  394. }
  395. }
  396. else
  397. {
  398. ISpotArea select = null;
  399. ISpotArea selectOther = null;
  400. InfraredMatch oneFailed = InfraredMatch.Nomatch;
  401. if (!v0)
  402. {
  403. select = matchedArea[InfraredMatch.Match1];
  404. //InfraredSpots[1].Update(select);
  405. oneFailed = InfraredMatch.Match0;
  406. }
  407. else if (!v1)
  408. {
  409. select = matchedArea[InfraredMatch.Match0];
  410. //InfraredSpots[0].Update(select);
  411. oneFailed = InfraredMatch.Match1;
  412. }
  413. if (oneFailed != InfraredMatch.Nomatch)
  414. {
  415. //Debug.LogWarning($"{Time.time}成功1个 {oneFailed}");
  416. spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  417. foreach (var i in spotArea)
  418. {
  419. if (i != select)
  420. {
  421. selectOther = i;
  422. break;
  423. }
  424. }
  425. matchedArea[oneFailed] = selectOther;
  426. //if (selectOther == null)
  427. //{
  428. // GetSpot(oneFailed).UpdateByPredict();
  429. //}
  430. //else
  431. //{
  432. // GetSpot(oneFailed).Update(selectOther);
  433. //}
  434. }
  435. else
  436. {
  437. //Debug.LogWarning($"{Time.time}成功2个");
  438. if (matchedArea[InfraredMatch.Match0] == matchedArea[InfraredMatch.Match1])
  439. {
  440. // 重叠
  441. Infrared12Overlap = true;
  442. //if (spotArea.Count == 1)
  443. //{
  444. // Infrared12Overlap = true;
  445. // InfraredSpots[0].Update(spotArea[0]);
  446. // InfraredSpots[1].UpdateByPredict();
  447. // return InfraredSpots;
  448. //}
  449. //else
  450. //{
  451. // Infrared12Overlap = false;
  452. // spotArea.Sort((a, b) => b.Radius.CompareTo(a.Radius)); // 排序亮区
  453. // InfraredSpots[0].Update(spotArea[0]);
  454. // InfraredSpots[1].Update(spotArea[1]);
  455. //}
  456. }
  457. else //if (matchedArea[InfraredMatch.Match1] != matchedArea[InfraredMatch.Match2])
  458. {
  459. //Infrared12Overlap = false;
  460. //InfraredSpots[0].Update(matchedArea[InfraredMatch.Match0]);
  461. //InfraredSpots[1].Update(matchedArea[InfraredMatch.Match1]);
  462. // 每隔20帧更新阈值
  463. if (++cheakCounter >= CheakFrame)
  464. {
  465. //Debug.Log($"{Time.time}更新阈值2个");
  466. var middle = (matchedArea[InfraredMatch.Match0].Radius + matchedArea[InfraredMatch.Match1].Radius) / 2;
  467. infraredSpotSettings.UpdateThreshold(middle);
  468. cheakCounter = 0;
  469. if (matchedArea[InfraredMatch.Match0].Radius < middle)
  470. {
  471. //Debug.Log($"{Time.time}大小异常");
  472. InfraredSpots[0].Reset(); // 防止异常
  473. InfraredSpots[1].Reset();
  474. }
  475. }
  476. }
  477. }
  478. }
  479. }
  480. if (Infrared12Overlap)
  481. {
  482. if (v0)
  483. {
  484. var overlapAera = matchedArea[InfraredMatch.Match0];
  485. (ISpotArea, float) split = (null, float.MaxValue);
  486. foreach (var i in spotArea)
  487. {
  488. if (i != overlapAera)
  489. {
  490. var distance = (i.Centroid - overlapAera.Centroid).magnitude;
  491. if (distance < overlapAera.Radius * 2 && distance < split.Item2)
  492. {
  493. split = (i, distance);
  494. }
  495. }
  496. }
  497. if (split.Item1 != null)
  498. {
  499. //InfraredSpots[0].Update(overlapAera);
  500. //InfraredSpots[1].Update(split.Item1);
  501. matchedArea[InfraredMatch.Match1] = split.Item1;
  502. InfraredSpots[1].Disappear = false;
  503. Infrared12Overlap = false;
  504. }
  505. else
  506. {
  507. if ((InfraredSpots[1].Predict.Value - overlapAera.Centroid).magnitude > overlapAera.Radius / 2)
  508. InfraredSpots[1].Disappear = true;
  509. //InfraredSpots[0].Update(overlapAera);
  510. if (InfraredSpots[1].Predict == null || InfraredSpots[1].Disappear)
  511. {
  512. //InfraredSpots[1].Update(overlapAera);
  513. matchedArea[InfraredMatch.Match1] = overlapAera;
  514. InfraredSpots[1].Predict = null;
  515. }
  516. else
  517. {
  518. matchedArea[InfraredMatch.Match1] = null;
  519. //InfraredSpots[1].UpdateByPredict();
  520. }
  521. //if (++cheakCounter >= 20 * cheakFrame)
  522. //{
  523. // cheakCounter = 0;
  524. // InfraredSpots[1].Reset();
  525. // Infrared12Overlap = false;
  526. //}
  527. }
  528. }
  529. else
  530. {
  531. //InfraredSpots[0].UpdateByPredict();
  532. //InfraredSpots[1].UpdateByPredict();
  533. matchedArea[InfraredMatch.Match1] = null;
  534. }
  535. }
  536. foreach (var i in matchedArea)
  537. GetSpot(i.Key).Update(i.Value);
  538. return InfraredSpots;
  539. }
  540. // 亮度图是64位整形,返回卷积后的均值是float
  541. float ConvBrightness(int[] pixels, (int x, int y) point, int kernel_size = 3)
  542. {
  543. var sum = 0f;
  544. for (int i = point.x - kernel_size / 2; i <= point.x + kernel_size / 2; i++)
  545. {
  546. for (int j = point.y - kernel_size / 2; j <= point.y + kernel_size / 2; j++)
  547. {
  548. var index = mCameraInfo.CoordToIndex(i, j);
  549. if (index > 0 && index < pixels.Length) // 超出边缘不计算
  550. sum += pixels[index];
  551. }
  552. }
  553. return sum / (kernel_size * kernel_size);
  554. }
  555. public List<Vector2> GetOld(int[] brightness) // 取整后的亮度图
  556. {
  557. return LocateOld(brightness, new Rect(0, 0, mCameraInfo.CurrentWidth, mCameraInfo.CurrentHeight));
  558. }
  559. public List<Vector2> LocateOld(int[] brightness, Rect rect)
  560. {
  561. var brightPixelDic = new Dictionary<float, List<Vector2>>();
  562. (int x, int y) origin = ((int)rect.min.x + 1, (int)rect.min.y + 1);
  563. Parallel.For(origin.x / SamplingScale, (origin.x + (int)rect.width) / SamplingScale, (i) =>
  564. {
  565. for (int j = origin.y / SamplingScale; j < (origin.y + rect.height) / SamplingScale; j++)
  566. {
  567. int ip = i * SamplingScale;
  568. int jp = j * SamplingScale;
  569. var index = mCameraInfo.CoordToIndex(ip, jp);
  570. //var b = brightness[index];
  571. //var b = (int)Math.Round(ConvBrightness(brightness, (ip, jp)));
  572. var b = ConvBrightness(brightness, (ip, jp), 3);
  573. if (b > 32)
  574. {
  575. lock (brightPixelDic)
  576. {
  577. if (brightPixelDic.TryGetValue(b, out List<Vector2> list))
  578. list.Add(new Vector2(ip, jp));
  579. else
  580. brightPixelDic.Add(b, new List<Vector2> { new Vector2(ip, jp) });
  581. }
  582. }
  583. }
  584. });
  585. //Parallel.For(0, pixels.Length / 7, (i) =>
  586. //{
  587. // i = i * 7;
  588. // var b = getBrightness(pixels[i]);
  589. // if (b >= maxBrightness)
  590. // {
  591. // lock (brightSpots)
  592. // {
  593. // if (b != maxBrightness)
  594. // brightSpots.Clear();
  595. // brightSpots.Add(indexToVector2(i));
  596. // }
  597. // maxBrightness = b;
  598. // }
  599. //});
  600. if (brightPixelDic.Count > 0)
  601. {
  602. // 取亮度最高的像素
  603. var keys = brightPixelDic.Keys.ToList();
  604. var maxIndex = o0.o0.MaxIndex(keys);
  605. //keys.Sort((a, b) => -a.CompareTo(b));
  606. var brightPixels = new List<Vector2>();
  607. for (int i = 0; i < Math.Min(1, keys.Count); i++)
  608. brightPixels.AddRange(brightPixelDic[keys[maxIndex]]);
  609. //Debug.Log("max brightness: " + keys[maxIndex]);
  610. //Debug.Log("brightPixels.Count: " + brightPixels.Count);
  611. //var testTexture = new Texture2D((int)_textureSize.x, (int)_textureSize.y);
  612. //testTexture.wrapMode = TextureWrapMode.Clamp;
  613. //testTexture.filterMode = FilterMode.Point;
  614. //foreach (var i in brightPixels)
  615. // testTexture.SetPixel((int)i.x, (int)i.y, Color.black);
  616. //testTexture.Apply();
  617. //testImage.texture = testTexture;
  618. var brightArea = new List<PixelCircleArea>() { new PixelCircleArea(brightPixels.First()) };
  619. for (int i = 1; i < brightPixels.Count; i++)
  620. {
  621. var p = brightPixels[i];
  622. var grid = PixelArea.GetGrid(p);
  623. var join = new SortedList<int, PixelCircleArea>();
  624. for (int j = 0; j < brightArea.Count; j++)
  625. {
  626. var area = brightArea[j];
  627. if (area.Include(grid))
  628. join.Add(j, area);
  629. }
  630. if (join.Count == 0)
  631. brightArea.Add(new PixelCircleArea(p));
  632. else if (join.Count == 1)
  633. join.First().Value.Add(p, grid);
  634. else
  635. {
  636. var combine = new PixelCircleArea(join.Values);
  637. combine.Add(p, grid);
  638. brightArea.Add(combine);
  639. for (int j = join.Count - 1; j >= 0; j--)
  640. brightArea.RemoveAt(join.ElementAt(j).Key);
  641. }
  642. //foreach (var j in brightArea)
  643. //{
  644. // var offset = (p - j.Center);
  645. // if (offset.magnitude < brightAreaRadius) // 距离近的并入该区域
  646. // {
  647. // j.Pixels.Add(p);
  648. // j.Center += offset / j.Pixels.Count;
  649. // join = true;
  650. // break;
  651. // }
  652. //}
  653. //if (!join)
  654. // brightArea.Add(new PixelArea(p));
  655. }
  656. //var sum = new Vector2(0, 0);
  657. //foreach (var i in brightPixels)
  658. //{
  659. // sum += i;
  660. //}
  661. //var middle = sum/brightPixels.Count;
  662. //Debug.Log("brightArea.Count: " + brightArea.Count);
  663. //if (brightArea.Count <= 1)
  664. // return brightArea.FirstOrDefault().Center;
  665. //PixelArea maxBrightArea = brightArea.First();
  666. //float maxCircleBrightness = 10000f;
  667. var CircleAreas = new List<PixelCircleArea>();
  668. for (int i = 0; i < brightArea.Count; i++)
  669. {
  670. var area = brightArea[i];
  671. var value = area.CircleBrightness(out float variance, brightness, ConvBrightness, 3);
  672. //Debug.Log(counter + "Variance: " + variance);
  673. //Debug.Log(counter + "CircleBrightness: " + value);
  674. //Debug.Log(counter + "CircleRadius: " + area.MaxRadius);
  675. if (variance < 30)
  676. {
  677. CircleAreas.Add(area);
  678. }
  679. //if (maxCircleBrightness == 10000f)
  680. //{
  681. // maxCircleBrightness = value;
  682. // maxBrightArea = area;
  683. //}
  684. //else if (maxCircleBrightness < value || (maxCircleBrightness == value && area.Pixels.Count > maxBrightArea.Pixels.Count))
  685. //{
  686. // maxCircleBrightness = value;
  687. // maxBrightArea = area;
  688. //}
  689. }
  690. //Debug.Log("CricleBrightness: " + maxCircleBrightness);
  691. //Debug.Log(counter + "CircleAreas: " + CircleAreas.Count);
  692. //counter++;
  693. if (CircleAreas.Count == 0)
  694. return null;
  695. if (CircleAreas.Count == 1)
  696. return new List<Vector2> { CircleAreas[0].Center };
  697. CircleAreas.Sort((a, b) => b.MaxRadius.CompareTo(a.MaxRadius));
  698. return new List<Vector2> { CircleAreas[0].Center, CircleAreas[1].Center };
  699. }
  700. return null;
  701. }
  702. //(int max, int second) MaxAreaIndex(Color[] pixels, List<PixelArea> list)
  703. //{
  704. // var maxValue = float.MinValue;
  705. // var secondValue = float.MinValue;
  706. // var max = 0;
  707. // var second = 0;
  708. // foreach (var i in list.Index())
  709. // {
  710. // var value = list[i].TotalBrightness(pixels, camera.Vector2ToIndex, samplingScale * 2);
  711. // if (value > maxValue)
  712. // {
  713. // maxValue = value;
  714. // max = i;
  715. // }
  716. // else if (maxValue > secondValue)
  717. // {
  718. // secondValue = value;
  719. // second = i;
  720. // }
  721. // }
  722. // return (max, second);
  723. //}
  724. //float CricleVariance(int[] pixels, PixelArea area, int kernel_size = 3)
  725. //{
  726. // var hash = new HashSet<(int, int)>();
  727. // foreach (var (cos,sin) in angleMathList)
  728. // {
  729. // var x = (int)Math.Round(area.Center.x + (area.MaxRadius + PixelArea.gridLength * 4) * cos);
  730. // var y = (int)Math.Round(area.Center.y + (area.MaxRadius + PixelArea.gridLength * 4) * sin);
  731. // hash.Add((x, y));
  732. // }
  733. // var avg = 0f;
  734. // foreach (var p in hash)
  735. // {
  736. // var value = ConvBrightness(pixels, p, kernel_size);
  737. // avg += value;
  738. // }
  739. // return avg / hash.Count;
  740. //}
  741. //class PixelArea
  742. //{
  743. // public static int gridLength;
  744. // public static (int x, int y) gridSize;
  745. // public static (int x, int y) GetGrid(Vector2 v)
  746. // {
  747. // var m = (int)(v.x / gridLength);
  748. // var n = (int)(v.y / gridLength);
  749. // return (m, n);
  750. // }
  751. // public Vector2 Center;
  752. // public List<Vector2> Pixels;
  753. // public PixelArea(Vector2 location)
  754. // {
  755. // this.Center = location;
  756. // this.Pixels = new List<Vector2> { location };
  757. // }
  758. //}
  759. }
  760. }