ScreenIdentification.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. #define ENABLE_LOG
  2. using o0.Geometry2D.Float;
  3. using o0.Num;
  4. using o0InfraredLocate;
  5. using o0InfraredLocate.ZIM;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading.Tasks;
  11. using UnityEngine;
  12. using UnityEngine.UIElements;
  13. using UnityStandardAssets.Utility;
  14. using ZIM;
  15. using ZIM.Unity;
  16. namespace o0.Project
  17. {
  18. public partial class ScreenIdentification
  19. {
  20. private const string TAG = "ScreenIdentification#";
  21. // LocateAreaData表示每次屏幕的色差变化的区域,可能有多次。通过设置LocateSingleStep可调整为仅识别一次色差
  22. static Rect[][] LocateAreaData = new Rect[][] {
  23. new Rect[] { new Rect(0f, 0f, 0.3f, 0.3f), new Rect(0f, 0f, 0.4f, 0.4f), new Rect(0f, 0f, 0.5f, 0.5f) },
  24. new Rect[] { new Rect(0.7f, 0f, 0.3f, 0.3f), new Rect(0.6f, 0f, 0.4f, 0.4f), new Rect(0.5f, 0f, 0.5f, 0.5f) },
  25. new Rect[] { new Rect(0f, 0.7f, 0.3f, 0.3f), new Rect(0f, 0.6f, 0.4f, 0.4f), new Rect(0f, 0.5f, 0.5f, 0.5f) },
  26. new Rect[] { new Rect(0.7f, 0.7f, 0.3f, 0.3f), new Rect(0.6f, 0.6f, 0.4f, 0.4f), new Rect(0.5f, 0.5f, 0.5f, 0.5f) }
  27. };
  28. //static Rect[][] LocateAreaData = new Rect[][] {
  29. // new Rect[] { new Rect(0f, 0f, 0.3f, 0.3f), new Rect(0f, 0f, 0.4f, 0.4f), new Rect(0f, 0f, 0.5f, 0.5f), new Rect(0f, 0f, 0.6f, 0.6f) },
  30. // new Rect[] { new Rect(0.7f, 0f, 0.3f, 0.3f), new Rect(0.6f, 0f, 0.4f, 0.4f), new Rect(0.5f, 0f, 0.5f, 0.5f), new Rect(0.4f, 0f, 0.6f, 0.6f) },
  31. // new Rect[] { new Rect(0f, 0.7f, 0.3f, 0.3f), new Rect(0f, 0.6f, 0.4f, 0.4f), new Rect(0f, 0.5f, 0.5f, 0.5f), new Rect(0f, 0.4f, 0.6f, 0.6f) },
  32. // new Rect[] { new Rect(0.7f, 0.7f, 0.3f, 0.3f), new Rect(0.6f, 0.6f, 0.4f, 0.4f), new Rect(0.5f, 0.5f, 0.5f, 0.5f), new Rect(0.4f, 0.4f, 0.6f, 0.6f) }
  33. //};
  34. //static bool LocateSingleStep = false;
  35. static bool LocateSingleStep = true;
  36. public Vector Size => ScreenLocate.Main.CameraSize;
  37. public Geometry.Vector<int> o0Size => new Geometry.Vector<int>((int)Size.x, (int)Size.y);
  38. public QuadrilateralInCamera QuadManual;
  39. public QuadrilateralInCamera QuadAuto; // 全自动,可以给用户选择(赋值给Screen.QuadInCamera即生效)
  40. public QuadrilateralInCamera QuadSemiAuto; // 半自动,可以给用户选择(赋值给Screen.QuadInCamera即生效)
  41. public ScreenMap Screen; // 识别到的屏幕,用于执行透视变换
  42. int capture = 0;
  43. int delay = 0;
  44. int maxCapture;
  45. int maxDelay;
  46. Geometry.Vector<float>[] ScreenBlackTexture;
  47. Geometry.Vector<float>[] ScreenWhiteTexture;
  48. int locateIndex = -1;
  49. readonly List<Rect> locateArea = new List<Rect> {
  50. new Rect(0f, 0f, 0.5f, 0.5f), new Rect(0.5f, 0f, 0.5f, 0.5f), new Rect(0f, 0.5f, 0.5f, 0.5f), new Rect(0.5f, 0.5f, 0.5f, 0.5f)
  51. }; // 屏幕显示白色的区域大小
  52. float areaPercent => locateArea[locateIndex].size.x; // 当前白色区域的占比
  53. int areaSelected = -1; // 选择哪个区域,顺序与Quadrilateral对应
  54. readonly List<float> sumTemp = new List<float>();
  55. readonly List<QuadrilateralInCamera> quadTemp = new List<QuadrilateralInCamera>();
  56. //public ScreenIdentification(WebCamTexture texture)
  57. //{
  58. // Size = new Geometry2D.Vector<int>(texture.width, texture.height);
  59. // Screen = new ScreenMap();
  60. //}
  61. public static UnityEngine.Color FloatValueToColor(float i)
  62. {
  63. return i switch
  64. {
  65. 1 => UnityEngine.Color.yellow,
  66. 2 => new UnityEngine.Color(0,1,1,1),
  67. 3 => UnityEngine.Color.green,
  68. 4 => UnityEngine.Color.white,
  69. 5 => UnityEngine.Color.red,
  70. _ => UnityEngine.Color.black,
  71. };
  72. }
  73. public ScreenIdentification(o0InfraredCameraHandler cameraHandler)
  74. {
  75. Screen = new ScreenMap(cameraHandler);
  76. //OnLocateScreenEnter += () => Application.targetFrameRate = 30; // 固定识别的帧率,确保摄像机拍到正确的画面
  77. //OnLocateScreenEnd += () => Application.targetFrameRate = 60;
  78. }
  79. public void SetScreenQuad(QuadrilateralInCamera quad) => Screen.QuadInCamera = quad;
  80. // 上一次半自动识别的情况,false代表这条边识别失败,线段顺序: 下、右、上、左
  81. public bool[] LastQuadSemiAutoState;
  82. public event Action OnLocateScreenEnter;
  83. public event Action OnLocateScreenEnd;
  84. public bool bStartLocateScreen { get; set; } = false;//是否进行捕获
  85. public bool SelectScreenAfterLocate(ScreenLocate.ScreenIdentificationTag tag)
  86. {
  87. QuadrilateralInCamera target = GetScreenAfterLocate(tag);
  88. if (target == null)
  89. return false;
  90. Debug.Log($"<color=aqua>[ScreenIdentification] 选择已识别到的屏幕({Enum.GetName(typeof(ScreenLocate.ScreenIdentificationTag), tag)}), {target}</color>");
  91. SetScreenQuad(target);
  92. return true;
  93. }
  94. public QuadrilateralInCamera GetScreenAfterLocate(ScreenLocate.ScreenIdentificationTag tag)
  95. {
  96. return tag switch
  97. {
  98. ScreenLocate.ScreenIdentificationTag.Manual => QuadManual,
  99. ScreenLocate.ScreenIdentificationTag.SemiAuto => QuadSemiAuto,
  100. ScreenLocate.ScreenIdentificationTag.Auto => QuadAuto,
  101. _ => null
  102. };
  103. }
  104. // 自动识别开始的入口
  105. public void LocateScreen(int Capture = 30, int Delay = 30) //数值单位是frame
  106. {
  107. if (ScreenLocate.Main.DebugScreenImages.Count != 0 && ScreenLocate.Main.DebugOnZIMDemo) // 这段仅用于测试图片
  108. {
  109. ScreenLocate.Main.SetCameraSize(new Vector(ScreenLocate.Main.DebugScreenImages[0].width, ScreenLocate.Main.DebugScreenImages[0].height));
  110. DebugImage(ScreenLocate.Main.DebugScreenImages);
  111. Screen.QuadInCamera = quadTemp[0];
  112. ScreenLocate.SetScreen(null);
  113. ScreenLocate.Main.ShowScreen(ScreenLocate.Main.ScreenQuad, Screen.QuadInCamera);
  114. delay = 0;
  115. capture = 0;
  116. ScreenWhiteTexture = null;
  117. ScreenBlackTexture = null;
  118. locateIndex = -1;
  119. areaSelected = -1;
  120. quadTemp.Clear();
  121. sumTemp.Clear();
  122. //ScreenLocate.Main.DebugScreenImages.Clear();
  123. return;
  124. }
  125. delay = Math.Max(Delay, 5);
  126. capture = Math.Max(Capture, 5);
  127. maxDelay = Delay;
  128. maxCapture = Capture;
  129. ScreenLocate.SetScreen(new Rect(0f, 0f, 1f, 1f), UnityEngine.Color.black);
  130. //ScreenLocate.SetScreen(new Rect(0f, 0f, 0.6f, 0.6f), UnityEngine.Color.white);
  131. //bStartLocateScreen = false;
  132. ScreenWhiteTexture = null;
  133. ScreenBlackTexture = null;
  134. OnLocateScreenEnter?.Invoke();
  135. }
  136. /// <summary>
  137. /// 开始进行捕获
  138. /// 初始化了两个数据 capture 和 delay
  139. /// </summary>
  140. /// <returns></returns>
  141. public bool isInitLocateScreen()
  142. {
  143. return capture != 0 && delay != 0;
  144. }
  145. void DebugImage(List<Texture2D> images)
  146. {
  147. QuadrilateralFit(images);
  148. //var watch = new System.Diagnostics.Stopwatch();
  149. //watch.Start();
  150. //var times = new List<double>() { 0.0 };
  151. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  152. Console.WriteLine($"{TAG} quadTemp.Count:{quadTemp.Count}");
  153. #endif
  154. if (quadTemp.Count > 0)
  155. {
  156. ScreenLocate.Main.ShowScreen(ScreenLocate.Main.outputRawImages[4].transform.GetChild(0) as RectTransform, quadTemp[0]);
  157. // 透视变换
  158. // var srcWidth = LocateLightedRedTex.width;
  159. // var transformWidth = (int)((quad.B.x - quad.A.x + quad.D.x - quad.C.x) / 2);
  160. // var transformHeight = (int)((quad.C.y - quad.A.y + quad.D.y - quad.B.y) / 2);
  161. // var transformTex = new Texture2D(transformWidth, transformHeight);
  162. // var pt = new ZIMPerspectiveTransform(new OrdinalQuadrilateral(new Vector(0, 0), new Vector(transformWidth, 0), new Vector(0, transformHeight), new Vector(transformWidth, transformHeight)), quad);
  163. // var dstPixel = new UnityEngine.Color[transformWidth * transformHeight];
  164. // var srcPixel = LocateLightedRedTex.GetPixels();
  165. // Parallel.For(0, transformWidth, (x) =>
  166. // {
  167. // for (int y = 0; y < transformHeight; y++)
  168. // {
  169. // var index = y * transformWidth + x;
  170. // var sampleCoord = pt.TransformRound(x, y);
  171. // dstPixel[index] = srcPixel[sampleCoord.y * srcWidth + sampleCoord.x];
  172. // }
  173. // });
  174. // transformTex.SetPixels(dstPixel);
  175. // transformTex.Apply();
  176. // //ScreenLocate.DebugTexture(1, transformTex);
  177. //#if (!NDEBUG && DEBUG && ENABLE_LOG)
  178. // Console.WriteLine($"{TAG} ScreenLocate.DebugTexture 1:{transformTex.GetNativeTexturePtr()}");
  179. //#endif
  180. }
  181. //times.Add(watch.ElapsedMilliseconds);
  182. //Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  183. }
  184. public void NextScreen()
  185. {
  186. // 只识别一次色差变化
  187. if (LocateSingleStep && areaSelected == -1)
  188. {
  189. LocateAreaData = new Rect[][] { new Rect[] { new Rect(0, 0, 1f, 1f) } };
  190. locateIndex = 3;
  191. areaSelected = 0;
  192. locateArea.AddRange(LocateAreaData[0]);
  193. }
  194. // index从-1开始
  195. locateIndex++;
  196. if (locateIndex < locateArea.Count) // 依次点亮屏幕区域
  197. {
  198. ScreenLocate.SetScreen(locateArea[locateIndex], UnityEngine.Color.white);
  199. delay = maxDelay;
  200. capture = maxCapture;
  201. }
  202. else // 退出屏幕黑白控制
  203. {
  204. ScreenLocate.SetScreen(null);
  205. ScreenLocate.Main.ShowScreen(ScreenLocate.Main.ScreenQuad, Screen.QuadInCamera);
  206. Reset();
  207. }
  208. }
  209. // 清除记录的屏幕识别数据(手动、自动等)
  210. public void ClearQuadCache()
  211. {
  212. SetScreenQuad(null);
  213. QuadManual = null;
  214. QuadSemiAuto = null;
  215. QuadAuto = null;
  216. }
  217. public void Reset()
  218. {
  219. // bStartLocateScreen = false;
  220. delay = 0;
  221. capture = 0;
  222. ScreenWhiteTexture = null;
  223. ScreenBlackTexture = null;
  224. locateIndex = -1;
  225. areaSelected = -1;
  226. if (locateArea.Count > 4)
  227. locateArea.RemoveRange(4, LocateAreaData[0].Length);
  228. quadTemp.Clear();
  229. sumTemp.Clear();
  230. }
  231. public void CaptureBlack(Texture2D cam)
  232. {
  233. if (ScreenBlackTexture == null)
  234. ScreenBlackTexture = new Geometry.Vector<float>[(int)(Size.x * Size.y)];
  235. var pixel = cam.GetPixels();
  236. Parallel.For(0, (int)(Size.x * Size.y), i =>
  237. {
  238. var ip = pixel[i];
  239. ScreenBlackTexture[i] += new Geometry.Vector<float>(ip.r / maxCapture, ip.g / maxCapture, ip.b / maxCapture);
  240. });
  241. }
  242. public void CaptureWhite(Texture2D cam)
  243. {
  244. if (ScreenWhiteTexture == null)
  245. ScreenWhiteTexture = new Geometry.Vector<float>[(int)(Size.x * Size.y)];
  246. var pixel = cam.GetPixels();
  247. Parallel.For(0, (int)(Size.x * Size.y), i =>
  248. {
  249. var ip = pixel[i];
  250. ScreenWhiteTexture[i] += new Geometry.Vector<float>(ip.r / maxCapture, ip.g / maxCapture, ip.b / maxCapture);
  251. });
  252. }
  253. public void CaptureStay(Texture2D cam)
  254. {
  255. if (locateIndex == -1) // 屏幕黑色
  256. {
  257. CaptureBlack(cam);
  258. }
  259. else // 屏幕部分为白色
  260. {
  261. CaptureWhite(cam);
  262. }
  263. }
  264. public void CaptureEnd()
  265. {
  266. //Debug.Log("locateIndex: " + locateIndex + ", quad: " + quadTemp.Count);
  267. if (locateIndex == -1)
  268. return;
  269. if (locateIndex < 4)
  270. {
  271. sumTemp.Add(GetBrightness());
  272. ScreenWhiteTexture = null;
  273. // 选择亮度差最大的区域
  274. if (locateIndex == 3)
  275. {
  276. areaSelected = sumTemp.MaxIndex();
  277. locateArea.AddRange(LocateAreaData[areaSelected]);
  278. }
  279. }
  280. else if (locateIndex >= 4 && locateIndex < locateArea.Count - 1)
  281. {
  282. QuadrilateralFit();
  283. ScreenWhiteTexture = null;
  284. }
  285. else
  286. {
  287. QuadrilateralFit();
  288. if (quadTemp.Count != LocateAreaData[0].Length)
  289. {
  290. Debug.Log($"<color=yellow>[ScreenIdentification] 拟合四边形失败, quadTemp.Count: {quadTemp.Count}</color>");
  291. }
  292. else if (quadTemp.Count == 1)
  293. {
  294. SetScreenQuad(quadTemp[0]);
  295. Debug.Log($"[ScreenIdentification] 拟合成功,识别数据: {Screen.QuadInCamera}");
  296. }
  297. else
  298. {
  299. // Debug.Log($"拟合四边形 2 , quadTemp.Count: {quadTemp.Count}");
  300. // 线性拟合
  301. var xValue = new List<float>() { 0 };
  302. var predicts = new List<Vector>();
  303. foreach (var i in LocateAreaData[0])
  304. xValue.Add(i.size.x);
  305. Vector baseVertex = Vector.Zero; // x==0 时的点
  306. {
  307. foreach (var q in quadTemp)
  308. {
  309. baseVertex += q.Quad[areaSelected];
  310. }
  311. baseVertex /= quadTemp.Count;
  312. }
  313. double rs = 0.0;
  314. for (int i = 0; i < 4; i++)
  315. {
  316. if (i == areaSelected)
  317. {
  318. predicts.Add(baseVertex);
  319. }
  320. else
  321. {
  322. var yValue = new List<Vector>() { baseVertex };
  323. foreach (var q in quadTemp)
  324. {
  325. yValue.Add(q.Quad[i]);
  326. }
  327. var lr = LinerRegression1D.Fit(2, xValue.ToArray(), yValue.ToArray());
  328. rs += lr.RSquared / 3;
  329. predicts.Add(lr.Predict<Vector>(1));
  330. }
  331. }
  332. SetScreenQuad(new QuadrilateralInCamera(predicts, new Vector(Size.x, Size.y)));
  333. Debug.Log($"[ScreenIdentification] 拟合成功,RSquared: {rs}, Quad: {Screen.QuadInCamera}");
  334. //if (rs < 0.8) Screen.Quad = null;
  335. }
  336. OnLocateScreenEnd?.Invoke();
  337. }
  338. }
  339. public bool Update(Texture2D cam)
  340. {
  341. //if (!bStartLocateScreen) return false;
  342. if (delay != 0)
  343. {
  344. //ScreenLocate.Main.CreateUVCTexture2DFocusSizeIfNeeded(1280, 720);
  345. delay--;
  346. if (delay == 0)
  347. {
  348. ScreenLocate.Main.SetCameraSize(new Vector(cam.width, cam.height)); // 记录当前的分辨率
  349. Debug.Log("[ScreenIdentification] 采样纹理,记录采样分辨率: [" + Size.x + ", " + Size.y + "]");
  350. }
  351. return true;
  352. }
  353. if (capture != 0)
  354. {
  355. //ScreenLocate.Main.CreateUVCTexture2DFocusSizeIfNeeded(1280, 720);
  356. CaptureStay(cam);
  357. capture--;
  358. if (capture == 0)
  359. {
  360. CaptureEnd();
  361. NextScreen();
  362. }
  363. return true;
  364. }
  365. return false;
  366. #region Old
  367. /*
  368. if (delay != 0)
  369. {
  370. delay--;
  371. return true;
  372. }
  373. if (capture != 0)
  374. {
  375. capture--;
  376. if (ScreenBlackTexture == null)
  377. ScreenBlackTexture = new Geometry.Vector<float>[Size.x * Size.y];
  378. var pixel = cam.GetPixels();
  379. Parallel.For(0, Size.x * Size.y, i =>
  380. {
  381. var ip = pixel[i];
  382. ScreenBlackTexture[i] += new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  383. });
  384. if (capture == 0)
  385. ScreenLocate.SetScreen(UnityEngine.Color.black);
  386. return true;
  387. }
  388. if (delay != 0)
  389. {
  390. delay--;
  391. return true;
  392. }
  393. if (capture != 0)
  394. {
  395. capture--;
  396. if (ScreenWhiteTexture == null)
  397. ScreenWhiteTexture = new Geometry.Vector<float>[Size.x * Size.y];
  398. var pixel = cam.GetPixels();
  399. Parallel.For(0, Size.x * Size.y, i =>
  400. {
  401. var ip = pixel[i];
  402. ScreenWhiteTexture[i] += new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  403. });
  404. if (capture == 0)
  405. ScreenLocate.SetScreen(UnityEngine.Color.black);
  406. return true;
  407. }
  408. if (delay != 0)
  409. {
  410. delay--;
  411. return true;
  412. }
  413. if (capture != 0)
  414. {
  415. capture--;
  416. var pixel = cam.GetPixels();
  417. Parallel.For(0, Size.x * Size.y, i =>
  418. {
  419. var ip = pixel[i];
  420. ScreenWhiteTexture[i] -= new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  421. });
  422. if (capture == 0)
  423. {
  424. ScreenLocate.SetScreen(null);
  425. UnityEngine.Color[] newPixel = new UnityEngine.Color[Size.x * Size.y];
  426. Parallel.For(0, Size.x * Size.y, i => {
  427. var pi = ScreenWhiteTexture[i] /= capture;
  428. newPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  429. });
  430. //读取数据
  431. //{
  432. // var fileName = "3.bin";
  433. // ScreenLocateTexture = $"2023 04 16 厦门测试数据/{fileName}".FileReadByte<Vector<float>[]>();
  434. // Debug.Log($"Read {fileName}");
  435. // Parallel.For(0, Size.x * Size.y, i =>
  436. // {
  437. // var pi = ScreenLocateTexture[i];
  438. // newPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  439. // });
  440. //}
  441. var ScreenLocateTex = new Texture2D(Size.x, Size.y);
  442. ScreenLocateTex.SetPixels(newPixel);
  443. ScreenLocateTex.Apply();
  444. //ScreenLocate.DebugTexture(2, ScreenLocateTex);
  445. var ScreenLocateTexLighted = ScreenLocateTex.AutoLight(10);
  446. //ScreenLocate.DebugTexture(2, ScreenLocateTexLighted);
  447. //var FileSavePath = Application.persistentDataPath + "/ScreenLocateTexture.bin";
  448. bool Save = ScreenLocate.Main.SaveToggle.isOn;
  449. string time;
  450. if (Save)
  451. {
  452. time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  453. var FileSavePath = $"屏幕定位数据{time}.bin";
  454. FileSavePath.FileWriteByte(ScreenWhiteTexture);
  455. var bytes = ScreenLocateTexLighted.EncodeToPNG();
  456. File.WriteAllBytes($"屏幕定位数据{time}.png", bytes);
  457. Debug.Log("ScreenLocateTexture Saved To: " + FileSavePath);
  458. }
  459. var ScreenLocateTexR = ScreenLocateTexLighted.ToRGB(ColorChannel.Red);
  460. var ScreenLocateTexG = ScreenLocateTexLighted.ToRGB(ColorChannel.Green);
  461. var ScreenLocateTexB = ScreenLocateTexLighted.ToRGB(ColorChannel.Blue);
  462. ScreenLocate.DebugTexture(2, ScreenLocateTexR);
  463. //ScreenLocate.DebugTexture(4, ScreenLocateTexG);
  464. //ScreenLocate.DebugTexture(5, ScreenLocateTexB);
  465. var watch = new System.Diagnostics.Stopwatch();
  466. watch.Start();
  467. var times = new List<double>() { 0.0 };
  468. var ScreenLocateTexLightedMat = ScreenLocateTexLighted.Too0Mat();
  469. //var ScreenLocateTexLightedMat = texture.Too0Mat();
  470. //var (edge, edgeDir) = ScreenLocateTexLightedMat.IdentifyEdge();
  471. var (edge, edgeDir) = ScreenLocateTexLightedMat.zimIdentifyEdgeGradientAny(15);
  472. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradient().ToTex());
  473. //ScreenLocate.DebugTexture(4, edge.ToTex());
  474. var quadLines = ScreenLocateTexLightedMat.IdentifyQuadLSD(edge, edgeDir, out List<Line> lightLines, 30);
  475. var drawLineMap = new MatrixF2D(edge..Size.x, edge.Size.y);
  476. int lineCount = 0;
  477. foreach (var l in quadLines)
  478. {
  479. if (l != null)
  480. {
  481. o0Extension.DrawLine(drawLineMap.DrawLine(l, (x, y) => 1, new Vector(0, 10));
  482. lineCount++;
  483. }
  484. }
  485. if (lineCount == 4)
  486. {
  487. var a = quadLines[0].Intersect(quadLines[3], false).Value;
  488. var b = quadLines[0].Intersect(quadLines[1], false).Value;
  489. var c = quadLines[2].Intersect(quadLines[3], false).Value;
  490. var d = quadLines[1].Intersect(quadLines[2], false).Value;
  491. Quad = new Quadrilateral(a, b, c, d);
  492. if (!Quad.IsInScreen(ScreenLocate.Main.WebCamera.Size))
  493. Quad = null;
  494. }
  495. ScreenLocate.Main.ShowScreen(Quad);
  496. //var lines = edge.IdentifyLineLSD(edgeDir, 100);
  497. ////var lines = ScreenLocateTexLightedMat.IdentifyLineLSD();
  498. //var drawLineMap = new MatrixF2D(edge..Size.x, edge.Size.y);
  499. //var returnMaxLines = lines.Sub(0, 10);
  500. //foreach (var (line, sum, gradient) in returnMaxLines)
  501. // o0Extension.DrawLine(drawLineMap.DrawLine(line, (x, y) => 1, new Vector(0, 10));
  502. ScreenLocate.DebugTexture(3, drawLineMap.ToTex());
  503. //{
  504. // var bytes = drawLineMap.ToTex().EncodeToPNG();
  505. // File.WriteAllBytes($"屏幕定位数据DrawLineMap.png", bytes);
  506. //}
  507. times.Add(watch.ElapsedMilliseconds);
  508. Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  509. //ScreenLocate.DebugTexture(5, edge.IdentifyLine(edgeDir).ToTex());
  510. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientX().ToTex());
  511. //ScreenLocate.DebugTexture(5, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientY().ToTex());
  512. //var convolutionLighted2 = ScreenLocateTexLighted.Too0Mat().IdentifyEdgeVariance().ToTex();
  513. // opecncv处理
  514. // zim
  515. {
  516. //var cvLines = edge.cvHoughLinesP();
  517. //ScreenLocate.DebugTexture(5, cvLines);
  518. //var myLines = Hough.Transform(edgeMat);
  519. //var cvLines = edge.cvLine(myLines);
  520. //ScreenLocate.DebugTexture(5, cvLines);
  521. }
  522. UnityEngine.Object.Destroy(ScreenLocateTex);
  523. //ScreenLocate.DebugTexture(4, convolutionLighted2);
  524. }
  525. return true;
  526. }
  527. /*
  528. var avg = new Geometry4D.Vector<float>();
  529. var pixel = texture.GetPixels();
  530. foreach(var i in pixel.Index())
  531. {
  532. var iP = pixel[i];
  533. avg += new Geometry4D.Vector<float>(iP.r, iP.g, iP.b, iP.a);
  534. }
  535. avg /= pixel.Count();
  536. /*
  537. var (texLightedR, texLightedG, texLightedB) = ToRGB(newTex);
  538. ScreenLocate.DebugTexture(3, texLightedR);
  539. ScreenLocate.DebugTexture(4, texLightedG);
  540. ScreenLocate.DebugTexture(5, texLightedB);
  541. //Debug.Log(avg);
  542. return false;
  543. /**/
  544. #endregion
  545. }
  546. float GetBrightness()
  547. {
  548. UnityEngine.Color[] differPixel = new UnityEngine.Color[(int)(Size.x * Size.y)];
  549. Parallel.For(0, (int)(Size.x * Size.y), i =>
  550. {
  551. var pi = ScreenWhiteTexture[i] - ScreenBlackTexture[i];
  552. differPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  553. });
  554. var sum = 0f;
  555. foreach (var i in differPixel)
  556. {
  557. sum += i.Brightness();
  558. }
  559. sum /= differPixel.Length;
  560. //Debug.Log(sum);
  561. return sum;
  562. }
  563. // 转换成屏幕定位所需的纹理图像
  564. Texture2D ToLocateTex(UnityEngine.Color[] pixels)
  565. {
  566. var ScreenLocateTex = new Texture2D(o0Size.x, o0Size.y);
  567. ScreenLocateTex.SetPixels(pixels);
  568. ScreenLocateTex.Apply();
  569. //ScreenLocate.DebugTexture(2, ScreenLocateTex);
  570. return ScreenLocateTex.AutoLight(10);
  571. //ScreenLocate.DebugTexture(2, ScreenLocateTexLighted);
  572. //var ScreenLocateTexR = ToLocateTex.ToRGB(ColorChannel.Red);
  573. //var ScreenLocateTexG = ToLocateTex.ToRGB(ColorChannel.Green);
  574. //var ScreenLocateTexB = ToLocateTex.ToRGB(ColorChannel.Blue);
  575. //LocateLightedRedTex = ScreenLocateTexR;
  576. //ScreenLocate.DebugTexture(2, ScreenLocateTexR);
  577. //ScreenLocate.DebugTexture(4, ScreenLocateTexG);
  578. //ScreenLocate.DebugTexture(5, ScreenLocateTexB);
  579. //var ScreenLocateTexLightedMat = texture.Too0Mat();
  580. }
  581. /// <param name="lineWidth">识别的最小线段长度</param>
  582. /// <param name="debugImages">这个参数如果不为null且数量大于0,则执行debug操作</param>
  583. void QuadrilateralFit(List<Texture2D> debugImages = null)
  584. {
  585. // 屏幕黑白差值,存放多批次的图像用于识别, 该List数量不能等于 0
  586. List<UnityEngine.Color[]> PixelsMultipleBatches = new List<UnityEngine.Color[]>();
  587. //var sw = new System.Diagnostics.Stopwatch();
  588. //sw.Start();
  589. //读取数据
  590. int batchCount;
  591. if (debugImages != null && debugImages.Count != 0)
  592. {
  593. batchCount = debugImages.Count;
  594. var dSize = debugImages.First().Size();
  595. foreach (var i in debugImages)
  596. {
  597. Debug.Log($"<color=aqua>Debug {i.name}</color>");
  598. if (i.Size() != dSize)
  599. throw new InvalidOperationException("Multiple Debug textures have different sizes");
  600. //PixelsMultipleBatches.Add(i.GetPixels());
  601. }
  602. }
  603. else // 获得屏幕差值
  604. {
  605. var differPixel = new UnityEngine.Color[(int)(Size.x * Size.y)];
  606. var whitePixel = new UnityEngine.Color[(int)(Size.x * Size.y)];
  607. Parallel.For(0, (int)Size.x, x =>
  608. {
  609. for (int y = 0; y < (int)Size.y; y++)
  610. {
  611. var i = y * (int)Size.x + x;
  612. var d = ScreenWhiteTexture[i] - ScreenBlackTexture[i];
  613. differPixel[i] = new UnityEngine.Color(d.x, d.y, d.z);
  614. whitePixel[i] = new UnityEngine.Color(ScreenWhiteTexture[i].x, ScreenWhiteTexture[i].y, ScreenWhiteTexture[i].z);
  615. }
  616. });
  617. PixelsMultipleBatches.Add(differPixel); // 色差图
  618. PixelsMultipleBatches.Add(whitePixel); // 原图
  619. batchCount = PixelsMultipleBatches.Count;
  620. }
  621. int conSize = (int)Math.Ceiling(0.007f * Size.y) * 2 + 1;
  622. conSize = Math.Max(conSize, 7); // 设置最小为7
  623. float minLength = conSize * 7.7f;
  624. minLength = locateIndex == -1 ? minLength : minLength * areaPercent; // minLength需要按areaPercent比例缩小
  625. string log = $"[Log][ScreenLocate Auto] Size: ({Size.x},{Size.y}), 卷积核Size: {conSize}, 最小线段长度: {minLength}";
  626. var allLines = new List<LineIdentified>();
  627. List<Texture2D> LocateTexTemp = new List<Texture2D>();
  628. List<Matrix> ScreenLocateMatList = new List<Matrix>();
  629. for (int batch = 0; batch < batchCount; batch++)
  630. {
  631. Texture2D locateTex;
  632. if (debugImages != null && debugImages.Count != 0)
  633. locateTex = debugImages[batch];
  634. else
  635. locateTex = ToLocateTex(PixelsMultipleBatches[batch]);
  636. LocateTexTemp.Add(locateTex);
  637. var ScreenLocateMat = locateTex.Too0Mat(); // 用于获取Lines的Matrix
  638. var lineCount = ZIMIdentifyQuadLSD(
  639. ref allLines,
  640. batch,
  641. ScreenLocateMat.zimIdentifyEdgeGradientAny(conSize),
  642. minLength,
  643. new Vector(minLength * 0.4f, conSize * 1.6f));
  644. log += $"\r\n识别图片{batch}, 识别到的线段数量为: {lineCount}";
  645. ScreenLocateMatList.Add(ScreenLocateMat);
  646. }
  647. Texture2D ScreenLocateTexture = LocateTexTemp[0]; // 色差图,for output
  648. // LSD计算得到的矩阵尺寸较小(因为卷积),这里必须进行位移
  649. // 新增:根据阈值筛去梯度太低的线段
  650. float minGradient = 0.08f;
  651. var offset = new Vector((conSize - 1) / 2, (conSize - 1) / 2);
  652. var tempList = new List<LineIdentified>();
  653. for (int i = 0; i < allLines.Count; i++)
  654. {
  655. var l = allLines[i];
  656. if (l.Gradient > minGradient * l.Line.Length)
  657. {
  658. l.Offset(offset);
  659. tempList.Add(l);
  660. }
  661. }
  662. allLines = tempList;
  663. log += $"\r\n根据梯度阈值筛选,最终线段数量为: {allLines.Count}";
  664. // 如果有手动数据,刷新一下Size
  665. QuadManual?.ReSize(new Vector(Size.x, Size.y), ScreenMap.ViewAspectRatioSetting);
  666. // 估算屏幕中点,如果已有手动定位数据,根据现有数据取平均即可,否则从色差计算,ScreenLocateMatList[0]默认是屏幕的黑白色差
  667. Vector AvgPoint = QuadManual != null ? QuadManual.Quad.Centroid : GetAvgPoint(ScreenLocateMatList[0]);
  668. // 过滤得到四边形的四条边,
  669. var (quadLinesSemiAuto, quadLinesAuto) = FilterLines(
  670. ScreenLocateMatList,
  671. allLines,
  672. AvgPoint,
  673. out LineIdentified[] manualLines,
  674. out List<LineIdentified> possibleLines,
  675. conSize,
  676. minLength);
  677. #region 全自动识别的结果
  678. List<LineIdentified> LineIdentifiedAuto = new List<LineIdentified>(); // 线段顺序: 下、右、上、左
  679. for (int i = 0; i < 4; i++)
  680. {
  681. if (quadLinesAuto[i] != null)
  682. LineIdentifiedAuto.Add(quadLinesAuto[i]);
  683. }
  684. if (LineIdentifiedAuto.Count == 4) // 判断识别的线段能否拼成屏幕,能拼成则记录
  685. {
  686. var a = LineIdentifiedAuto[0].Line.Intersect(LineIdentifiedAuto[3].Line, false).Value;
  687. var b = LineIdentifiedAuto[0].Line.Intersect(LineIdentifiedAuto[1].Line, false).Value;
  688. var c = LineIdentifiedAuto[2].Line.Intersect(LineIdentifiedAuto[3].Line, false).Value;
  689. var d = LineIdentifiedAuto[1].Line.Intersect(LineIdentifiedAuto[2].Line, false).Value;
  690. QuadAuto = new QuadrilateralInCamera(a, b, c, d, new Vector(Size.x, Size.y));
  691. if (!QuadAuto.IsQuadComplete())
  692. QuadAuto = null;
  693. }
  694. #endregion
  695. #region 半自动识别
  696. List<LineIdentified> LineIdentifiedSemiAuto = new List<LineIdentified>(); // 线段顺序: 下、右、上、左
  697. LastQuadSemiAutoState = new bool[4] { true, true, true, true };
  698. for (int i = 0; i < 4; i++)
  699. {
  700. if (quadLinesSemiAuto[i] != null)
  701. LineIdentifiedSemiAuto.Add(quadLinesSemiAuto[i]);
  702. else if (manualLines != null)
  703. {
  704. LineIdentifiedSemiAuto.Add(manualLines[i]);
  705. LastQuadSemiAutoState[i] = false;
  706. }
  707. }
  708. if (LineIdentifiedSemiAuto.Count == 4) // 判断识别的线段能否拼成屏幕,能拼成则记录
  709. {
  710. var a = LineIdentifiedSemiAuto[0].Line.Intersect(LineIdentifiedSemiAuto[3].Line, false).Value;
  711. var b = LineIdentifiedSemiAuto[0].Line.Intersect(LineIdentifiedSemiAuto[1].Line, false).Value;
  712. var c = LineIdentifiedSemiAuto[2].Line.Intersect(LineIdentifiedSemiAuto[3].Line, false).Value;
  713. var d = LineIdentifiedSemiAuto[1].Line.Intersect(LineIdentifiedSemiAuto[2].Line, false).Value;
  714. QuadSemiAuto = new QuadrilateralInCamera(a, b, c, d, new Vector(Size.x, Size.y));
  715. if (!QuadSemiAuto.IsQuadComplete())
  716. QuadSemiAuto = null;
  717. }
  718. #endregion
  719. // 优先应用自动的结果(也可以在外部手动设置)
  720. if (QuadSemiAuto == null && QuadAuto == null && Screen.QuadInCamera != null) // 如果可能,回退到上一个screen
  721. {
  722. Debug.Log($"<color=yellow>[ScreenIdentification] 本次识别失败,回退到上次的识别结果: {Screen.QuadInCamera}</color>");
  723. quadTemp.Add(Screen.QuadInCamera);
  724. }
  725. else if (QuadAuto != null)
  726. {
  727. Debug.Log($"<color=aqua>[ScreenIdentification] 识别到四边形(全自动): {QuadAuto}</color>");
  728. quadTemp.Add(QuadAuto);
  729. }
  730. else if (QuadSemiAuto != null)
  731. {
  732. Debug.Log($"<color=aqua>[ScreenIdentification] 识别到四边形(半自动): {QuadSemiAuto}</color>");
  733. quadTemp.Add(QuadSemiAuto);
  734. }
  735. #region 绘制 output texture
  736. // 绘制半自动
  737. var ScreenQuadMap = new Matrix(o0Size, Tiling: true); // 识别的到的屏幕四边形(半自动和自动在一张图上)
  738. foreach (var i in LineIdentifiedSemiAuto.Index())
  739. {
  740. if (LastQuadSemiAutoState[i])
  741. o0Extension.DrawLine(ScreenQuadMap, LineIdentifiedSemiAuto[i].DrawLine, (x, y) => 5, new Vector(0, 10));
  742. else
  743. o0Extension.DrawLine(ScreenQuadMap, LineIdentifiedSemiAuto[i].DrawLine, (x, y) => 3, new Vector(0, 6), true);
  744. }
  745. // 绘制全自动
  746. foreach (var i in LineIdentifiedAuto.Index())
  747. o0Extension.DrawLine(ScreenQuadMap, LineIdentifiedAuto[i].DrawLine, (x, y) => 4, new Vector(0, 4), true);
  748. Texture2D ScreenQuad = ScreenQuadMap.ToTexRGBA(FloatValueToColor);
  749. Texture2D ScreenQuadWithScreen = ScreenQuad.Overlay(ScreenLocateTexture); // 叠加屏幕色差图
  750. // 绘制allLines
  751. var allLinesMap = new Matrix(o0Size, Tiling: true);
  752. foreach (var l in allLines)
  753. {
  754. if (l.DrawLine != null)
  755. o0Extension.DrawLine(allLinesMap, l.DrawLine, (x, y) => 1, new Vector(0, 2), true);
  756. }
  757. var allLinesTex = allLinesMap.ToTexRGBA(FloatValueToColor);
  758. ScreenLocate.DebugTexture(1, allLinesTex);
  759. // 还需要输出一张识别结果图,包含干扰线段
  760. var ChoosableLineMap = new Matrix(o0Size, Tiling: true);
  761. foreach (var l in possibleLines)
  762. {
  763. if (l != null && !quadLinesSemiAuto.Contains(l) && !manualLines.Contains(l))
  764. o0Extension.DrawLine(ChoosableLineMap, l.DrawLine, (x, y) => 1, new Vector(0, 2), true); // 其他的备选线段
  765. }
  766. foreach (var l in LineIdentifiedSemiAuto)
  767. {
  768. if (l != null)
  769. o0Extension.DrawLine(ChoosableLineMap, l.DrawLine, (x, y) => 5, new Vector(0, 5)); // 识别的结果
  770. }
  771. if (manualLines != null)
  772. {
  773. foreach (var l in manualLines)
  774. o0Extension.DrawLine(ChoosableLineMap, l.DrawLine, (x, y) => 3, new Vector(0, 2), true); // 旧的屏幕线段(例如上次手动识别的)
  775. }
  776. Texture2D ChoosableLineTex = ChoosableLineMap.ToTexRGBA(FloatValueToColor);
  777. #endregion
  778. log += $"\r\n屏幕四边形_手动识别{QuadManual != null}\r\n屏幕四边形_半自动识别{QuadSemiAuto != null}\r\n屏幕四边形_全自动识别{QuadAuto != null}";
  779. Debug.Log(log);
  780. // 是否将图片保存到本地
  781. if (ScreenLocate.Main.SaveToggle?.isOn ?? false && ScreenLocate.Main.DebugOnZIMDemo)
  782. {
  783. var FileDirectory = $"Debug_屏幕定位/";
  784. SaveImages(FileDirectory, log, ScreenLocateTexture, allLinesTex, ChoosableLineTex, ScreenQuad);
  785. }
  786. //times.Add(watch.ElapsedMilliseconds);
  787. //Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  788. // opecncv处理, zim
  789. {
  790. //var cvLines = edge.cvHoughLinesP();
  791. //ScreenLocate.DebugTexture(5, cvLines);
  792. //var myLines = Hough.Transform(edgeMat);
  793. //var cvLines = edge.cvLine(myLines);
  794. //ScreenLocate.DebugTexture(5, cvLines);
  795. }
  796. {
  797. ScreenLocate.DebugTexture(2, ScreenLocateTexture);
  798. ScreenLocate.DebugTexture(3, ScreenQuad);
  799. ScreenLocate.DebugTexture(4, ScreenQuadWithScreen);
  800. ScreenLocate.DebugTexture(5, ChoosableLineTex);
  801. }
  802. foreach (var i in LocateTexTemp)
  803. {
  804. if (i != ScreenLocateTexture) // ScreenLocateTexture 由 ScreenLocate.DebugTexture 释放
  805. GameObject.Destroy(i);
  806. }
  807. }
  808. Vector GetAvgPoint(Matrix screenLocateMat)
  809. {
  810. // 加权平均
  811. Vector[] avgPointsColumn = new Vector[screenLocateMat.Size.x];
  812. float[] valueSumsColumn = new float[screenLocateMat.Size.x];
  813. Parallel.For(0, screenLocateMat.Size.x, i =>
  814. {
  815. for (int j = 0; j < screenLocateMat.Size.y; j++)
  816. {
  817. var value = screenLocateMat[i, j];
  818. valueSumsColumn[i] += value;
  819. avgPointsColumn[i] += new Vector(i, j) * value;
  820. }
  821. });
  822. Vector avgPoint = Vector.Zero;
  823. var valueSum = 0f;
  824. for (int i = 0; i < screenLocateMat.Size.x; i++)
  825. {
  826. avgPoint += avgPointsColumn[i];
  827. valueSum += valueSumsColumn[i];
  828. }
  829. avgPoint /= valueSum;
  830. return avgPoint;
  831. }
  832. // 返回查找到的线段数量,0是查找失败
  833. int ZIMIdentifyQuadLSD(ref List<LineIdentified> allLines, int batch, (Matrix edgeMat, Matrix edgeDirMat) edgeGradient,
  834. float minLength, Vector LineCaptureSize)
  835. {
  836. var l = edgeGradient.edgeMat.IdentifyLineLSD(edgeGradient.edgeDirMat, minLength, 25, LineCaptureSize);
  837. if (l == null || l.Count == 0)
  838. return 0;
  839. allLines.AddRange(l.Select((i) => new LineIdentified(batch, i)));
  840. return l.Count;
  841. }
  842. // 返回四边形的四条边(半自动、全自动),List长度一定是4 (如果没有识别到就是null),且线段顺序是: 下、右、上、左
  843. (List<LineIdentified>, List<LineIdentified>) FilterLines(List<Matrix> screenLocateMatList, List<LineIdentified> allLines, Vector avgPoint,
  844. out LineIdentified[] manualLines, out List<LineIdentified> possibleLines, float gradientLength, float minLength = 100)
  845. {
  846. // 筛掉椭圆框外的线段(超出一半会筛掉)
  847. var innerLines = new List<LineIdentified>();
  848. for (int i = 0; i < allLines.Count; i++)
  849. {
  850. List<Vector> InArea = new List<Vector>();
  851. var dir = (allLines[i].Line.B - allLines[i].Line.A) / 4;
  852. var points = new Vector[5] { allLines[i].Line.A, allLines[i].Line.A + dir, allLines[i].Line.A + dir * 2f, allLines[i].Line.A + dir * 3f, allLines[i].Line.B }; // A点、中间的点、B点
  853. for (int pI = 0; pI < points.Length; pI++)
  854. {
  855. if (ScreenLocate.Main.ScreenPixelCheaker != null && !ScreenLocate.Main.ScreenPixelCheaker.OutArea2D(points[pI], Size))
  856. InArea.Add(points[pI]);
  857. }
  858. if (InArea.Count < 2) // 少于2个点在内部
  859. continue;
  860. else if (InArea.Count < points.Length) // 不完全在内部
  861. allLines[i].DrawLine = new Line(InArea.First(), InArea.Last()); // 将部分线条设置为drawline,用于下一步的绘制
  862. else // 线段全部在椭圆内
  863. allLines[i].DrawLine = allLines[i].Line;
  864. innerLines.Add(allLines[i]);
  865. }
  866. // 角度阈值,用来判断线段的梯度方向是否指向屏幕中心(avgPoint)
  867. var avaAngleHalf = 75f;
  868. // 评估屏幕内部的Line
  869. var interLineGuess = new InterLineGuess(screenLocateMatList, gradientLength * 2, minLength);
  870. #region 内部函数
  871. float ScreenGrad(LineIdentified line)
  872. {
  873. var dir = (line.Line.B - line.Line.A).Normalized;
  874. var vertical = new Vector(-dir.y, dir.x) * (gradientLength / 2);
  875. int step = (int)(minLength / 5);
  876. var ll = line.Line.Length;
  877. var lg = new List<float>();
  878. for (int i = 0; i <= ll; i += step)
  879. {
  880. var point = line.Line.A + dir * i;
  881. var ga = point + vertical;
  882. var gb = point - vertical;
  883. lg.Add(screenLocateMatList[line.Batch][(int)ga.x, (int)ga.y] - screenLocateMatList[line.Batch][(int)gb.x, (int)gb.y]);
  884. }
  885. return Math.Abs(lg.Mean());
  886. }
  887. // 沿直线计算综合梯度(梯度乘以长度系数,再乘以距离系数), distanceRatio是实际距离除以距离阈值
  888. float estimateGradient(LineIdentified line, float distanceRatio)
  889. {
  890. var gM = ScreenGrad(line);
  891. if (line.Batch > 0) // 其他batch的图,梯度权重小
  892. gM /= 3;
  893. float e = (float)Math.Sqrt(Math.Ceiling(line.Line.Length / minLength)); // 长度系数,筛选时梯度更大、长度更长的线段更优
  894. float d = (10f - distanceRatio * distanceRatio) / 10f; // 距离系数,距离越近,系数越大
  895. line.ZIMGradient = e * gM + d; // 记录一下综合梯度,新增的识别黑边功能会二次使用
  896. return line.ZIMGradient;
  897. }
  898. // 根据线段梯度的角度,判断是不是屏幕的边,index代表是哪条边(顺序是: 下、右、上、左)
  899. void GetScreenLineIndex(LineIdentified line)
  900. {
  901. var a = (avgPoint - (line.Line.A + line.Line.B) / 2).DegreeToXAxis();
  902. //Debug.Log(a + ", " + gradient + ", " + sum);
  903. var index = -1;
  904. if (Math.Abs(a - line.GradientDegree) < avaAngleHalf || Math.Abs(a - 360 - line.GradientDegree) < avaAngleHalf || Math.Abs(a + 360 - line.GradientDegree) < avaAngleHalf)
  905. {
  906. if (line.GradientDegree > 45 && line.GradientDegree < 135) // 下
  907. index = 0;
  908. else if (line.GradientDegree > 135 && line.GradientDegree < 225) // 右
  909. index = 1;
  910. else if (line.GradientDegree > 225 && line.GradientDegree < 315) // 上
  911. index = 2;
  912. else
  913. index = 3;
  914. }
  915. line.ScreenLineIndex = index;
  916. }
  917. #endregion
  918. // 根据梯度方向,判断是哪条边
  919. foreach (var l in innerLines)
  920. GetScreenLineIndex(l);
  921. // 下、右、上、左, 半自动和自动
  922. var quadLinesSemiAuto = new List<(float, LineIdentified)>[4] { new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>() };
  923. var quadLinesAuto = new List<(float, LineIdentified)>[4] { new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>(), new List<(float, LineIdentified)>() };
  924. possibleLines = new List<LineIdentified>();
  925. #region 半自动(利用手动数据)
  926. // 如果已有手动定位数据,根据现有数据筛选线条(半自动)
  927. manualLines = null;
  928. if (QuadManual != null)
  929. {
  930. Debug.Log($"[IdentifyLineLSD] 根据已有定位数据做筛选, QuadManual: {QuadManual}");
  931. manualLines = QuadManual.GetLines().Select((i) => new LineIdentified(0, i, 0, 0, true)).ToArray();
  932. var calibration = ScreenLocate.Main.ReDoLocateCalibrationRatio * Size.y;
  933. var distanceMeasure = 0.02f * Size.y;
  934. var avgPointCross = manualLines.Select((i) => i.Line.LineCrossWithPoint(avgPoint)).ToArray(); // 对于平均点的corss值
  935. var avgPointPedal = manualLines.Select((i) => o0Extension.PointPedal(i.Line, avgPoint, out _)).ToArray(); // 当前定位的垂足,下、右、上、左
  936. foreach (var line in innerLines)
  937. {
  938. // 筛选条件:1-梯度方向匹配,2-垂足的距离足够近, 3-线段的AB点均在旧线段外部, 4-新的线段的中点,到旧线段的垂足,要在旧线段内
  939. if (line.ScreenLineIndex >= 0)
  940. {
  941. var distanceToOld = (o0Extension.PointPedal(line.Line, avgPoint, out _) - avgPointPedal[line.ScreenLineIndex]).Length;
  942. if (distanceToOld < calibration &&
  943. manualLines[line.ScreenLineIndex].Line.LineCrossWithPoint(line.Line.A) * avgPointCross[line.ScreenLineIndex] <= 0 &&
  944. manualLines[line.ScreenLineIndex].Line.LineCrossWithPoint(line.Line.B) * avgPointCross[line.ScreenLineIndex] <= 0)
  945. {
  946. var middleToOldLine = o0Extension.PointPedal(manualLines[line.ScreenLineIndex].Line, (line.Line.A + line.Line.B) / 2, out bool inLineSegment);
  947. if (inLineSegment)
  948. {
  949. quadLinesSemiAuto[line.ScreenLineIndex].Add((estimateGradient(line, (float)Math.Floor(distanceToOld / distanceMeasure)), line));
  950. possibleLines.Add(line);
  951. }
  952. }
  953. }
  954. }
  955. }
  956. // 获得结果
  957. var resultSemiAuto = new LineIdentified[4];
  958. var resultSemiAutoPedal = new Vector[4]; // 用于找平行线
  959. for (int i = 0; i < 4; i++)
  960. {
  961. resultSemiAuto[i] = quadLinesSemiAuto[i].Max((a, b) => a.Item1.CompareTo(b.Item1)).Item2;
  962. if (resultSemiAuto[i] != null)
  963. resultSemiAutoPedal[i] = o0Extension.PointPedal(resultSemiAuto[i].Line, avgPoint, out _);
  964. }
  965. // 新增功能(解决黑边问题):根据 result 再找平行线,判断是否替换(1-在 result 内部,且离中点最近,2-接近平行)
  966. UpdateResultlines(resultSemiAuto, FindInterLinePair(
  967. interLineGuess,
  968. GetInterSelectableLines(quadLinesSemiAuto, resultSemiAuto, resultSemiAutoPedal, avgPoint)));
  969. #endregion
  970. #region 全自动
  971. // 全自动
  972. foreach (var line in innerLines)
  973. {
  974. if (line.ScreenLineIndex >= 0 && line.Batch < 1) // 全自动只处理第一张图,默认是色差图
  975. {
  976. quadLinesAuto[line.ScreenLineIndex].Add((estimateGradient(line, 1), line));
  977. }
  978. }
  979. // 获得结果
  980. var resultAuto = new LineIdentified[4];
  981. var resultAutoPedal = new Vector[4]; // 用于找平行线
  982. for (int i = 0; i < 4; i++)
  983. {
  984. resultAuto[i] = quadLinesAuto[i].Max((a, b) => a.Item1.CompareTo(b.Item1)).Item2;
  985. if (resultAuto[i] != null)
  986. resultAutoPedal[i] = o0Extension.PointPedal(resultAuto[i].Line, avgPoint, out _);
  987. }
  988. // 新增功能(解决黑边问题):根据 resultAuto 再找平行线,判断是否替换(1-在 result 内部,且离中点最近,2-接近平行,3-LineGuess判断是直线)
  989. UpdateResultlines(resultAuto, FindInterLinePair(
  990. interLineGuess,
  991. GetInterSelectableLines(quadLinesAuto, resultAuto, resultAutoPedal, avgPoint)));
  992. #endregion
  993. return (resultSemiAuto.ToList(), resultAuto.ToList());
  994. }
  995. List<LineIdentified> GetInterSelectableLines(List<(float, LineIdentified)>[] quadLines, LineIdentified[] resultLines, Vector[] resultPedal, Vector avgPoint)
  996. {
  997. var result = new List<LineIdentified>();
  998. foreach (var ql in quadLines)
  999. {
  1000. foreach (var (_, line) in ql)
  1001. {
  1002. if (line != resultLines[line.ScreenLineIndex] && line.Batch < 1) // batch0才做黑边的内部线条检测
  1003. {
  1004. var pedal = o0Extension.PointPedal(line.Line, avgPoint, out _);
  1005. var a0 = pedal - avgPoint;
  1006. var a0L = a0.Length;
  1007. line.DistanceToMiddle = a0L;
  1008. var a1 = resultPedal[line.ScreenLineIndex] - avgPoint;
  1009. var a1L = a1.Length;
  1010. if (a0L < a1L)
  1011. {
  1012. var dotN = a0.Dot(a1) / a0L / a1L;
  1013. if (Math.Abs(dotN - 1) < 0.002) // 接近平行即可
  1014. result.Add(line);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. return result;
  1020. }
  1021. void UpdateResultlines(LineIdentified[] result, (LineIdentified a, LineIdentified b) inter)
  1022. {
  1023. if (inter.a != null) // 替换上一步筛选的结果中的部分边,得到最终的结果
  1024. result[inter.a.ScreenLineIndex] = inter.a;
  1025. if (inter.b != null)
  1026. result[inter.b.ScreenLineIndex] = inter.b;
  1027. }
  1028. (LineIdentified a, LineIdentified b) FindInterLinePair(InterLineGuess lineGuess, List<LineIdentified> interSelectable, int maxCountToSelect = 8)
  1029. {
  1030. Debug.Log("[ScreenIdentification] selectable inter line count: " + interSelectable.Count);
  1031. interSelectable.Sort((a, b) => b.ZIMGradient.CompareTo(a.ZIMGradient));
  1032. int count = 0;
  1033. LineIdentified[] selected = new LineIdentified[4];
  1034. foreach (var line in interSelectable)
  1035. {
  1036. if (line.GuessIsInterLine(lineGuess)) // 评价是不是Line, 并且找到离中心点最近的
  1037. {
  1038. if (ScreenLocate.Main.DebugOnZIMDemo)
  1039. Debug.Log($"[ScreenIdentification] {interSelectable.IndexOf(line)}, guess is line: (index)" + line.ScreenLineIndex);
  1040. if (selected[line.ScreenLineIndex] == null || selected[line.ScreenLineIndex].DistanceToMiddle > line.DistanceToMiddle)
  1041. selected[line.ScreenLineIndex] = line;
  1042. }
  1043. if (count++ >= maxCountToSelect)
  1044. break;
  1045. }
  1046. var selectedList = new List<LineIdentified>();
  1047. foreach (var i in selected)
  1048. {
  1049. if (i != null)
  1050. selectedList.Add(i);
  1051. }
  1052. if (selectedList.Count == 4)
  1053. {
  1054. if (selected[0].ZIMGradient + selected[2].ZIMGradient > selected[1].ZIMGradient + selected[3].ZIMGradient)
  1055. return (selected[0], selected[2]);
  1056. else
  1057. return (selected[1], selected[3]);
  1058. }
  1059. else if (selected[0] != null && selected[2] != null)
  1060. return (selected[0], selected[2]);
  1061. else if (selected[1] != null && selected[3] != null)
  1062. return (selected[1], selected[3]);
  1063. else if (selectedList.Count == 2)
  1064. return selectedList[0].ZIMGradient > selectedList[1].ZIMGradient ? (selectedList[0], null) : (selectedList[1], null);
  1065. else if (selectedList.Count == 1)
  1066. return (selectedList[0], null);
  1067. else
  1068. return (null, null);
  1069. }
  1070. void SaveImages(string FileDirectory, string log,
  1071. Texture2D ScreenLocateTex, Texture2D allLinesTex, Texture2D ChoosableLineTex, Texture2D ScreenQuadTex)
  1072. {
  1073. if (!Directory.Exists(FileDirectory))
  1074. Directory.CreateDirectory(FileDirectory);
  1075. var time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  1076. var pngData = ScreenLocate.Main.OutputTextures[7]?.EncodeToPNG();
  1077. if (pngData != null)
  1078. File.WriteAllBytes($"{FileDirectory}{time}A屏幕原图.png", pngData);
  1079. var pngData1 = ScreenLocateTex?.EncodeToPNG();
  1080. if (pngData1 != null)
  1081. File.WriteAllBytes($"{FileDirectory}{time}B黑白色差.png", pngData1);
  1082. var pngData2 = allLinesTex?.EncodeToPNG();
  1083. if (pngData2 != null)
  1084. File.WriteAllBytes($"{FileDirectory}{time}C全部识别线段_半自动.png", pngData2);
  1085. var pngData3 = ChoosableLineTex?.EncodeToPNG();
  1086. if (pngData3 != null)
  1087. File.WriteAllBytes($"{FileDirectory}{time}D备选线段_半自动.png", pngData3);
  1088. var pngData4 = ScreenQuadTex?.EncodeToPNG();
  1089. if (pngData4 != null)
  1090. File.WriteAllBytes($"{FileDirectory}{time}E识别结果.png", pngData4);
  1091. Debug.Log($"<color=aqua>({time}) 屏幕识别图片保存至:程序根目录/{FileDirectory}</color>");
  1092. log +=
  1093. $"\r\n屏幕原图保存{pngData != null}, " +
  1094. $"\r\n黑白色差保存{pngData1 != null}, " +
  1095. $"\r\n全部识别线段(半自动)保存{pngData2 != null}, " +
  1096. $"\r\n备选线段(半自动)保存{pngData3 != null}, " +
  1097. $"\r\n识别结果保存{pngData4 != null}";
  1098. File.WriteAllText($"{FileDirectory}{time}屏幕自动定位_日志.log", log);
  1099. }
  1100. }
  1101. }