ScreenIdentification.cs 56 KB

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