ScreenIdentification.cs 49 KB

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