ScreenIdentification.cs 30 KB

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