InfraredLocate.cs 34 KB

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