InfraredLocate.cs 32 KB

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