CImageHandler.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. using OTSDataType;
  2. using OTSModelSharp.ImageProcess;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using static OTSDataType.otsdataconst;
  10. namespace OTSModelSharp.ServiceInterface
  11. {
  12. using OpenCvSharp;
  13. using OTSCLRINTERFACE;
  14. using OTSIMGPROC;
  15. using OTSModelSharp.DTLBase;
  16. using System.Drawing.Imaging;
  17. using System.Runtime.InteropServices;
  18. using System.Windows;
  19. public class CImageHandler:IImageProcess
  20. {
  21. #region 通过byte数组生成BMP图像文件
  22. /// <summary>
  23. /// 将一个byte的数组转换为8bit灰度位图
  24. /// </summary>
  25. /// <param name="data">数组</param>
  26. /// <param name="width">图像宽度</param>
  27. /// <param name="height">图像高度</param>
  28. /// <returns>位图</returns>
  29. public static Bitmap ToGrayBitmap(byte[] data, int width, int height)
  30. {
  31. if (width == 0 || height == 0)
  32. return null;
  33. //// 申请目标位图的变量,并将其内存区域锁定
  34. Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
  35. //// BitmapData这部分内容 需要 using System.Drawing.Imaging;
  36. BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height),
  37. ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
  38. //// 获取图像参数
  39. // 扫描线的宽度
  40. int stride = bmpData.Stride;
  41. // 显示宽度与扫描线宽度的间隙
  42. int offset = stride - width;
  43. // 获取bmpData的内存起始位置
  44. IntPtr iptr = bmpData.Scan0;
  45. // 用stride宽度,表示这是内存区域的大小
  46. int scanBytes = stride * height;
  47. //// 下面把原始的显示大小字节数组转换为内存中实际存放的字节数组
  48. int posScan = 0;
  49. int posReal = 0;// 分别设置两个位置指针,指向源数组和目标数组
  50. byte[] pixelValues = new byte[scanBytes]; //为目标数组分配内存
  51. //for (int x = height-1;x>=0 ; x--) data[startIndex+ y];//
  52. for (int x = 0; x < height; x++)
  53. {
  54. int startIndex = x * width;
  55. //// 下面的循环节是模拟行扫描
  56. for (int y = 0; y < width; y++)
  57. {
  58. pixelValues[posScan++] = data[posReal++];
  59. }
  60. posScan += offset; //行扫描结束,要将目标位置指针移过那段“间隙”
  61. }
  62. //// 用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中
  63. System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
  64. bmp.UnlockBits(bmpData); // 解锁内存区域
  65. //// 下面的代码是为了修改生成位图的索引表,从伪彩修改为灰度
  66. ColorPalette tempPalette;
  67. using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
  68. {
  69. tempPalette = tempBmp.Palette;
  70. }
  71. for (int i = 0; i < 256; i++)
  72. {
  73. tempPalette.Entries[i] = Color.FromArgb(i, i, i);
  74. }
  75. bmp.Palette = tempPalette;
  76. return bmp;
  77. }
  78. #endregion
  79. public static byte[] BitmapToGrayByte(Bitmap bitmap)
  80. {
  81. // 申请目标位图的变量,并将其内存区域锁定
  82. BitmapData bitmapDat = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
  83. // 获取bmpData的内存起始位置
  84. IntPtr intPtr = bitmapDat.Scan0;
  85. byte[] image = new byte[bitmap.Width * bitmap.Height];//原始数据
  86. Marshal.Copy(intPtr, image, 0, bitmap.Width * bitmap.Height); // 将数据复制到byte数组中,
  87. //解锁内存区域
  88. bitmap.UnlockBits(bitmapDat);
  89. return image;
  90. }
  91. //获取测量的BSE图
  92. //COTSSample WSample: 工作样品测量
  93. //Byte[] BSEImage: 带背景图数据
  94. //int iHeight: 图像高度
  95. //int iWidth: 图像宽度
  96. //Byte[]BSEImageNoBG : 去背景图数据
  97. public bool GetBSEImage(COTSImageProcParam ImgProcPrm, double pixelSize, byte[] BSEImage, int iHeight, int iWidth, ref byte[] BSEImageNoBG)
  98. {
  99. Rectangle rect = new Rectangle();
  100. rect.Height = iHeight;
  101. rect.Width = iWidth;
  102. CBSEImgClr pBSEImageIn = new CBSEImgClr(rect);
  103. CBSEImgClr pBSEImageOut = new CBSEImgClr(rect);
  104. //pBSEImageIn.SetImageRect(rect);
  105. pBSEImageIn.SetImageData(BSEImage,iWidth, iHeight );
  106. //pBSEImageOut.SetImageRect(rect);
  107. if (null == ImgProcPrm)
  108. {
  109. return false;
  110. }
  111. RemoveBackGround(pBSEImageIn, ImgProcPrm, pixelSize ,ref pBSEImageOut);
  112. BSEImageNoBG = pBSEImageOut.GetImageDataPtr();
  113. return true;
  114. }
  115. /// <summary>
  116. /// 获取测量的BSE图
  117. /// </summary>
  118. /// <param name="BSEImage">BSE原数据</param>
  119. /// <param name="iHeight">图像高度</param>
  120. /// <param name="iWidth">图像宽度</param>
  121. /// <param name="grayStart"></param>
  122. /// <param name="grayEnd"></param>
  123. /// <param name="BSEImageNoBG">去背景图数据</param>
  124. /// <returns></returns>
  125. public bool GetBSEImage(byte[] BSEImage, int iHeight, int iWidth, int grayStart, int grayEnd, ref byte[] BSEImageNoBG)
  126. {
  127. Rectangle rect = new Rectangle();
  128. rect.Height = iHeight;
  129. rect.Width = iWidth;
  130. CBSEImgClr pBSEImageIn = new CBSEImgClr(rect);
  131. CBSEImgClr pBSEImageOut = new CBSEImgClr(rect);
  132. //pBSEImageIn.SetImageRect(rect);
  133. pBSEImageIn.SetImageData(BSEImage, iWidth, iHeight );
  134. CIntRangeClr cIntRangeClr = new CIntRangeClr();
  135. cIntRangeClr.SetStart(grayStart);
  136. cIntRangeClr.SetEnd(grayEnd);
  137. OTSCLRINTERFACE.ImageProForClr imgpro = new OTSCLRINTERFACE.ImageProForClr();
  138. int num=0;
  139. imgpro.GetSpecialGrayRangeImage(pBSEImageIn, cIntRangeClr, pBSEImageOut,ref num);
  140. for (int i = 0; i < iWidth; i++)
  141. {
  142. for (int j = 0; j < iHeight; j++)
  143. {
  144. var bse = pBSEImageOut.GetBSEValue(i, j);
  145. if (bse == 255)
  146. {
  147. var originalBse = pBSEImageIn.GetBSEValue(i, j);
  148. pBSEImageOut.SetBSEValue(i, j, originalBse);
  149. }
  150. else
  151. {
  152. pBSEImageOut.SetBSEValue(i, j, 255);
  153. }
  154. }
  155. }
  156. BSEImageNoBG = pBSEImageOut.GetImageDataPtr();
  157. return true;
  158. }
  159. // remove background
  160. public void RemoveBackGround(CBSEImgClr a_pImgIn, COTSImageProcParam a_pImgProcessParam, double a_pixelSize, ref CBSEImgClr a_pImgOut)
  161. {
  162. List<COTSParticleClr> parts = new List<COTSParticleClr>();
  163. List<COTSParticleClr> specialGreyparts = new List<COTSParticleClr>();
  164. if (!RemoveBGAndGetParts(a_pImgIn, a_pImgProcessParam, a_pixelSize, ref parts))
  165. {
  166. return;
  167. }
  168. if (a_pImgProcessParam.GetSpecialGreyRangeParam().GetIsToRun())
  169. {
  170. var param = a_pImgProcessParam.GetSpecialGreyRangeParam();
  171. var ranges = param.GetSpecialGreyRanges();
  172. foreach (var r in ranges)
  173. {
  174. CIntRangeClr r1 = new CIntRangeClr();
  175. r1.SetStart(r.range.GetStart());
  176. r1.SetEnd(r.range.GetEnd());
  177. CDoubleRangeClr r2 = new CDoubleRangeClr();
  178. r2.SetStart(r.diameterRange.GetStart());
  179. r2.SetEnd(r.diameterRange.GetEnd());
  180. GetParticlesBySpecialGray(a_pImgIn, r1, r2, a_pixelSize, ref specialGreyparts);
  181. }
  182. }
  183. for (int i = 0; i < a_pImgOut.GetWidth(); i++)
  184. {
  185. for (int j = 0; j < a_pImgOut.GetHeight(); j++)
  186. {
  187. a_pImgOut.SetBSEValue(i, j, 255);
  188. }
  189. }
  190. if (specialGreyparts.Count > 0)
  191. {
  192. foreach (var p in specialGreyparts)
  193. {
  194. foreach (var s in p.GetFeature().GetSegmentsList())
  195. {
  196. for (int i = s.GetStart(); i < s.GetStart() + s.GetLength(); i++)
  197. {
  198. var bseValue = a_pImgIn.GetBSEValue(i, s.GetHeight());
  199. a_pImgOut.SetBSEValue(i, s.GetHeight(), bseValue);
  200. }
  201. }
  202. }
  203. }
  204. foreach (var p in parts)
  205. {
  206. foreach (var s in p.GetFeature().GetSegmentsList())
  207. {
  208. for (int i = s.GetStart(); i < s.GetStart() + s.GetLength(); i++)
  209. {
  210. var bseValue = a_pImgIn.GetBSEValue(i, s.GetHeight());
  211. a_pImgOut.SetBSEValue(i, s.GetHeight(), bseValue);
  212. }
  213. }
  214. }
  215. return;
  216. }
  217. public void BDilate3(string source, string target, int wDegree, int rows, int columns)
  218. {
  219. throw new NotImplementedException();
  220. }
  221. public void BErode3(string source, string target, int wDegree, int rows, int columns)
  222. {
  223. throw new NotImplementedException();
  224. }
  225. public bool CalParticleImageProp( COTSParticleClr part, double a_pixelSize)
  226. {
  227. OTSCLRINTERFACE.ImageProForClr imgpro = new OTSCLRINTERFACE.ImageProForClr();
  228. imgpro.CalcuParticleImagePropertes(part,a_pixelSize);
  229. return true;
  230. }
  231. public bool RemoveBGAndGetParts(CBSEImgClr img, COTSImageProcParam a_pImgProcessParam,double a_pixelSize,ref List<COTSParticleClr> parts)
  232. {
  233. OTSCLRINTERFACE.ImageProForClr imgpro = new OTSCLRINTERFACE.ImageProForClr();
  234. OTSCLRINTERFACE.COTSImgProcPrmClr prm = GetImageProcPrmClr(a_pImgProcessParam);
  235. OTSCLRINTERFACE.COTSFieldDataClr flddataclr = new OTSCLRINTERFACE.COTSFieldDataClr();
  236. if (!imgpro.GetFieldDataFromImage(img, prm, a_pixelSize, flddataclr))
  237. {
  238. return false;
  239. }
  240. parts = flddataclr.GetParticleList();
  241. return true;
  242. }
  243. public bool GetParticlesBySpecialGray(CBSEImgClr img, CIntRangeClr grayrange, CDoubleRangeClr diameterRange,double a_pixelSize, ref List<COTSParticleClr> parts)
  244. {
  245. OTSCLRINTERFACE.ImageProForClr imgpro = new OTSCLRINTERFACE.ImageProForClr();
  246. //OTSCLRINTERFACE.COTSImgProcPrmClr prm = GetImageProcPrmClr(a_pImgProcessParam);
  247. OTSCLRINTERFACE.COTSFieldDataClr flddataclr = new OTSCLRINTERFACE.COTSFieldDataClr();
  248. imgpro.GetParticlesBySpecialPartGrayRange(img, grayrange,diameterRange,a_pixelSize, flddataclr);
  249. parts = flddataclr.GetParticleList();
  250. return true;
  251. }
  252. private COTSImgProcPrmClr GetImageProcPrmClr(COTSImageProcParam a_oSource)
  253. {
  254. COTSImgProcPrmClr prmclr = new COTSImgProcPrmClr();
  255. OTSCLRINTERFACE.CDoubleRangeClr r1 = new OTSCLRINTERFACE.CDoubleRangeClr(a_oSource.GetIncAreaRange().GetStart(), a_oSource.GetIncAreaRange().GetEnd());
  256. prmclr.SetIncArea(r1);
  257. OTSCLRINTERFACE.CIntRangeClr r2= new OTSCLRINTERFACE.CIntRangeClr(a_oSource.GetBGGray().GetStart(), a_oSource.GetBGGray().GetEnd());
  258. prmclr.SetBGGray(r2);
  259. OTSCLRINTERFACE.CIntRangeClr r3= new OTSCLRINTERFACE.CIntRangeClr(a_oSource.GetParticleGray().GetStart(), a_oSource.GetParticleGray().GetEnd());
  260. prmclr.SetParticleGray(r3);
  261. prmclr.SetBGRemoveType((int)a_oSource.GetBGRemoveType());
  262. prmclr.SetAutoBGRemoveType((int)a_oSource.GetAutoBGRemoveType());
  263. prmclr.SetErrodDilateParam(a_oSource.GetErrodDilateParam());
  264. prmclr.SetOverlapParam(a_oSource.GetOverlapParam());
  265. return prmclr;
  266. }
  267. public bool MergeBigBoundaryParticles(List<COTSFieldData> allFields, double pixelSize, int scanFieldSize, System.Drawing.Size ResolutionSize, ref List<COTSParticleClr> mergedParts)
  268. {
  269. List<COTSFieldDataClr> fldclrs = new List<COTSFieldDataClr>();
  270. foreach (var f in allFields)
  271. {
  272. COTSFieldDataClr fldclr = new COTSFieldDataClr();
  273. PointF p1 = f.GetOTSPosition();
  274. System.Drawing.Point p2 = new System.Drawing.Point((int)p1.X, (int)p1.Y);
  275. fldclr.SetPosition(p2);
  276. fldclr.SetImageWidth(f.Width);
  277. fldclr.SetImageHeight(f.Height);
  278. var parts = f.GetListAnalysisParticles();
  279. foreach (var p in parts)
  280. {
  281. fldclr.AddParticle(p);
  282. }
  283. fldclrs.Add(fldclr);
  284. }
  285. OTSCLRINTERFACE.ImageProForClr imgpro = new OTSCLRINTERFACE.ImageProForClr();
  286. imgpro.MergeBigBoundaryParticles(fldclrs, pixelSize, scanFieldSize, ResolutionSize, mergedParts);
  287. return true;
  288. }
  289. /// <summary>
  290. /// 根据Segment寻找边缘坐标点
  291. /// </summary>
  292. /// <param name="width"></param>
  293. /// <param name="height"></param>
  294. /// <param name="segmentClrs"></param>
  295. /// <returns></returns>
  296. public static List<System.Drawing.Point> FindContoursBySegment(int width, int height, List<COTSSegmentClr> segmentClrs)
  297. {
  298. List<System.Drawing.Point> points = new List<System.Drawing.Point>();
  299. using (Mat mat = new Mat(height, width, MatType.CV_8UC1, new Scalar(0)))
  300. {
  301. for (int i = 0; i < segmentClrs.Count; i++)
  302. {
  303. Cv2.Line(mat, new OpenCvSharp.Point(segmentClrs[i].GetStart(), segmentClrs[i].GetHeight()), new OpenCvSharp.Point(segmentClrs[i].GetStart() + segmentClrs[i].GetLength(), segmentClrs[i].GetHeight()), Scalar.White, 1, LineTypes.AntiAlias);
  304. }
  305. Point[][] contours;
  306. HierarchyIndex[] hierarchy;
  307. Cv2.FindContours(mat, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple, null);
  308. for (int i = 0; i < contours.ToList().Count(); i++)
  309. {
  310. for (int j = 0; j < contours[i].Count(); j++)
  311. {
  312. System.Drawing.Point point = new System.Drawing.Point(contours[i][j].X, contours[i][j].Y);
  313. if (!points.Contains(point))
  314. {
  315. points.Add(point);
  316. }
  317. }
  318. }
  319. }
  320. return points;
  321. }
  322. public bool RepeatedParticleTreatment(List<COTSFieldData> allFields, COTSSample theSample, string stdPath)
  323. {
  324. int maxPartCount = theSample.GetMsrParams().GetXRayParam().GetXrayLimit();
  325. int overlap = theSample.GetMsrParams().GetImageProcessParam().GetOverlapParam();
  326. double pixelSize = theSample.CalculatePixelSize();
  327. System.Drawing.Size resolutionSize = theSample.GetResolutionSize();
  328. int scanFieldSizeX = theSample.GetSEMDataMsr().GetScanFieldSize();
  329. int scanFieldSizeY = scanFieldSizeX * resolutionSize.Height / resolutionSize.Width;
  330. int offsetX = scanFieldSizeX - (int)(overlap * pixelSize);
  331. int offsetY = scanFieldSizeY - (int)(overlap * pixelSize);
  332. List<COTSParticleClr> deletePartList = new List<COTSParticleClr>();
  333. foreach (var item in allFields)
  334. {
  335. if (!item.GetIsMeasureComplete())
  336. {
  337. break;
  338. }
  339. //找到上下左右四帧图
  340. List<COTSFieldData> leftField = allFields.Where(a => a.OTSPos == new System.Drawing.PointF(item.OTSPos.X - offsetX, item.OTSPos.Y)).ToList();
  341. List<COTSFieldData> rightField = allFields.Where(a => a.OTSPos == new System.Drawing.PointF(item.OTSPos.X + offsetX, item.OTSPos.Y)).ToList();
  342. List<COTSFieldData> upField = allFields.Where(a => a.OTSPos == new System.Drawing.PointF(item.OTSPos.X, item.OTSPos.Y + offsetY)).ToList();
  343. List<COTSFieldData> downField = allFields.Where(a => a.OTSPos == new System.Drawing.PointF(item.OTSPos.X, item.OTSPos.Y - offsetY)).ToList();
  344. //判断是否有效
  345. if (leftField.Count() == 1)//包含左帧图
  346. {
  347. if (leftField[0].GetIsMeasureComplete() == true)//存在测量帧图
  348. {
  349. //寻找重叠颗粒
  350. deletePartList.AddRange(FieldFun(leftField[0], item, "left_right", resolutionSize, overlap));
  351. }
  352. }
  353. if (rightField.Count() == 1)//包含右帧图
  354. {
  355. if (rightField[0].GetIsMeasureComplete() == true)//存在测量帧图
  356. {
  357. //寻找重叠颗粒
  358. deletePartList.AddRange(FieldFun(item, rightField[0], "left_right", resolutionSize, overlap));
  359. }
  360. }
  361. if (upField.Count() == 1)//包含上帧图
  362. {
  363. if (upField[0].GetIsMeasureComplete() == true)//存在测量帧图
  364. {
  365. //寻找重叠颗粒
  366. deletePartList.AddRange(FieldFun(upField[0], item, "up_down", resolutionSize, overlap));
  367. }
  368. }
  369. if (downField.Count() == 1)//包含下帧图
  370. {
  371. if (downField[0].GetIsMeasureComplete() == true)//存在测量帧图
  372. {
  373. //寻找重叠颗粒
  374. deletePartList.AddRange(FieldFun(item, downField[0], "up_down", resolutionSize, overlap));
  375. }
  376. }
  377. }
  378. //数据库操作
  379. SQLiteHelper sQLiteHelper = new SQLiteHelper(stdPath);
  380. sQLiteHelper.GetDBConnection();
  381. sQLiteHelper.BeginTransaction();
  382. deletePartList = deletePartList.Distinct().ToList();//去重
  383. if (!sQLiteHelper.DeletePartForTransaction(deletePartList))
  384. {
  385. return false;
  386. }
  387. sQLiteHelper.CommitTransaction();
  388. return true;
  389. }
  390. private List<COTSParticleClr> FieldFun(COTSFieldData left_upField, COTSFieldData right_downField, string style, System.Drawing.Size resolutionSize, int overlap)
  391. {
  392. List<COTSParticleClr> particleClrs = new List<COTSParticleClr>();
  393. if (style == "left_right")
  394. {
  395. //寻找左帧图的右侧区域颗粒
  396. foreach (var leftParticles in left_upField.GetListAnalysisParticles())
  397. {
  398. Rectangle leftRectangle = (Rectangle)leftParticles.GetParticleRect();
  399. if (leftRectangle.Left > resolutionSize.Width - overlap)//未跨界
  400. {
  401. if (leftRectangle.Right == resolutionSize.Width)//颗粒右侧在边界处截断
  402. {
  403. }
  404. else
  405. {
  406. particleClrs.Add(leftParticles);
  407. }
  408. }
  409. }
  410. }
  411. else
  412. {
  413. //寻找上帧图的下侧区域颗粒
  414. foreach (var upParticles in left_upField.GetListAnalysisParticles())
  415. {
  416. Rectangle upRectangle = (Rectangle)upParticles.GetParticleRect();
  417. if (upRectangle.Top > resolutionSize.Height - overlap / 2)//未跨界
  418. {
  419. if (upRectangle.Bottom == resolutionSize.Height)//颗粒下方在边界处截断
  420. {
  421. }
  422. else
  423. {
  424. particleClrs.Add(upParticles);
  425. }
  426. }
  427. }
  428. }
  429. return particleClrs;
  430. }
  431. public Mat CombinImageX(Mat[] list_mats, int OverlapParam, int type)
  432. {
  433. List<Mat> matStitch = new List<Mat>();//拼接
  434. List<Mat> matCombin = new List<Mat>();//合并
  435. for (int i = 0; i < list_mats.Count(); i++)
  436. {
  437. if (i == 0)//首张
  438. {
  439. matCombin.Add(new Mat(list_mats[i], new Rect(0, 0, list_mats[i].Width - OverlapParam - 100, list_mats[i].Height)));
  440. matStitch.Add(new Mat(list_mats[i], new Rect(list_mats[i].Width - OverlapParam - 100, 0, OverlapParam + 100, list_mats[i].Height)));
  441. }
  442. else if(i == list_mats.Count() - 1)//末张
  443. {
  444. matStitch.Add(new Mat(list_mats[i], new Rect(0, 0, OverlapParam + 100, list_mats[i].Height)));
  445. matCombin.Add(new Mat(list_mats[i], new Rect(OverlapParam + 100, 0, list_mats[i].Width - OverlapParam - 100, list_mats[i].Height)));
  446. }
  447. else
  448. {
  449. matStitch.Add(new Mat(list_mats[i], new Rect(0, 0, OverlapParam + 100, list_mats[i].Height)));
  450. matCombin.Add(new Mat(list_mats[i], new Rect(OverlapParam + 100, 0, list_mats[i].Width - (OverlapParam + 100) * 2, list_mats[i].Height)));
  451. matStitch.Add(new Mat(list_mats[i], new Rect(list_mats[i].Width - OverlapParam - 100, 0, OverlapParam + 100, list_mats[i].Height)));
  452. }
  453. }
  454. for (int i = 0; i < matStitch.Count; i += 2)
  455. {
  456. if (matStitch.Count == 1)
  457. {
  458. matCombin.Insert(i + 1, matStitch[i]);
  459. }
  460. else
  461. {
  462. matCombin.Insert(i + 1, StitchImageX((int)(OverlapParam / 2 * 1.2), type, matStitch[i], matStitch[i + 1]));
  463. }
  464. }
  465. Mat pano = new OpenCvSharp.Mat();
  466. Cv2.HConcat(matCombin.ToArray(), pano);
  467. return pano;
  468. }
  469. public Mat CombinImageY(Mat[] list_mats, int OverlapParam, int type)
  470. {
  471. List<Mat> matStitch = new List<Mat>();//拼接
  472. List<Mat> matCombin = new List<Mat>();//合并
  473. for (int i = 0; i < list_mats.Count(); i++)
  474. {
  475. if (i == 0)//首张
  476. {
  477. matCombin.Add(new Mat(list_mats[i], new Rect(0, 0, list_mats[i].Width, list_mats[i].Height - OverlapParam - 100)));
  478. matStitch.Add(new Mat(list_mats[i], new Rect(0, list_mats[i].Height - OverlapParam - 100, list_mats[i].Width, OverlapParam + 100)));
  479. }
  480. else if (i == list_mats.Count() - 1)//末张
  481. {
  482. matStitch.Add(new Mat(list_mats[i], new Rect(0, 0, list_mats[i].Width, OverlapParam + 100)));
  483. matCombin.Add(new Mat(list_mats[i], new Rect(0, OverlapParam + 100, list_mats[i].Width, list_mats[i].Height - OverlapParam - 100)));
  484. }
  485. else
  486. {
  487. matStitch.Add(new Mat(list_mats[i], new Rect(0, 0, list_mats[i].Width, OverlapParam + 100)));
  488. matCombin.Add(new Mat(list_mats[i], new Rect(0, OverlapParam + 100, list_mats[i].Width, list_mats[i].Height - (OverlapParam + 100) * 2)));
  489. matStitch.Add(new Mat(list_mats[i], new Rect(0, list_mats[i].Height - OverlapParam - 100, list_mats[i].Width, OverlapParam + 100)));
  490. }
  491. }
  492. for (int i = 0; i < matStitch.Count; i += 2)
  493. {
  494. if (matStitch.Count == 1)
  495. {
  496. matCombin.Insert(i + 1, matStitch[i]);
  497. }
  498. else
  499. {
  500. matCombin.Insert(i + 1, StitchImageY(OverlapParam, type, matStitch[i], matStitch[i + 1]));
  501. }
  502. }
  503. Mat pano = new OpenCvSharp.Mat();
  504. Cv2.VConcat(matCombin.ToArray(), pano);
  505. return pano;
  506. }
  507. public struct MStitch
  508. {
  509. public int Pwidth;//单幅图像的宽度
  510. public int Pheight;//单幅图像的高度
  511. public int W_min;//最小的重叠区域宽度
  512. public int W_max;//最大的重叠区域宽度
  513. public int H_min;//最小的重叠区域高度
  514. public double minval;//块过滤阈值
  515. public Mat im;//图像信息
  516. }
  517. public struct ImageParam
  518. {
  519. public int W_box;//宽度信息
  520. public int H_box;//高度信息
  521. public int bdown;//上下信息
  522. public MStitch mStitch; //参数结构
  523. public Mat im;//图像信息
  524. }
  525. /// <summary>
  526. /// 横向拼图
  527. /// </summary>
  528. public Mat StitchImageX(int min_w, int type, Mat newImg1, Mat newImg2)
  529. {
  530. MStitch mStitch = new MStitch();
  531. mStitch.Pwidth = newImg1.Width;
  532. mStitch.Pheight = newImg1.Height;
  533. mStitch.W_min = min_w;
  534. mStitch.W_max = min_w;
  535. mStitch.H_min = newImg1.Height;
  536. mStitch.minval = 255;
  537. mStitch.im = newImg1;
  538. ImageParam imageParam = Fun_Match(newImg2, mStitch);
  539. imageParam.im = newImg2;
  540. if (type == 2)
  541. {
  542. return Fun_Stitch(imageParam);
  543. }
  544. else
  545. {
  546. return Fun_StitchRGB(imageParam);
  547. }
  548. }
  549. /// <summary>
  550. /// 纵向拼图
  551. /// </summary>
  552. public Mat StitchImageY(int min_w, int type, Mat newImg1, Mat newImg2)
  553. {
  554. Cv2.Transpose(newImg1, newImg1);
  555. Cv2.Flip(newImg1, newImg1, FlipMode.X);
  556. Cv2.Transpose(newImg2, newImg2);
  557. Cv2.Flip(newImg2, newImg2, FlipMode.X);
  558. MStitch mStitch = new MStitch();
  559. mStitch.Pwidth = newImg1.Width;
  560. mStitch.Pheight = newImg1.Height;
  561. mStitch.W_min = min_w - 100;
  562. mStitch.W_max = min_w + 100;
  563. mStitch.H_min = newImg1.Height;
  564. mStitch.minval = 255;
  565. mStitch.im = newImg1;
  566. ImageParam imageParam = Fun_Match(newImg2, mStitch);
  567. imageParam.im = newImg2;
  568. Mat result = type == 2 ? Fun_Stitch(imageParam) : Fun_StitchRGB(imageParam);
  569. Cv2.Transpose(result, result);
  570. Cv2.Flip(result, result, FlipMode.Y);
  571. return result;
  572. }
  573. public static ImageParam Fun_Match(Mat im2, MStitch mStitch)
  574. {
  575. ImageParam imageParam = new ImageParam();
  576. double imsum = 0;
  577. int x1 = 0;
  578. int y1 = 0;
  579. int x2 = 0;
  580. int y2 = 0;
  581. int w_ind = 0;
  582. int h_ind = 0;
  583. //在上窗口所有匹配块内进行搜索
  584. for (int w = mStitch.W_min; w <= mStitch.W_max; w++)
  585. {
  586. for (int h = mStitch.H_min; h <= mStitch.Pheight; h++)
  587. {
  588. imsum = 0;//块差分集初始化
  589. x2 = 1;
  590. for (x1 = mStitch.Pwidth - w; x1 <= mStitch.Pwidth; x1 += 5)
  591. {
  592. y2 = 1;
  593. for (y1 = mStitch.Pheight - h + 1; y1 <= mStitch.Pheight; y1 += 5)
  594. {
  595. //块差分集计算
  596. CheckRC(ref x1, ref y1, mStitch.im);
  597. CheckRC(ref x2, ref y2, im2);
  598. imsum = imsum + Math.Abs(mStitch.im.At<Vec3b>(y1, x1).Item0 - im2.At<Vec3b>(y2, x2).Item0);
  599. y2 = y2 + 5;
  600. }
  601. x2 = x2 + 5;
  602. }
  603. //阈值更新
  604. if (imsum * 5 * 5 <= mStitch.minval * w * h)
  605. {
  606. mStitch.minval = imsum * 5 * 5 / (w * h);
  607. w_ind = w;
  608. h_ind = h;
  609. }
  610. }
  611. }
  612. imageParam.W_box = w_ind;
  613. imageParam.H_box = h_ind;
  614. imageParam.bdown = 1;
  615. //在下窗口所有匹配块内进行搜索
  616. Parallel.For(mStitch.W_min, mStitch.W_max, w =>
  617. {
  618. Parallel.For(mStitch.H_min, mStitch.Pheight, h =>
  619. {
  620. imsum = 0;//块差分集初始化
  621. x2 = 1;
  622. for (x1 = mStitch.Pwidth - w; x1 <= mStitch.Pwidth; x1 += 5)
  623. {
  624. y1 = 1;
  625. for (y2 = mStitch.Pheight - h + 1; y2 <= mStitch.Pheight; y2 += 5)
  626. {
  627. //块差分集计算
  628. CheckRC(ref x1, ref y1, mStitch.im);
  629. CheckRC(ref x2, ref y2, im2);
  630. imsum = imsum + Math.Abs(mStitch.im.At<Vec3b>(y1, x1).Item0 - im2.At<Vec3b>(y2, x2).Item0);
  631. y1 = y1 + 5;
  632. }
  633. x2 = x2 + 5;
  634. }
  635. //阈值更新
  636. if (imsum * 5 * 5 <= mStitch.minval * w * h)
  637. {
  638. mStitch.minval = imsum * 5 * 5 / (w * h);
  639. w_ind = w;
  640. h_ind = h;
  641. imageParam.bdown = 0;
  642. }
  643. });
  644. });
  645. imageParam.mStitch = mStitch;
  646. return imageParam;
  647. }
  648. public static void CheckRC(ref int x, ref int y, Mat im)
  649. {
  650. //图像矩阵访问有效性检测
  651. // 输入参数:
  652. // x——列
  653. // y——行
  654. // im——图像矩阵
  655. // 输出参数:
  656. // x——列
  657. // y——行
  658. y = Math.Max(y, 1);
  659. y = Math.Min(y, im.Height - 1);
  660. x = Math.Max(x, 1);
  661. x = Math.Min(x, im.Width - 1);
  662. }
  663. public Mat Fun_Stitch(ImageParam imageParam)
  664. {
  665. //图像融合
  666. //输入参数:
  667. //im2——待融合图像
  668. //W_box——宽度信息
  669. //H_box——高度信息
  670. //bdown——上下信息
  671. //MStitch——参数结构
  672. //输出参数:
  673. //MStitch——参数结构
  674. //im——融合图像
  675. Mat img = imageParam.im;
  676. int x1 = 0;
  677. int y1 = 0;
  678. int x2 = 0;
  679. int y2 = 0;
  680. double w = 0.5; //融合权值
  681. if (imageParam.bdown == 1)
  682. {
  683. //下区域重叠
  684. x2 = 1;
  685. //融合重叠区域
  686. for (x1 = imageParam.mStitch.Pwidth - imageParam.W_box; x1 < imageParam.mStitch.Pwidth; x1++)
  687. {
  688. y2 = 1;
  689. for (y1 = imageParam.mStitch.Pheight - imageParam.H_box + 1; y1 < imageParam.mStitch.Pheight; y1++)
  690. {
  691. //安全性检测
  692. CheckRC(ref x1, ref y1, imageParam.mStitch.im);
  693. CheckRC(ref x2, ref y2, imageParam.im);
  694. //融合权值
  695. w = (double)x2 / (double)imageParam.W_box;
  696. //加权融合
  697. double ColorRGB = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item0 * w;
  698. imageParam.mStitch.im.Set<Vec3b>(y1, x1, new Vec3b((byte)ColorRGB, (byte)ColorRGB, (byte)ColorRGB));
  699. y2 = y2 + 1;
  700. }
  701. x2 = x2 + 1;
  702. }
  703. }
  704. else
  705. {
  706. //上区域重叠
  707. x2 = 1;
  708. //融合重叠区域
  709. for (x1 = imageParam.mStitch.Pwidth - imageParam.W_box; x1 < imageParam.mStitch.Pwidth; x1++)
  710. {
  711. y2 = 1;
  712. for (y1 = imageParam.mStitch.Pheight - imageParam.H_box + 1; y1 < imageParam.mStitch.Pheight; y1++)
  713. {
  714. //安全性检测
  715. CheckRC(ref x1, ref y1, imageParam.mStitch.im);
  716. CheckRC(ref x2, ref y2, imageParam.im);
  717. //融合权值
  718. w = (double)x2 / (double)imageParam.W_box;
  719. //加权融合
  720. double ColorRGB = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item0 * w;
  721. imageParam.mStitch.im.Set<Vec3b>(y1, x1, new Vec3b((byte)ColorRGB, (byte)ColorRGB, (byte)ColorRGB));
  722. y2 = y2 + 1;
  723. }
  724. x2 = x2 + 1;
  725. }
  726. }
  727. //最终图
  728. img = new Mat(imageParam.mStitch.Pheight, imageParam.mStitch.Pwidth + imageParam.im.Width - x2 + 1, MatType.CV_8UC3);
  729. //分离出重叠区域
  730. Rect m_select = new Rect(x2 - 1, 0, imageParam.im.Width - x2 + 1, imageParam.mStitch.Pheight);
  731. Mat imgSwitch = new Mat(imageParam.im, m_select);
  732. Cv2.HConcat(imageParam.mStitch.im, imgSwitch, img);
  733. return img;
  734. }
  735. public Mat Fun_StitchRGB(ImageParam imageParam)
  736. {
  737. //图像融合
  738. //输入参数:
  739. //im2——待融合图像
  740. //W_box——宽度信息
  741. //H_box——高度信息
  742. //bdown——上下信息
  743. //MStitch——参数结构
  744. //输出参数:
  745. //MStitch——参数结构
  746. //im——融合图像
  747. Mat img = imageParam.im;
  748. int x1 = 0;
  749. int y1 = 0;
  750. int x2 = 0;
  751. int y2 = 0;
  752. double w = 0.5; //融合权值
  753. if (imageParam.bdown == 1)
  754. {
  755. //下区域重叠
  756. x2 = 1;
  757. //融合重叠区域
  758. for (x1 = imageParam.mStitch.Pwidth - imageParam.W_box; x1 < imageParam.mStitch.Pwidth; x1++)
  759. {
  760. y2 = 1;
  761. for (y1 = imageParam.mStitch.Pheight - imageParam.H_box + 1; y1 < imageParam.mStitch.Pheight; y1++)
  762. {
  763. //安全性检测
  764. CheckRC(ref x1, ref y1, imageParam.mStitch.im);
  765. CheckRC(ref x2, ref y2, imageParam.im);
  766. //融合权值
  767. w = (double)x2 / (double)imageParam.W_box;
  768. //加权融合
  769. double ColorR = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item0 * w;
  770. double ColorG = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item1 * w;
  771. double ColorB = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item2 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item2 * w;
  772. if (imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 == imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 &&
  773. imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 == imageParam.mStitch.im.At<Vec3b>(y1, x1).Item2 &&
  774. imageParam.im.At<Vec3b>(y2, x2).Item0 == imageParam.im.At<Vec3b>(y2, x2).Item1 &&
  775. imageParam.im.At<Vec3b>(y2, x2).Item1 == imageParam.im.At<Vec3b>(y2, x2).Item2)
  776. {
  777. imageParam.mStitch.im.Set<Vec3b>(y1, x1, new Vec3b((byte)ColorR, (byte)ColorG, (byte)ColorB));
  778. }
  779. else
  780. {
  781. }
  782. y2 = y2 + 1;
  783. }
  784. x2 = x2 + 1;
  785. }
  786. }
  787. else
  788. {
  789. //上区域重叠
  790. x2 = 1;
  791. //融合重叠区域
  792. for (x1 = imageParam.mStitch.Pwidth - imageParam.W_box; x1 < imageParam.mStitch.Pwidth; x1++)
  793. {
  794. y2 = 1;
  795. for (y1 = imageParam.mStitch.Pheight - imageParam.H_box + 1; y1 < imageParam.mStitch.Pheight; y1++)
  796. {
  797. //安全性检测
  798. CheckRC(ref x1, ref y1, imageParam.mStitch.im);
  799. CheckRC(ref x2, ref y2, imageParam.im);
  800. //融合权值
  801. w = (double)x2 / (double)imageParam.W_box;
  802. //加权融合
  803. double ColorR = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item0 * w;
  804. double ColorG = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item1 * w;
  805. double ColorB = imageParam.mStitch.im.At<Vec3b>(y1, x1).Item2 * (1.0 - w) + imageParam.im.At<Vec3b>(y2, x2).Item2 * w;
  806. if (imageParam.mStitch.im.At<Vec3b>(y1, x1).Item0 == imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 &&
  807. imageParam.mStitch.im.At<Vec3b>(y1, x1).Item1 == imageParam.mStitch.im.At<Vec3b>(y1, x1).Item2 &&
  808. imageParam.im.At<Vec3b>(y2, x2).Item0 == imageParam.im.At<Vec3b>(y2, x2).Item1 &&
  809. imageParam.im.At<Vec3b>(y2, x2).Item1 == imageParam.im.At<Vec3b>(y2, x2).Item2)
  810. {
  811. imageParam.mStitch.im.Set<Vec3b>(y1, x1, new Vec3b((byte)ColorR, (byte)ColorG, (byte)ColorB));
  812. }
  813. else
  814. {
  815. }
  816. y2 = y2 + 1;
  817. }
  818. x2 = x2 + 1;
  819. }
  820. }
  821. //最终图
  822. img = new Mat(imageParam.mStitch.Pheight, imageParam.mStitch.Pwidth + imageParam.im.Width - x2 + 1, MatType.CV_8UC3);
  823. //分离出重叠区域
  824. Rect m_select = new Rect(x2 - 1, 0, imageParam.im.Width - x2 + 1, imageParam.mStitch.Pheight);
  825. Mat imgSwitch = new Mat(imageParam.im, m_select);
  826. Cv2.HConcat(imageParam.mStitch.im, imgSwitch, img);
  827. return img;
  828. }
  829. }
  830. }