InfraredLocate.cs 34 KB

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