Tools.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Runtime.InteropServices;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using PaintDotNet.Camera.TUC;
  10. using OpenCvSharp;
  11. namespace PaintDotNet.Camera
  12. {
  13. /// <summary>
  14. /// Bitmap转化
  15. /// </summary>
  16. public static class Tools
  17. {
  18. static Bitmap currBitmap;
  19. public static Bitmap ToBitmap(this byte[] rawValues, int width, int height, PixelFormat pixelFormat)
  20. {
  21. //// 申请目标位图的变量,并将其内存区域锁定
  22. try
  23. {
  24. if (currBitmap == null || width != currBitmap.Width || height != currBitmap.Height || pixelFormat != currBitmap.PixelFormat)
  25. {
  26. currBitmap = new Bitmap(width, height, pixelFormat);
  27. }
  28. var rect = new Rectangle(0, 0, width, height);
  29. var bitmapData = currBitmap.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat);
  30. IntPtr iptr = bitmapData.Scan0; // 获取bmpData的内存起始位置
  31. int size = width * height;
  32. if (pixelFormat == PixelFormat.Format24bppRgb)
  33. size *= 3;
  34. Marshal.Copy(rawValues, 0, iptr, size);
  35. currBitmap.UnlockBits(bitmapData);
  36. return currBitmap;
  37. }
  38. catch
  39. {
  40. return null;
  41. }
  42. }
  43. public static byte[] ToByteArray(this Bitmap bitmap)
  44. {
  45. BitmapData bmpdata = null;
  46. try
  47. {
  48. bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  49. int numbytes = bmpdata.Stride * bitmap.Height;
  50. byte[] bytedata = new byte[numbytes];
  51. IntPtr ptr = bmpdata.Scan0;
  52. Marshal.Copy(ptr, bytedata, 0, numbytes);
  53. return bytedata;
  54. }
  55. finally
  56. {
  57. if (bmpdata != null)
  58. bitmap.UnlockBits(bmpdata);
  59. }
  60. }
  61. public static Bitmap ToBitmap(this TUCAM_FRAME frame)
  62. {
  63. var width = (int)(frame.usWidth);
  64. var height = (int)(frame.usHeight);
  65. int nSize = (int)(frame.uiImgSize + frame.usHeader);
  66. var buff = new byte[nSize];
  67. Marshal.Copy(frame.pBuffer, buff, 0, nSize);
  68. Buffer.BlockCopy(buff, (int)(frame.usHeader), buff, 0, (int)(frame.uiImgSize));
  69. Bitmap bitmap;
  70. if (frame.ucChannels == 1)
  71. {
  72. bitmap = buff.ToBitmap(width, height, PixelFormat.Format8bppIndexed);
  73. if (bitmap == null)
  74. {
  75. return null;
  76. }
  77. // 定义灰度调色板
  78. System.Drawing.Imaging.ColorPalette GreyColorPalette = bitmap.Palette;
  79. for (int Index = 0; Index <= byte.MaxValue; Index++)
  80. {
  81. GreyColorPalette.Entries[Index] = Color.FromArgb(byte.MaxValue, Index, Index, Index);
  82. }
  83. bitmap.Palette = GreyColorPalette;
  84. //bitmap.Palette.Flags = 4;
  85. }
  86. else
  87. {
  88. bitmap = buff.ToBitmap(width, height, PixelFormat.Format24bppRgb); ;
  89. }
  90. return bitmap;
  91. }
  92. public static Bitmap CreatBitmap(this TUCAM_FRAME frame)
  93. {
  94. var width = (int)(frame.usWidth);
  95. var height = (int)(frame.usHeight);
  96. int nSize = (int)(frame.uiImgSize + frame.usHeader);
  97. var buff = new byte[nSize];
  98. Marshal.Copy(frame.pBuffer, buff, 0, nSize);
  99. Buffer.BlockCopy(buff, (int)(frame.usHeader), buff, 0, (int)(frame.uiImgSize));
  100. Bitmap bitmap;
  101. PixelFormat pixelFormat;
  102. if (frame.ucChannels == 1)
  103. {
  104. pixelFormat = PixelFormat.Format8bppIndexed;
  105. }
  106. else
  107. {
  108. pixelFormat = PixelFormat.Format24bppRgb;
  109. }
  110. bitmap = new Bitmap(width, height, pixelFormat);
  111. var rect = new Rectangle(0, 0, width, height);
  112. var bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, pixelFormat);
  113. IntPtr iptr = bitmapData.Scan0; // 获取bmpData的内存起始位置
  114. int size = width * height;
  115. if (pixelFormat == PixelFormat.Format24bppRgb)
  116. size *= 3;
  117. Marshal.Copy(buff, 0, iptr, size);
  118. bitmap.UnlockBits(bitmapData);
  119. if (frame.ucChannels == 1)
  120. {
  121. // 定义灰度调色板
  122. System.Drawing.Imaging.ColorPalette GreyColorPalette = bitmap.Palette;
  123. for (int Index = 0; Index <= byte.MaxValue; Index++)
  124. {
  125. GreyColorPalette.Entries[Index] = Color.FromArgb(byte.MaxValue, Index, Index, Index);
  126. }
  127. bitmap.Palette = GreyColorPalette;
  128. }
  129. return bitmap;
  130. }
  131. #region ToMat
  132. /// <summary>
  133. /// Converts System.Drawing.Bitmap to Mat
  134. /// </summary>
  135. /// <param name="src">System.Drawing.Bitmap object to be converted</param>
  136. /// <returns>A Mat object which is converted from System.Drawing.Bitmap</returns>
  137. public static Mat ToMat(this Bitmap src)
  138. {
  139. if (src == null)
  140. throw new ArgumentNullException(nameof(src));
  141. int w = src.Width;
  142. int h = src.Height;
  143. int channels;
  144. switch (src.PixelFormat)
  145. {
  146. case PixelFormat.Format24bppRgb:
  147. case PixelFormat.Format32bppRgb:
  148. channels = 3; break;
  149. case PixelFormat.Format32bppArgb:
  150. case PixelFormat.Format32bppPArgb:
  151. channels = 4; break;
  152. case PixelFormat.Format8bppIndexed:
  153. case PixelFormat.Format1bppIndexed:
  154. channels = 1; break;
  155. default:
  156. throw new NotImplementedException();
  157. }
  158. Mat dst = new Mat(h, w, MatType.CV_8UC(channels));
  159. //return OpenCvSharp.Extensions.BitmapConverter.ToMat(src);
  160. ToMat(src, dst);
  161. return dst;
  162. }
  163. /// <summary>
  164. /// Converts System.Drawing.Bitmap to Mat
  165. /// </summary>
  166. /// <param name="src">System.Drawing.Bitmap object to be converted</param>
  167. /// <param name="dst">A Mat object which is converted from System.Drawing.Bitmap</param>
  168. public static unsafe void ToMat(this Bitmap src, Mat dst)
  169. {
  170. if (src == null)
  171. throw new ArgumentNullException(nameof(src));
  172. if (dst == null)
  173. throw new ArgumentNullException(nameof(dst));
  174. if (dst.IsDisposed)
  175. throw new ArgumentException("The specified dst is disposed.", nameof(dst));
  176. if (dst.Depth() != MatType.CV_8U)
  177. throw new NotSupportedException("Mat depth != CV_8U");
  178. if (dst.Dims != 2)
  179. throw new NotSupportedException("Mat dims != 2");
  180. if (src.Width != dst.Width || src.Height != dst.Height)
  181. throw new ArgumentException("src.Size != dst.Size");
  182. int w = src.Width;
  183. int h = src.Height;
  184. Rectangle rect = new Rectangle(0, 0, w, h);
  185. BitmapData bd = null;
  186. try
  187. {
  188. bd = src.LockBits(rect, ImageLockMode.ReadOnly, src.PixelFormat);
  189. switch (src.PixelFormat)
  190. {
  191. case PixelFormat.Format1bppIndexed:
  192. Format1bppIndexed();
  193. break;
  194. case PixelFormat.Format8bppIndexed:
  195. Format8bppIndexed();
  196. break;
  197. case PixelFormat.Format24bppRgb:
  198. Format24bppRgb();
  199. break;
  200. case PixelFormat.Format32bppRgb:
  201. case PixelFormat.Format32bppArgb:
  202. case PixelFormat.Format32bppPArgb:
  203. Format32bppRgb();
  204. break;
  205. }
  206. }
  207. finally
  208. {
  209. if (bd != null)
  210. src.UnlockBits(bd);
  211. }
  212. // ReSharper disable once InconsistentNaming
  213. void Format1bppIndexed()
  214. {
  215. if (dst.Channels() != 1)
  216. throw new ArgumentException("Invalid nChannels");
  217. if (dst.IsSubmatrix())
  218. throw new NotImplementedException("submatrix not supported");
  219. if (bd == null)
  220. throw new NotSupportedException("BitmapData == null (Format1bppIndexed)");
  221. byte* srcPtr = (byte*)bd.Scan0.ToPointer();
  222. byte* dstPtr = dst.DataPointer;
  223. int srcStep = bd.Stride;
  224. uint dstStep = (uint)dst.Step();
  225. int x = 0;
  226. for (int y = 0; y < h; y++)
  227. {
  228. // 横は必ず4byte幅に切り上げられる。
  229. // この行の各バイトを調べていく
  230. for (int bytePos = 0; bytePos < srcStep; bytePos++)
  231. {
  232. if (x < w)
  233. {
  234. // 現在の位置のバイトからそれぞれのビット8つを取り出す
  235. byte b = srcPtr[bytePos];
  236. for (int i = 0; i < 8; i++)
  237. {
  238. if (x >= w)
  239. {
  240. break;
  241. }
  242. // IplImageは8bit/pixel
  243. dstPtr[dstStep * y + x] = ((b & 0x80) == 0x80) ? (byte)255 : (byte)0;
  244. b <<= 1;
  245. x++;
  246. }
  247. }
  248. }
  249. // 次の行へ
  250. x = 0;
  251. srcPtr += srcStep;
  252. }
  253. }
  254. void Ch1(Mat dst1, int height, int srcStep, uint dstStep, IntPtr srcData, byte[] palette)
  255. {
  256. if (dstStep == srcStep && !dst1.IsSubmatrix() && dst1.IsContinuous())
  257. {
  258. // Read Bitmap pixel data to managed array
  259. long length = dst1.DataEnd.ToInt64() - dst1.Data.ToInt64();
  260. if (length > int.MaxValue)
  261. throw new NotSupportedException("Too big dst Mat");
  262. var buffer = new byte[length];
  263. Marshal.Copy(srcData, buffer, 0, buffer.Length);
  264. // Apply conversion by palette
  265. buffer = buffer.Select(b => palette[b]).ToArray();
  266. // Write to dst Mat
  267. Marshal.Copy(buffer, 0, dst1.Data, buffer.Length);
  268. }
  269. else
  270. {
  271. // Copy line bytes from src to dst for each line
  272. byte* sp = (byte*)srcData;
  273. byte* dp = (byte*)dst1.Data;
  274. var buffer = new byte[srcStep];
  275. for (int y = 0; y < height; y++)
  276. {
  277. // Read Bitmap pixel data to managed array
  278. Marshal.Copy(new IntPtr(sp), buffer, 0, buffer.Length);
  279. // Apply conversion by palette
  280. buffer = buffer.Select(b => palette[b]).ToArray();
  281. // Write to dst Mat
  282. Marshal.Copy(buffer, 0, new IntPtr(dp), buffer.Length);
  283. sp += srcStep;
  284. dp += dstStep;
  285. }
  286. }
  287. }
  288. // ReSharper disable once InconsistentNaming
  289. void Format8bppIndexed()
  290. {
  291. int srcStep = bd.Stride;
  292. uint dstStep = (uint)dst.Step();
  293. int channels = dst.Channels();
  294. if (channels == 1)
  295. {
  296. var palette = new byte[256];
  297. var paletteLength = Math.Min(256, src.Palette.Entries.Length);
  298. for (int i = 0; i < paletteLength; i++)
  299. {
  300. // TODO src.Palette.Flags & 2 == 2
  301. // https://docs.microsoft.com/ja-jp/dotnet/api/system.drawing.imaging.colorpalette.flags?view=netframework-4.8
  302. palette[i] = src.Palette.Entries[i].R;
  303. }
  304. Ch1(dst, h, srcStep, dstStep, bd.Scan0, palette);
  305. }
  306. else if (channels == 3)
  307. {
  308. // Palette
  309. var paletteR = new byte[256];
  310. var paletteG = new byte[256];
  311. var paletteB = new byte[256];
  312. var paletteLength = Math.Min(256, src.Palette.Entries.Length);
  313. for (int i = 0; i < paletteLength; i++)
  314. {
  315. var c = src.Palette.Entries[i];
  316. paletteR[i] = c.R;
  317. paletteG[i] = c.G;
  318. paletteB[i] = c.B;
  319. }
  320. using (var dstR = new Mat(h, w, MatType.CV_8UC1))
  321. using (var dstG = new Mat(h, w, MatType.CV_8UC1))
  322. using (var dstB = new Mat(h, w, MatType.CV_8UC1))
  323. {
  324. Ch1(dstR, h, srcStep, (uint)dstR.Step(), bd.Scan0, paletteR);
  325. Ch1(dstG, h, srcStep, (uint)dstG.Step(), bd.Scan0, paletteG);
  326. Ch1(dstB, h, srcStep, (uint)dstB.Step(), bd.Scan0, paletteB);
  327. Cv2.Merge(new[] { dstB, dstG, dstR }, dst);
  328. }
  329. }
  330. else
  331. {
  332. throw new ArgumentException($"Invalid channels of dst Mat ({channels})");
  333. }
  334. }
  335. // ReSharper disable once InconsistentNaming
  336. void Format24bppRgb()
  337. {
  338. if (dst.Channels() != 3)
  339. throw new ArgumentException("Invalid nChannels");
  340. if (dst.Depth() != MatType.CV_8U && dst.Depth() != MatType.CV_8S)
  341. throw new ArgumentException("Invalid depth of dst Mat");
  342. int srcStep = bd.Stride;
  343. long dstStep = dst.Step();
  344. if (dstStep == srcStep && !dst.IsSubmatrix() && dst.IsContinuous())
  345. {
  346. IntPtr dstData = dst.Data;
  347. long bytesToCopy = dst.DataEnd.ToInt64() - dstData.ToInt64();
  348. Buffer.MemoryCopy(bd.Scan0.ToPointer(), dstData.ToPointer(), bytesToCopy, bytesToCopy);
  349. }
  350. else
  351. {
  352. // Copy line bytes from src to dst for each line
  353. byte* sp = (byte*)bd.Scan0;
  354. byte* dp = (byte*)dst.Data;
  355. for (int y = 0; y < h; y++)
  356. {
  357. Buffer.MemoryCopy(sp, dp, dstStep, dstStep);
  358. sp += srcStep;
  359. dp += dstStep;
  360. }
  361. }
  362. }
  363. // ReSharper disable once InconsistentNaming
  364. void Format32bppRgb()
  365. {
  366. int srcStep = bd.Stride;
  367. long dstStep = dst.Step();
  368. switch (dst.Channels())
  369. {
  370. case 4:
  371. if (!dst.IsSubmatrix() && dst.IsContinuous())
  372. {
  373. IntPtr dstData = dst.Data;
  374. long bytesToCopy = dst.DataEnd.ToInt64() - dstData.ToInt64();
  375. Buffer.MemoryCopy(bd.Scan0.ToPointer(), dstData.ToPointer(), bytesToCopy, bytesToCopy);
  376. }
  377. else
  378. {
  379. byte* sp = (byte*)bd.Scan0;
  380. byte* dp = (byte*)dst.Data;
  381. for (int y = 0; y < h; y++)
  382. {
  383. Buffer.MemoryCopy(sp, dp, dstStep, dstStep);
  384. sp += srcStep;
  385. dp += dstStep;
  386. }
  387. }
  388. break;
  389. case 3:
  390. byte* srcPtr = (byte*)bd.Scan0.ToPointer();
  391. byte* dstPtr = (byte*)dst.Data.ToPointer();
  392. for (int y = 0; y < h; y++)
  393. {
  394. for (int x = 0; x < w; x++)
  395. {
  396. dstPtr[y * dstStep + x * 3 + 0] = srcPtr[y * srcStep + x * 4 + 0];
  397. dstPtr[y * dstStep + x * 3 + 1] = srcPtr[y * srcStep + x * 4 + 1];
  398. dstPtr[y * dstStep + x * 3 + 2] = srcPtr[y * srcStep + x * 4 + 2];
  399. }
  400. }
  401. break;
  402. default:
  403. throw new ArgumentException("Invalid nChannels");
  404. }
  405. }
  406. }
  407. #endregion
  408. #region ToBitmap
  409. /*
  410. /// <summary>
  411. /// Converts Mat to System.Drawing.Bitmap
  412. /// </summary>
  413. /// <param name="src">Mat</param>
  414. /// <returns></returns>
  415. public static Bitmap ToBitmap(this Mat src)
  416. {
  417. if (src == null)
  418. {
  419. throw new ArgumentNullException(nameof(src));
  420. }
  421. PixelFormat pf;
  422. switch (src.Channels())
  423. {
  424. case 1:
  425. pf = PixelFormat.Format8bppIndexed; break;
  426. case 3:
  427. pf = PixelFormat.Format24bppRgb; break;
  428. case 4:
  429. pf = PixelFormat.Format32bppArgb; break;
  430. default:
  431. throw new ArgumentException("Number of channels must be 1, 3 or 4.", nameof(src));
  432. }
  433. return ToBitmap(src, pf);
  434. }
  435. /// <summary>
  436. /// Converts Mat to System.Drawing.Bitmap
  437. /// </summary>
  438. /// <param name="src">Mat</param>
  439. /// <param name="pf">Pixel Depth</param>
  440. /// <returns></returns>
  441. public static Bitmap ToBitmap(this Mat src, PixelFormat pf)
  442. {
  443. if (src == null)
  444. throw new ArgumentNullException(nameof(src));
  445. src.ThrowIfDisposed();
  446. Bitmap bitmap = new Bitmap(src.Width, src.Height, pf);
  447. ToBitmap(src, bitmap);
  448. return bitmap;
  449. }
  450. /// <summary>
  451. /// Converts Mat to System.Drawing.Bitmap
  452. /// </summary>
  453. /// <param name="src">Mat</param>
  454. /// <param name="dst">Mat</param>
  455. /// <remarks>Author: shimat, Gummo (ROI support)</remarks>
  456. public static unsafe void ToBitmap(this Mat src, Bitmap dst)
  457. {
  458. if (src == null)
  459. throw new ArgumentNullException(nameof(src));
  460. if (dst == null)
  461. throw new ArgumentNullException(nameof(dst));
  462. if (src.IsDisposed)
  463. throw new ArgumentException("The image is disposed.", nameof(src));
  464. if (src.Depth() != MatType.CV_8U)
  465. throw new ArgumentException("Depth of the image must be CV_8U");
  466. //if (src.IsSubmatrix())
  467. // throw new ArgumentException("Submatrix is not supported");
  468. if (src.Width != dst.Width || src.Height != dst.Height)
  469. throw new ArgumentException("");
  470. PixelFormat pf = dst.PixelFormat;
  471. // 1プレーン用の場合、グレースケールのパレット情報を生成する
  472. if (pf == PixelFormat.Format8bppIndexed)
  473. {
  474. ColorPalette plt = dst.Palette;
  475. for (int x = 0; x < 256; x++)
  476. {
  477. plt.Entries[x] = Color.FromArgb(x, x, x);
  478. }
  479. dst.Palette = plt;
  480. }
  481. int w = src.Width;
  482. int h = src.Height;
  483. Rectangle rect = new Rectangle(0, 0, w, h);
  484. BitmapData bd = null;
  485. bool submat = src.IsSubmatrix();
  486. bool continuous = src.IsContinuous();
  487. try
  488. {
  489. bd = dst.LockBits(rect, ImageLockMode.WriteOnly, pf);
  490. IntPtr srcData = src.Data;
  491. byte* pSrc = (byte*)(srcData.ToPointer());
  492. byte* pDst = (byte*)(bd.Scan0.ToPointer());
  493. int ch = src.Channels();
  494. int srcStep = (int)src.Step();
  495. int dstStep = ((src.Width * ch) + 3) / 4 * 4; // 4の倍数に揃える
  496. int stride = bd.Stride;
  497. switch (pf)
  498. {
  499. case PixelFormat.Format1bppIndexed:
  500. {
  501. if (submat)
  502. throw new NotImplementedException("submatrix not supported");
  503. // BitmapDataは4byte幅だが、IplImageは1byte幅
  504. // 手作業で移し替える
  505. //int offset = stride - (w / 8);
  506. int x = 0;
  507. byte b = 0;
  508. for (int y = 0; y < h; y++)
  509. {
  510. for (int bytePos = 0; bytePos < stride; bytePos++)
  511. {
  512. if (x < w)
  513. {
  514. for (int i = 0; i < 8; i++)
  515. {
  516. var mask = (byte)(0x80 >> i);
  517. if (x < w && pSrc[srcStep * y + x] == 0)
  518. b &= (byte)(mask ^ 0xff);
  519. else
  520. b |= mask;
  521. x++;
  522. }
  523. pDst[bytePos] = b;
  524. }
  525. }
  526. x = 0;
  527. pDst += stride;
  528. }
  529. break;
  530. }
  531. case PixelFormat.Format8bppIndexed:
  532. case PixelFormat.Format24bppRgb:
  533. case PixelFormat.Format32bppArgb:
  534. if (srcStep == dstStep && !submat && continuous)
  535. {
  536. long bytesToCopy = src.DataEnd.ToInt64() - src.Data.ToInt64();
  537. Buffer.MemoryCopy(pSrc, pDst, bytesToCopy, bytesToCopy);
  538. }
  539. else
  540. {
  541. for (int y = 0; y < h; y++)
  542. {
  543. long offsetSrc = (y * srcStep);
  544. long offsetDst = (y * dstStep);
  545. long bytesToCopy = w * ch;
  546. // 一列ごとにコピー
  547. Buffer.MemoryCopy(pSrc + offsetSrc, pDst + offsetDst, bytesToCopy, bytesToCopy);
  548. }
  549. }
  550. break;
  551. default:
  552. throw new NotImplementedException();
  553. }
  554. }
  555. finally
  556. {
  557. if (bd != null)
  558. dst.UnlockBits(bd);
  559. }
  560. }*/
  561. #endregion
  562. }
  563. }