InfraredLocate.cs 32 KB

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