ScreenIdentification.cs 30 KB

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