ScreenIdentification.cs 29 KB

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