InfraredLocate.cs 30 KB

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