ScreenIdentification.cs 27 KB

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