ScreenIdentification.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. #define ENABLE_LOG
  2. using o0.Geometry2D.Float;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Threading.Tasks;
  7. using UnityEngine;
  8. using ZIM;
  9. using ZIM.Unity;
  10. namespace o0.Project
  11. {
  12. public partial class ScreenIdentification
  13. {
  14. private const string TAG = "ScreenIdentification#";
  15. //static Rect[][] LocateAreaData = new Rect[][] {
  16. // 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) },
  17. // 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) },
  18. // 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) },
  19. // 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) }
  20. //};
  21. static Rect[][] LocateAreaData = new Rect[][] {
  22. 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) },
  23. 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) },
  24. 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) },
  25. 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) }
  26. };
  27. //static bool LocateDebug = false;
  28. static bool LocateDebug = true;
  29. public Geometry2D.Vector<int> Size { get; private set; }
  30. public ScreenMap Screen; // 识别到的屏幕,用于执行透视变换
  31. int capture = 0;
  32. int delay = 0;
  33. int maxCapture;
  34. int maxDelay;
  35. Geometry.Vector<float>[] ScreenBlackTexture;
  36. Geometry.Vector<float>[] ScreenWhiteTexture;
  37. int locateIndex = -1;
  38. List<Rect> locateArea = new List<Rect> {
  39. 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)
  40. }; // 屏幕显示白色的区域大小
  41. float areaPercent => locateArea[locateIndex].size.x; // 当前白色区域的占比
  42. int areaSelected = -1; // 选择哪个区域,顺序与Quadrilateral对应
  43. List<float> sumTemp = new List<float>();
  44. List<OrdinalQuadrilateral> quadTemp = new List<OrdinalQuadrilateral>();
  45. //public ScreenIdentification(WebCamTexture texture)
  46. //{
  47. // Size = new Geometry2D.Vector<int>(texture.width, texture.height);
  48. // Screen = new ScreenMap();
  49. //}
  50. public ScreenIdentification(Texture texture)
  51. {
  52. Size = new Geometry2D.Vector<int>(texture.width, texture.height);
  53. Screen = new ScreenMap();
  54. }
  55. public ScreenIdentification(Geometry2D.Vector<int> size)
  56. {
  57. Size = size;
  58. Screen = new ScreenMap();
  59. }
  60. public void LocateScreenManual(OrdinalQuadrilateral quad) => Screen.Quad = quad;
  61. public void LocateScreen(int Capture = 30, int Delay = 30)//frame
  62. {
  63. if (ScreenLocate.Main.DebugScreenImage != null) // 测试图片
  64. {
  65. DebugImage(ScreenLocate.Main.DebugScreenImage);
  66. return;
  67. }
  68. delay = Delay;
  69. capture = Capture;
  70. maxDelay = Delay;
  71. maxCapture = Capture;
  72. ScreenLocate.SetScreen(new Rect(0f, 0f, 1f, 1f), UnityEngine.Color.black);
  73. //ScreenLocate.SetScreen(new Rect(0f, 0f, 0.6f, 0.6f), UnityEngine.Color.white);
  74. }
  75. void DebugImage(Texture2D image)
  76. {
  77. QuadrilateralFit(out Texture2D LocateTex, out Texture2D DrawLineTex, image);
  78. ScreenLocate.DebugTexture(2, LocateTex);
  79. ScreenLocate.DebugTexture(3, DrawLineTex);
  80. //Debug.Log(quadTemp[0]);
  81. //var watch = new System.Diagnostics.Stopwatch();
  82. //watch.Start();
  83. //var times = new List<double>() { 0.0 };
  84. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  85. Console.WriteLine($"{TAG} quadTemp.Count:{ quadTemp.Count}");
  86. #endif
  87. if (quadTemp.Count > 0)
  88. {
  89. // 透视变换
  90. var quad = quadTemp[0];
  91. var srcWidth = LocateTex.width;
  92. var transformWidth = (int)((quad.B.x - quad.A.x + quad.D.x - quad.C.x) / 2);
  93. var transformHeight = (int)((quad.C.y - quad.A.y + quad.D.y - quad.B.y) / 2);
  94. var transformTex = new Texture2D(transformWidth, transformHeight);
  95. var pt = new ZIMPerspectiveTransform(new OrdinalQuadrilateral(new Vector(0, 0), new Vector(transformWidth, 0), new Vector(0, transformHeight), new Vector(transformWidth, transformHeight)), quad);
  96. var dstPixel = new UnityEngine.Color[transformWidth * transformHeight];
  97. var srcPixel = LocateTex.GetPixels();
  98. Parallel.For(0, transformWidth, (x) =>
  99. {
  100. for (int y = 0; y < transformHeight; y++)
  101. {
  102. var index = y * transformWidth + x;
  103. var sampleCoord = pt.TransformRound(x, y);
  104. dstPixel[index] = srcPixel[sampleCoord.y * srcWidth + sampleCoord.x];
  105. }
  106. });
  107. transformTex.SetPixels(dstPixel);
  108. transformTex.Apply();
  109. ScreenLocate.DebugTexture(1, transformTex);
  110. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  111. Console.WriteLine($"{TAG} ScreenLocate.DebugTexture 1:{ transformTex.GetNativeTexturePtr()}");
  112. #endif
  113. }
  114. //times.Add(watch.ElapsedMilliseconds);
  115. //UnityEngine.Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  116. }
  117. public void NextScreen()
  118. {
  119. // 测试用
  120. if (LocateDebug && areaSelected == -1)
  121. {
  122. LocateAreaData = new Rect[][] { new Rect[] { new Rect(0, 0, 1f, 1f) } };
  123. locateIndex = 3;
  124. areaSelected = 0;
  125. locateArea.AddRange(LocateAreaData[0]);
  126. }
  127. // index从-1开始
  128. locateIndex++;
  129. if (locateIndex < locateArea.Count) // 依次点亮屏幕区域
  130. {
  131. ScreenLocate.SetScreen(locateArea[locateIndex], UnityEngine.Color.white);
  132. delay = maxDelay;
  133. capture = maxCapture;
  134. }
  135. else // 退出屏幕黑白控制
  136. {
  137. ScreenLocate.SetScreen(null);
  138. ScreenLocate.Main.ShowScreen(Screen.Quad);
  139. Reset();
  140. }
  141. }
  142. void Reset()
  143. {
  144. delay = 0;
  145. capture = 0;
  146. ScreenWhiteTexture = null;
  147. ScreenBlackTexture = null;
  148. locateIndex = -1;
  149. areaSelected = -1;
  150. locateArea.RemoveRange(4, LocateAreaData[0].Length);
  151. quadTemp.Clear();
  152. sumTemp.Clear();
  153. }
  154. public void CaptureBlack(Texture2D cam)
  155. {
  156. if (ScreenBlackTexture == null)
  157. ScreenBlackTexture = new Geometry.Vector<float>[Size.x * Size.y];
  158. var pixel = cam.GetPixels();
  159. Parallel.For(0, Size.x * Size.y, i =>
  160. {
  161. var ip = pixel[i];
  162. ScreenBlackTexture[i] += new Geometry.Vector<float>(ip.r / maxCapture, ip.g / maxCapture, ip.b / maxCapture);
  163. });
  164. }
  165. public void CaptureWhite(Texture2D cam)
  166. {
  167. if (ScreenWhiteTexture == null)
  168. ScreenWhiteTexture = new Geometry.Vector<float>[Size.x * Size.y];
  169. var pixel = cam.GetPixels();
  170. Parallel.For(0, Size.x * Size.y, i =>
  171. {
  172. var ip = pixel[i];
  173. ScreenWhiteTexture[i] += new Geometry.Vector<float>(ip.r / maxCapture, ip.g / maxCapture, ip.b / maxCapture);
  174. });
  175. }
  176. public void CaptureStay(Texture2D cam)
  177. {
  178. if (locateIndex == -1) // 屏幕黑色
  179. {
  180. CaptureBlack(cam);
  181. }
  182. else // 屏幕部分为白色
  183. {
  184. CaptureWhite(cam);
  185. }
  186. }
  187. public void CaptureEnd()
  188. {
  189. //Debug.Log("locateIndex: " + locateIndex + ", quad: " + quadTemp.Count);
  190. if (locateIndex == -1)
  191. return;
  192. if (locateIndex < 4)
  193. {
  194. sumTemp.Add(GetBrightness());
  195. ScreenWhiteTexture = null;
  196. // 选择亮度差最大的区域
  197. if (locateIndex == 3)
  198. {
  199. areaSelected = sumTemp.MaxIndex();
  200. locateArea.AddRange(LocateAreaData[areaSelected]);
  201. }
  202. }
  203. else if (locateIndex >= 4 && locateIndex < locateArea.Count - 1)
  204. {
  205. QuadrilateralFit(out _,out _);
  206. ScreenWhiteTexture = null;
  207. }
  208. else
  209. {
  210. QuadrilateralFit(out Texture2D LocateTex, out Texture2D DrawLineTex);
  211. ScreenLocate.DebugTexture(2, LocateTex);
  212. ScreenLocate.DebugTexture(3, DrawLineTex);
  213. if (quadTemp.Count != LocateAreaData[0].Length)
  214. {
  215. Debug.Log($"拟合四边形失败, quadTemp.Count: {quadTemp.Count}");
  216. }
  217. else if (quadTemp.Count == 1)
  218. {
  219. Screen.Quad = quadTemp[0];
  220. }
  221. else
  222. {
  223. // 线性拟合
  224. var xValue = new List<float>() { 0 };
  225. var predicts = new List<Vector>();
  226. foreach (var i in LocateAreaData[0])
  227. xValue.Add(i.size.x);
  228. Vector baseVertex = Vector.Zero; // x==0 时的点
  229. {
  230. foreach (var q in quadTemp)
  231. {
  232. baseVertex += q[areaSelected];
  233. }
  234. baseVertex /= quadTemp.Count;
  235. }
  236. double rs = 0.0;
  237. for (int i = 0; i < 4; i++)
  238. {
  239. if (i == areaSelected)
  240. {
  241. predicts.Add(baseVertex);
  242. }
  243. else
  244. {
  245. var yValue = new List<Vector>() { baseVertex };
  246. foreach (var q in quadTemp)
  247. {
  248. yValue.Add(q[i]);
  249. }
  250. var lr = LinerRegression1D.Fit(2, xValue.ToArray(), yValue.ToArray());
  251. rs += lr.RSquared / 3;
  252. predicts.Add(lr.Predict<Vector>(1));
  253. }
  254. }
  255. Screen.Quad = new OrdinalQuadrilateral(predicts);
  256. Debug.Log($"[InfraredIdentification2拟合结果] RSquared: {rs}, Quad: {Screen.Quad}");
  257. if (rs < 0.8) Screen.Quad = null;
  258. }
  259. }
  260. }
  261. public bool Update(Texture2D cam)
  262. {
  263. if (delay != 0)
  264. {
  265. delay--;
  266. return true;
  267. }
  268. if (capture != 0)
  269. {
  270. CaptureStay(cam);
  271. capture--;
  272. if (capture == 0)
  273. {
  274. CaptureEnd();
  275. NextScreen();
  276. }
  277. return true;
  278. }
  279. return false;
  280. #region Old
  281. /*
  282. if (delay != 0)
  283. {
  284. delay--;
  285. return true;
  286. }
  287. if (capture != 0)
  288. {
  289. capture--;
  290. if (ScreenBlackTexture == null)
  291. ScreenBlackTexture = new Geometry.Vector<float>[Size.x * Size.y];
  292. var pixel = cam.GetPixels();
  293. Parallel.For(0, Size.x * Size.y, i =>
  294. {
  295. var ip = pixel[i];
  296. ScreenBlackTexture[i] += new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  297. });
  298. if (capture == 0)
  299. ScreenLocate.SetScreen(UnityEngine.Color.black);
  300. return true;
  301. }
  302. if (delay != 0)
  303. {
  304. delay--;
  305. return true;
  306. }
  307. if (capture != 0)
  308. {
  309. capture--;
  310. if (ScreenWhiteTexture == null)
  311. ScreenWhiteTexture = new Geometry.Vector<float>[Size.x * Size.y];
  312. var pixel = cam.GetPixels();
  313. Parallel.For(0, Size.x * Size.y, i =>
  314. {
  315. var ip = pixel[i];
  316. ScreenWhiteTexture[i] += new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  317. });
  318. if (capture == 0)
  319. ScreenLocate.SetScreen(UnityEngine.Color.black);
  320. return true;
  321. }
  322. if (delay != 0)
  323. {
  324. delay--;
  325. return true;
  326. }
  327. if (capture != 0)
  328. {
  329. capture--;
  330. var pixel = cam.GetPixels();
  331. Parallel.For(0, Size.x * Size.y, i =>
  332. {
  333. var ip = pixel[i];
  334. ScreenWhiteTexture[i] -= new Geometry.Vector<float>(ip.r, ip.g, ip.b);
  335. });
  336. if (capture == 0)
  337. {
  338. ScreenLocate.SetScreen(null);
  339. UnityEngine.Color[] newPixel = new UnityEngine.Color[Size.x * Size.y];
  340. Parallel.For(0, Size.x * Size.y, i => {
  341. var pi = ScreenWhiteTexture[i] /= capture;
  342. newPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  343. });
  344. //读取数据
  345. //{
  346. // var fileName = "3.bin";
  347. // ScreenLocateTexture = $"2023 04 16 厦门测试数据/{fileName}".FileReadByte<Vector<float>[]>();
  348. // Debug.Log($"Read {fileName}");
  349. // Parallel.For(0, Size.x * Size.y, i =>
  350. // {
  351. // var pi = ScreenLocateTexture[i];
  352. // newPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  353. // });
  354. //}
  355. var ScreenLocateTex = new Texture2D(Size.x, Size.y);
  356. ScreenLocateTex.SetPixels(newPixel);
  357. ScreenLocateTex.Apply();
  358. //ScreenLocate.DebugTexture(2, ScreenLocateTex);
  359. var ScreenLocateTexLighted = ScreenLocateTex.AutoLight(10);
  360. //ScreenLocate.DebugTexture(2, ScreenLocateTexLighted);
  361. //var FileSavePath = Application.persistentDataPath + "/ScreenLocateTexture.bin";
  362. bool Save = ScreenLocate.Main.SaveToggle.isOn;
  363. string time;
  364. if (Save)
  365. {
  366. time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  367. var FileSavePath = $"屏幕定位数据{time}.bin";
  368. FileSavePath.FileWriteByte(ScreenWhiteTexture);
  369. var bytes = ScreenLocateTexLighted.EncodeToPNG();
  370. File.WriteAllBytes($"屏幕定位数据{time}.png", bytes);
  371. Debug.Log("ScreenLocateTexture Saved To: " + FileSavePath);
  372. }
  373. var ScreenLocateTexR = ScreenLocateTexLighted.ToRGB(ColorChannel.Red);
  374. var ScreenLocateTexG = ScreenLocateTexLighted.ToRGB(ColorChannel.Green);
  375. var ScreenLocateTexB = ScreenLocateTexLighted.ToRGB(ColorChannel.Blue);
  376. ScreenLocate.DebugTexture(2, ScreenLocateTexR);
  377. //ScreenLocate.DebugTexture(4, ScreenLocateTexG);
  378. //ScreenLocate.DebugTexture(5, ScreenLocateTexB);
  379. var watch = new System.Diagnostics.Stopwatch();
  380. watch.Start();
  381. var times = new List<double>() { 0.0 };
  382. var ScreenLocateTexLightedMat = ScreenLocateTexLighted.Too0Mat();
  383. //var ScreenLocateTexLightedMat = texture.Too0Mat();
  384. //var (edge, edgeDir) = ScreenLocateTexLightedMat.IdentifyEdge();
  385. var (edge, edgeDir) = ScreenLocateTexLightedMat.zimIdentifyEdgeGradientAny(15);
  386. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradient().ToTex());
  387. //ScreenLocate.DebugTexture(4, edge.ToTex());
  388. var quadLines = ScreenLocateTexLightedMat.IdentifyQuadLSD(edge, edgeDir, out List<Line> lightLines, 30);
  389. var drawLineMap = new MatrixF2D(edge..Size.x, edge.Size.y);
  390. int lineCount = 0;
  391. foreach (var l in quadLines)
  392. {
  393. if (l != null)
  394. {
  395. drawLineMap.DrawLine(l, (x, y) => 1, new Geometry2D.Float.Vector(0, 10));
  396. lineCount++;
  397. }
  398. }
  399. if (lineCount == 4)
  400. {
  401. var a = quadLines[0].Intersect(quadLines[3], false).Value;
  402. var b = quadLines[0].Intersect(quadLines[1], false).Value;
  403. var c = quadLines[2].Intersect(quadLines[3], false).Value;
  404. var d = quadLines[1].Intersect(quadLines[2], false).Value;
  405. Quad = new Quadrilateral(a, b, c, d);
  406. if (!Quad.IsInScreen(ScreenLocate.Main.WebCamera.Size))
  407. Quad = null;
  408. }
  409. ScreenLocate.Main.ShowScreen(Quad);
  410. //var lines = edge.IdentifyLineLSD(edgeDir, 100);
  411. ////var lines = ScreenLocateTexLightedMat.IdentifyLineLSD();
  412. //var drawLineMap = new MatrixF2D(edge..Size.x, edge.Size.y);
  413. //var returnMaxLines = lines.Sub(0, 10);
  414. //foreach (var (line, sum, gradient) in returnMaxLines)
  415. // drawLineMap.DrawLine(line, (x, y) => 1, new Geometry2D.Float.Vector(0, 10));
  416. ScreenLocate.DebugTexture(3, drawLineMap.ToTex());
  417. //{
  418. // var bytes = drawLineMap.ToTex().EncodeToPNG();
  419. // File.WriteAllBytes($"屏幕定位数据DrawLineMap.png", bytes);
  420. //}
  421. times.Add(watch.ElapsedMilliseconds);
  422. UnityEngine.Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  423. //ScreenLocate.DebugTexture(5, edge.IdentifyLine(edgeDir).ToTex());
  424. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientX().ToTex());
  425. //ScreenLocate.DebugTexture(5, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientY().ToTex());
  426. //var convolutionLighted2 = ScreenLocateTexLighted.Too0Mat().IdentifyEdgeVariance().ToTex();
  427. // opecncv处理
  428. // zim
  429. {
  430. //var cvLines = edge.cvHoughLinesP();
  431. //ScreenLocate.DebugTexture(5, cvLines);
  432. //var myLines = Hough.Transform(edgeMat);
  433. //var cvLines = edge.cvLine(myLines);
  434. //ScreenLocate.DebugTexture(5, cvLines);
  435. }
  436. UnityEngine.Object.Destroy(ScreenLocateTex);
  437. //ScreenLocate.DebugTexture(4, convolutionLighted2);
  438. }
  439. return true;
  440. }
  441. /*
  442. var avg = new Geometry4D.Vector<float>();
  443. var pixel = texture.GetPixels();
  444. foreach(var i in pixel.Index())
  445. {
  446. var iP = pixel[i];
  447. avg += new Geometry4D.Vector<float>(iP.r, iP.g, iP.b, iP.a);
  448. }
  449. avg /= pixel.Count();
  450. /*
  451. var (texLightedR, texLightedG, texLightedB) = ToRGB(newTex);
  452. ScreenLocate.DebugTexture(3, texLightedR);
  453. ScreenLocate.DebugTexture(4, texLightedG);
  454. ScreenLocate.DebugTexture(5, texLightedB);
  455. //Debug.Log(avg);
  456. return false;
  457. /**/
  458. #endregion
  459. }
  460. float GetBrightness()
  461. {
  462. UnityEngine.Color[] differPixel = new UnityEngine.Color[Size.x * Size.y];
  463. Parallel.For(0, Size.x * Size.y, i => {
  464. var pi = ScreenWhiteTexture[i] - ScreenBlackTexture[i];
  465. differPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  466. });
  467. var sum = 0f;
  468. foreach (var i in differPixel)
  469. {
  470. sum += i.Brightness();
  471. }
  472. sum /= differPixel.Length;
  473. //Debug.Log(sum);
  474. return sum;
  475. }
  476. void QuadrilateralFit(out Texture2D LocateTex, out Texture2D DrawLineTex, Texture2D debugImage = null)
  477. {
  478. OrdinalQuadrilateral quad = null;
  479. UnityEngine.Color[] differPixel = new UnityEngine.Color[Size.x * Size.y];
  480. //读取数据
  481. if (debugImage != null)
  482. {
  483. Debug.Log($"Debug {debugImage.name}");
  484. differPixel = debugImage.GetPixels();
  485. }
  486. else // 获得屏幕差值
  487. {
  488. Parallel.For(0, Size.x * Size.y, i => {
  489. var pi = ScreenWhiteTexture[i] - ScreenBlackTexture[i];
  490. differPixel[i] = new UnityEngine.Color(pi.x, pi.y, pi.z);
  491. });
  492. }
  493. var ScreenLocateTex = new Texture2D(Size.x, Size.y);
  494. ScreenLocateTex.SetPixels(differPixel);
  495. ScreenLocateTex.Apply();
  496. //ScreenLocate.DebugTexture(2, ScreenLocateTex);
  497. var ScreenLocateTexLighted = ScreenLocateTex.AutoLight(10);
  498. //ScreenLocate.DebugTexture(2, ScreenLocateTexLighted);
  499. var ScreenLocateTexR = ScreenLocateTexLighted.ToRGB(ColorChannel.Red);
  500. var ScreenLocateTexG = ScreenLocateTexLighted.ToRGB(ColorChannel.Green);
  501. var ScreenLocateTexB = ScreenLocateTexLighted.ToRGB(ColorChannel.Blue);
  502. LocateTex = ScreenLocateTexR;
  503. //ScreenLocate.DebugTexture(2, ScreenLocateTexR);
  504. //ScreenLocate.DebugTexture(4, ScreenLocateTexG);
  505. //ScreenLocate.DebugTexture(5, ScreenLocateTexB);
  506. //var watch = new System.Diagnostics.Stopwatch();
  507. //watch.Start();
  508. //var times = new List<double>() { 0.0 };
  509. var ScreenLocateTexLightedMat = ScreenLocateTexLighted.Too0Mat();
  510. //var ScreenLocateTexLightedMat = texture.Too0Mat();
  511. //var (edge, edgeDir) = ScreenLocateTexLightedMat.IdentifyEdge();
  512. int conSize = 15;
  513. var (edge, edgeDir) = ScreenLocateTexLightedMat.zimIdentifyEdgeGradientAny(conSize);
  514. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradient().ToTex());
  515. //ScreenLocate.DebugTexture(4, edge.ToTex());
  516. var minLength = locateIndex == -1 ? 50 : 50 * areaPercent;
  517. var quadLines = ScreenLocateTexLightedMat.ZIMIdentifyQuadLSD(edge, edgeDir, out List<Line> lightLines, conSize, minLength);
  518. var drawLineMap = new Matrix(edge.Size, Tiling: true);
  519. int lineCount = 0;
  520. foreach (var l in quadLines)
  521. {
  522. if (l != null)
  523. {
  524. drawLineMap.DrawLine(l, (x, y) => 1, new Geometry2D.Float.Vector(0, 10));
  525. lineCount++;
  526. }
  527. }
  528. //foreach (var l in lightLines)
  529. //{
  530. // if (l != null)
  531. // {
  532. // if (quadLines.Contains(l))
  533. // {
  534. // drawLineMap.DrawLine(l, (x, y) => 1, new Geometry2D.Float.Vector(0, 10));
  535. // lineCount++;
  536. // }
  537. // else
  538. // {
  539. // drawLineMap.DrawLine(l, (x, y) => 1, new Geometry2D.Float.Vector(0, 2));
  540. // }
  541. // }
  542. //}
  543. if (lineCount == 4)
  544. {
  545. var a = quadLines[0].Intersect(quadLines[3], false).Value;
  546. var b = quadLines[0].Intersect(quadLines[1], false).Value;
  547. var c = quadLines[2].Intersect(quadLines[3], false).Value;
  548. var d = quadLines[1].Intersect(quadLines[2], false).Value;
  549. quad = new OrdinalQuadrilateral(a, b, c, d);
  550. if (!quad.IsInScreen(ScreenLocate.Main.mUVCCameraInfo.Size))
  551. quad = null;
  552. }
  553. //if (quad != null && debugImage == null)
  554. if (quad != null)
  555. quadTemp.Add(quad);
  556. //var lines = edge.IdentifyLineLSD(edgeDir, 100);
  557. ////var lines = ScreenLocateTexLightedMat.IdentifyLineLSD();
  558. //var drawLineMap = new MatrixF2D(edge..Size.x, edge.Size.y);
  559. //var returnMaxLines = lines.Sub(0, 10);
  560. //foreach (var (line, sum, gradient) in returnMaxLines)
  561. // drawLineMap.DrawLine(line, (x, y) => 1, new Geometry2D.Float.Vector(0, 10));
  562. DrawLineTex = drawLineMap.ToTex();
  563. //ScreenLocate.DebugTexture(3, drawLineMap.ToTex());
  564. //var FileSavePath = Application.persistentDataPath + "/ScreenLocateTexture.bin";
  565. bool Save = ScreenLocate.Main.SaveToggle.isOn;
  566. string time;
  567. if (Save)
  568. {
  569. time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  570. var FileSavePath = $"{time}屏幕定位数据.bin";
  571. FileSavePath.FileWriteByte(ScreenWhiteTexture);
  572. var bytes = ScreenLocateTexLighted.EncodeToPNG();
  573. File.WriteAllBytes($"{time}屏幕.png", bytes);
  574. bytes = DrawLineTex.EncodeToPNG();
  575. File.WriteAllBytes($"{time}屏幕边框识别.png", bytes);
  576. Debug.Log("ScreenLocateTexture Saved To: " + FileSavePath);
  577. }
  578. //times.Add(watch.ElapsedMilliseconds);
  579. //UnityEngine.Debug.Log("time: " + (times[times.Count - 1] - times[times.Count - 2]));
  580. //ScreenLocate.DebugTexture(5, edge.IdentifyLine(edgeDir).ToTex());
  581. //ScreenLocate.DebugTexture(4, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientX().ToTex());
  582. //ScreenLocate.DebugTexture(5, ScreenLocateTexLighted.Too0Mat().IdentifyEdgeGradientY().ToTex());
  583. //var convolutionLighted2 = ScreenLocateTexLighted.Too0Mat().IdentifyEdgeVariance().ToTex();
  584. // opecncv处理
  585. // zim
  586. {
  587. //var cvLines = edge.cvHoughLinesP();
  588. //ScreenLocate.DebugTexture(5, cvLines);
  589. //var myLines = Hough.Transform(edgeMat);
  590. //var cvLines = edge.cvLine(myLines);
  591. //ScreenLocate.DebugTexture(5, cvLines);
  592. }
  593. UnityEngine.Object.Destroy(ScreenLocateTex);
  594. }
  595. }
  596. }