MorphologyIntent.cs 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309
  1. using OpenCvSharp;
  2. using OpenCvSharp.XImgProc;
  3. using PaintDotNet.Adjust.BaseImage;
  4. using PaintDotNet.Base;
  5. using PaintDotNet.Base.Enum;
  6. using PaintDotNet.Base.Functionodel;
  7. using PaintDotNet.Base.CommTool;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Windows.Forms;
  12. namespace PaintDotNet.Adjust
  13. {
  14. /// <summary>
  15. /// 形态学处理
  16. /// </summary>
  17. public class MorphologyIntent
  18. {
  19. #region 腐蚀
  20. /// <summary>
  21. /// 腐蚀
  22. /// </summary>
  23. /// <param name="mat"></param>
  24. /// <param name="lists"></param>
  25. /// <returns></returns>
  26. public static Mat ImageErosion(Mat mat, List<Args> lists)
  27. {
  28. int count = 1;
  29. Structure structure = Structure.horizon;
  30. for (int i = 0; i < lists.Count; i++)
  31. {
  32. Args args = lists[i];
  33. switch (args.Key)
  34. {
  35. case "Count":
  36. count = int.Parse(args.Value.ToString());
  37. break;
  38. case "Structures":
  39. structure = (Structure)args.Value;
  40. break;
  41. default:
  42. break;
  43. }
  44. }
  45. Mat element = null;
  46. switch (structure)
  47. {
  48. case Structure.horizon:
  49. InputArray kernel1 = InputArray.Create<int>(new int[1, 3] { { 1, 1, 1 } });
  50. element = kernel1.GetMat();
  51. break;
  52. case Structure.angle45:
  53. InputArray kernel2 = InputArray.Create<int>(new int[3, 3] { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } });
  54. element = kernel2.GetMat();
  55. break;
  56. case Structure.vertical:
  57. InputArray kernel3 = InputArray.Create<int>(new int[3, 1] { { 1 }, { 1 }, { 1 } });
  58. element = kernel3.GetMat();
  59. break;
  60. case Structure.angle135:
  61. InputArray kernel4 = InputArray.Create<int>(new int[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } });
  62. element = kernel4.GetMat();
  63. break;
  64. case Structure.cross:
  65. element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(3, 3));
  66. break;
  67. case Structure.square:
  68. element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
  69. break;
  70. case Structure.octagon:
  71. InputArray kernel7 = InputArray.Create<int>(new int[7, 7] {
  72. { 0, 0, 1, 1, 1, 0, 0 },
  73. { 0, 1, 1, 1, 1, 1, 0 },
  74. { 1, 1, 1, 1, 1, 1, 1 },
  75. { 1, 1, 1, 1, 1, 1, 1 },
  76. { 1, 1, 1, 1, 1, 1, 1 },
  77. { 0, 1, 1, 1, 1, 1, 0 },
  78. { 0, 0, 1, 1, 1, 0, 0 }
  79. });
  80. element = kernel7.GetMat();
  81. break;
  82. }
  83. if (structure == Structure.conventional)
  84. {
  85. Cv2.Erode(mat, mat, null, null, count);
  86. }
  87. else
  88. {
  89. element.ConvertTo(element, MatType.CV_8UC1);
  90. Cv2.Erode(mat, mat, element, null, count, BorderTypes.Constant);
  91. if (element != null)
  92. {
  93. element.Dispose();
  94. }
  95. }
  96. return mat;
  97. }
  98. #endregion
  99. #region 膨胀
  100. /// <summary>
  101. /// 膨胀
  102. /// </summary>
  103. /// <param name="mat"></param>
  104. /// <param name="lists"></param>
  105. /// <returns></returns>
  106. public static Mat ImageDilation(Mat mat, List<Args> lists)
  107. {
  108. int count = 1;
  109. Structure structure = Structure.horizon;
  110. for (int i = 0; i < lists.Count; i++)
  111. {
  112. Args args = lists[i];
  113. switch (args.Key)
  114. {
  115. case "Count":
  116. count = int.Parse(args.Value.ToString());
  117. break;
  118. case "Structures":
  119. structure = (Structure)args.Value;
  120. break;
  121. default:
  122. break;
  123. }
  124. }
  125. Mat element = null;
  126. switch (structure)
  127. {
  128. case Structure.horizon:
  129. InputArray kernel1 = InputArray.Create<int>(new int[1, 3] { { 1, 1, 1 } });
  130. element = kernel1.GetMat();
  131. break;
  132. case Structure.angle45:
  133. InputArray kernel2 = InputArray.Create<int>(new int[3, 3] { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } });
  134. element = kernel2.GetMat();
  135. break;
  136. case Structure.vertical:
  137. InputArray kernel3 = InputArray.Create<int>(new int[3, 1] { { 1 }, { 1 }, { 1 } });
  138. element = kernel3.GetMat();
  139. break;
  140. case Structure.angle135:
  141. InputArray kernel4 = InputArray.Create<int>(new int[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } });
  142. element = kernel4.GetMat();
  143. break;
  144. case Structure.cross:
  145. element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(3, 3));
  146. break;
  147. case Structure.square:
  148. element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
  149. break;
  150. case Structure.octagon:
  151. InputArray kernel7 = InputArray.Create<int>(new int[7, 7] {
  152. { 0, 0, 1, 1, 1, 0, 0 },
  153. { 0, 1, 1, 1, 1, 1, 0 },
  154. { 1, 1, 1, 1, 1, 1, 1 },
  155. { 1, 1, 1, 1, 1, 1, 1 },
  156. { 1, 1, 1, 1, 1, 1, 1 },
  157. { 0, 1, 1, 1, 1, 1, 0 },
  158. { 0, 0, 1, 1, 1, 0, 0 }
  159. });
  160. element = kernel7.GetMat();
  161. break;
  162. }
  163. if (structure == Structure.conventional)
  164. {
  165. Cv2.Dilate(mat, mat, null, null, count);
  166. }
  167. else
  168. {
  169. element.ConvertTo(element, MatType.CV_8UC1);
  170. Cv2.Dilate(mat, mat, element, null, count, BorderTypes.Constant);
  171. }
  172. return mat;
  173. }
  174. #endregion
  175. #region 开运算
  176. /// <summary>
  177. /// 开运算
  178. /// </summary>
  179. /// <param name="mat"></param>
  180. /// <param name="lists"></param>
  181. /// <returns></returns>
  182. public static Mat ImageOpen(Mat mat, List<Args> lists)
  183. {
  184. int count = 1;
  185. Structure structure = Structure.horizon;
  186. for (int i = 0; i < lists.Count; i++)
  187. {
  188. Args args = lists[i];
  189. switch (args.Key)
  190. {
  191. case "Count":
  192. count = int.Parse(args.Value.ToString());
  193. break;
  194. case "Structures":
  195. structure = (Structure)args.Value;
  196. break;
  197. default:
  198. break;
  199. }
  200. }
  201. Mat element = null;
  202. switch (structure)
  203. {
  204. case Structure.horizon:
  205. InputArray kernel1 = InputArray.Create<int>(new int[1, 3] { { 1, 1, 1 } });
  206. element = kernel1.GetMat();
  207. break;
  208. case Structure.angle45:
  209. InputArray kernel2 = InputArray.Create<int>(new int[3, 3] { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } });
  210. element = kernel2.GetMat();
  211. break;
  212. case Structure.vertical:
  213. InputArray kernel3 = InputArray.Create<int>(new int[3, 1] { { 1 }, { 1 }, { 1 } });
  214. element = kernel3.GetMat();
  215. break;
  216. case Structure.angle135:
  217. InputArray kernel4 = InputArray.Create<int>(new int[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } });
  218. element = kernel4.GetMat();
  219. break;
  220. case Structure.cross:
  221. element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(3, 3));
  222. break;
  223. case Structure.square:
  224. element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
  225. break;
  226. case Structure.octagon:
  227. InputArray kernel7 = InputArray.Create<int>(new int[7, 7] {
  228. { 0, 0, 1, 1, 1, 0, 0 },
  229. { 0, 1, 1, 1, 1, 1, 0 },
  230. { 1, 1, 1, 1, 1, 1, 1 },
  231. { 1, 1, 1, 1, 1, 1, 1 },
  232. { 1, 1, 1, 1, 1, 1, 1 },
  233. { 0, 1, 1, 1, 1, 1, 0 },
  234. { 0, 0, 1, 1, 1, 0, 0 }
  235. });
  236. element = kernel7.GetMat();
  237. break;
  238. }
  239. if (structure == Structure.conventional)
  240. {
  241. Cv2.MorphologyEx(mat, mat, MorphTypes.Open, null, null, count, BorderTypes.Constant);
  242. }
  243. else
  244. {
  245. element.ConvertTo(element, MatType.CV_8UC1);
  246. Cv2.MorphologyEx(mat, mat, MorphTypes.Open, element, null, count, BorderTypes.Constant);
  247. if (element != null)
  248. {
  249. element.Dispose();
  250. }
  251. }
  252. return mat;
  253. }
  254. #endregion
  255. #region 闭运算
  256. /// <summary>
  257. /// 闭运算
  258. /// </summary>
  259. /// <param name="mat"></param>
  260. /// <param name="lists"></param>
  261. /// <returns></returns>
  262. public static Mat ImageClose(Mat mat, List<Args> lists)
  263. {
  264. int count = 1;
  265. Structure structure = Structure.horizon;
  266. for (int i = 0; i < lists.Count; i++)
  267. {
  268. Args args = lists[i];
  269. switch (args.Key)
  270. {
  271. case "Count":
  272. count = int.Parse(args.Value.ToString());
  273. break;
  274. case "Structures":
  275. structure = (Structure)args.Value;
  276. break;
  277. default:
  278. break;
  279. }
  280. }
  281. Mat element = null;
  282. switch (structure)
  283. {
  284. case Structure.horizon:
  285. InputArray kernel1 = InputArray.Create<int>(new int[1, 3] { { 1, 1, 1 } });
  286. element = kernel1.GetMat();
  287. break;
  288. case Structure.angle45:
  289. InputArray kernel2 = InputArray.Create<int>(new int[3, 3] { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } });
  290. element = kernel2.GetMat();
  291. break;
  292. case Structure.vertical:
  293. InputArray kernel3 = InputArray.Create<int>(new int[3, 1] { { 1 }, { 1 }, { 1 } });
  294. element = kernel3.GetMat();
  295. break;
  296. case Structure.angle135:
  297. InputArray kernel4 = InputArray.Create<int>(new int[3, 3] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } });
  298. element = kernel4.GetMat();
  299. break;
  300. case Structure.cross:
  301. element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(3, 3));
  302. break;
  303. case Structure.square:
  304. element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
  305. break;
  306. case Structure.octagon:
  307. InputArray kernel7 = InputArray.Create<int>(new int[7, 7] {
  308. { 0, 0, 1, 1, 1, 0, 0 },
  309. { 0, 1, 1, 1, 1, 1, 0 },
  310. { 1, 1, 1, 1, 1, 1, 1 },
  311. { 1, 1, 1, 1, 1, 1, 1 },
  312. { 1, 1, 1, 1, 1, 1, 1 },
  313. { 0, 1, 1, 1, 1, 1, 0 },
  314. { 0, 0, 1, 1, 1, 0, 0 }
  315. });
  316. element = kernel7.GetMat();
  317. break;
  318. }
  319. if (structure == Structure.conventional)
  320. {
  321. Cv2.MorphologyEx(mat, mat, MorphTypes.Close, null, null, count, BorderTypes.Constant);
  322. }
  323. else
  324. {
  325. element.ConvertTo(element, MatType.CV_8UC1);
  326. Cv2.MorphologyEx(mat, mat, MorphTypes.Close, element, null, count, BorderTypes.Constant);
  327. if (element != null)
  328. {
  329. element.Dispose();
  330. }
  331. }
  332. return mat;
  333. }
  334. #endregion
  335. #region 粗化/细化
  336. private static int GetArgCount(List<Args> lists)
  337. {
  338. for (int i = 0; i < lists.Count; i++)
  339. {
  340. Args args = lists[i];
  341. if (args.Key == "Count")
  342. {
  343. return int.Parse(args.Value.ToString());
  344. }
  345. }
  346. return 0;
  347. }
  348. /// <summary>
  349. /// 粗化,需要二值化的图像
  350. /// </summary>
  351. /// <param name="mat"></param>
  352. /// <param name="lists"></param>
  353. /// <returns></returns>
  354. public static Mat Thickening(Mat mat, List<Args> lists, int color)
  355. {
  356. System.Drawing.Color color1 = System.Drawing.Color.FromArgb(color);
  357. Mat dstC1 = null;
  358. Mat dstC4 = null;
  359. Mat scrC1 = null;
  360. try
  361. {
  362. scrC1 = new Mat(mat.Size(), MatType.CV_8UC1);
  363. for (int o = 0; o < scrC1.Height; o++)
  364. for (int p = 0; p < scrC1.Width; p++)
  365. {
  366. var v = mat.At<Vec4b>(o, p).Item3;
  367. if (v == 0)
  368. {
  369. scrC1.Set(o, p, 255);
  370. }
  371. else
  372. {
  373. scrC1.Set(o, p, 0);
  374. }
  375. }
  376. //扩充图像边界,方便处理,最后在统一截掉
  377. var times = GetArgCount(lists);//细化执行次数
  378. Thinning(scrC1, out dstC1, times);
  379. dstC4 = new Mat(mat.Size(), OpenCvSharp.MatType.CV_8UC4);
  380. for (int o = 0; o < dstC1.Height; o++)
  381. {
  382. for (int p = 0; p < dstC1.Width; p++)
  383. {
  384. byte v = dstC1.At<byte>(o, p);
  385. if (v > 0)
  386. {
  387. dstC4.Set<Vec4b>(o, p, new Vec4b(0, 0, 0, 0));
  388. }
  389. else
  390. {
  391. dstC4.Set<Vec4b>(o, p, new Vec4b(color1.B, color1.G, color1.R, 255));
  392. }
  393. }
  394. }
  395. dstC4.CopyTo(mat);
  396. return mat;
  397. }
  398. catch (Exception)
  399. {
  400. return mat;
  401. }
  402. finally
  403. {
  404. if (dstC1 != null && !dstC1.IsDisposed) dstC1.Dispose();
  405. if (scrC1 != null && !scrC1.IsDisposed) scrC1.Dispose();
  406. if (dstC4 != null && !dstC4.IsDisposed) dstC4.Dispose();
  407. GC.Collect();
  408. }
  409. }
  410. /// <summary>
  411. /// 细化,需要黑白二值图
  412. /// </summary>
  413. /// <param name="mat"></param>
  414. /// <param name="lists"></param>
  415. /// <returns></returns>
  416. public static Mat Thinning(Mat mat, List<Args> lists, int color)
  417. {
  418. System.Drawing.Color color1 = System.Drawing.Color.FromArgb(color);
  419. Mat dstC4 = null;
  420. Mat dstC1 = null;
  421. Mat scrC1 = null;
  422. try
  423. {
  424. scrC1 = new Mat(mat.Size(), MatType.CV_8UC1);
  425. for (int o = 0; o < scrC1.Height; o++)
  426. for (int p = 0; p < scrC1.Width; p++)
  427. {
  428. var v = mat.At<Vec4b>(o, p).Item3;
  429. if (v > 0)
  430. {
  431. scrC1.Set(o, p, 255);
  432. }
  433. else
  434. {
  435. scrC1.Set(o, p, 0);
  436. }
  437. }
  438. var times = GetArgCount(lists);//细化执行次数
  439. Thinning(scrC1, out dstC1, times);
  440. dstC4 = new Mat(mat.Size(), OpenCvSharp.MatType.CV_8UC4);
  441. for (int o = 0; o < mat.Height; o++)
  442. {
  443. for (int p = 0; p < mat.Width; p++)
  444. {
  445. byte v = dstC1.At<byte>(o, p);
  446. if (v > 0)
  447. {
  448. dstC4.Set<Vec4b>(o, p, new Vec4b(color1.B, color1.G, color1.R, 255));
  449. }
  450. else
  451. {
  452. dstC4.Set<Vec4b>(o, p, new Vec4b(0, 0, 0, 0));
  453. }
  454. }
  455. }
  456. dstC4.CopyTo(mat);
  457. return mat;
  458. }
  459. catch (Exception)
  460. {
  461. return mat;
  462. }
  463. finally
  464. {
  465. if (dstC4 != null && !dstC4.IsDisposed) dstC4.Dispose();
  466. if (dstC1 != null && !dstC1.IsDisposed) dstC1.Dispose();
  467. if (scrC1 != null && !scrC1.IsDisposed) scrC1.Dispose();
  468. }
  469. }
  470. /// <summary>
  471. ///
  472. /// </summary>
  473. /// <param name="src"> Source 8-bit single-channel image, containing binary blobs, with blobs having</param>
  474. /// <returns>Destination image of the same size and the same type as src. The function can</returns>
  475. private static unsafe int Thinning(Mat src, out Mat dst, int times = 0)
  476. {
  477. int i, j, n;
  478. int width, height;
  479. int count = 0;
  480. int edge = 2;
  481. //之所以减1,是方便处理8邻域,防止越界
  482. int p2, p3, p4, p5, p6, p7, p8, p9;
  483. byte* img;
  484. bool ifEnd;
  485. var temp = new Mat(new OpenCvSharp.Size(src.Width + 2 * edge, src.Height + 2 * edge), MatType.CV_8U);
  486. Cv2.CopyMakeBorder(src, temp, edge, edge, edge, edge, BorderTypes.Constant, Scalar.All(255));
  487. dst = temp;
  488. int step = (int)dst.Step();
  489. int[] dir = new int[4] { -step, step, 1, -1 };
  490. width = dst.Cols - 2;
  491. height = dst.Rows - 2;
  492. using (Mat tmpimg = new Mat())
  493. {
  494. do
  495. {
  496. count++;
  497. //分四个子迭代过程,分别对应北,南,东,西四个边界点的情况
  498. ifEnd = false;
  499. for (n = 0; n < 4; n++)
  500. {
  501. dst.CopyTo(tmpimg);
  502. img = tmpimg.DataPointer;
  503. for (i = 1; i < height; i++)
  504. {
  505. img += step;
  506. for (j = 1; j < width; j++)
  507. {
  508. byte* p = img + j;
  509. //如果p点是背景点或者且为方向边界点,依次为北南东西,继续循环
  510. if (p[0] == 0 || p[dir[n]] > 0) continue;
  511. p2 = p[-step] > 0 ? 1 : 0;
  512. p3 = p[-step + 1] > 0 ? 1 : 0;
  513. p4 = p[1] > 0 ? 1 : 0;
  514. p5 = p[step + 1] > 0 ? 1 : 0;
  515. p6 = p[step] > 0 ? 1 : 0;
  516. p7 = p[step - 1] > 0 ? 1 : 0;
  517. p8 = p[-1] > 0 ? 1 : 0;
  518. p9 = p[-step - 1] > 0 ? 1 : 0;
  519. int adjsum;
  520. adjsum = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
  521. //判断是否是邻接点或孤立点,0,1分别对于那个孤立点和端点
  522. if (adjsum > 1)
  523. {
  524. //8 simple判定
  525. int is8simple = 1;
  526. if ((p2 == 0 && p6 == 0) && ((p9 == 1 || p8 == 1 || p7 == 1) && (p3 == 1 || p4 == 1 || p5 == 1)))
  527. is8simple = 0;
  528. else if ((p4 == 0 && p8 == 0) && ((p9 == 1 || p2 == 1 || p3 == 1) && (p5 == 1 || p6 == 1 || p7 == 1)))
  529. is8simple = 0;
  530. else if ((p8 == 0 && p2 == 0) && (p9 == 1 && (p3 == 1 || p4 == 1 || p5 == 1 || p6 == 1 || p7 == 1)))
  531. is8simple = 0;
  532. else if ((p4 == 0 && p2 == 0) && (p3 == 1 && (p5 == 1 || p6 == 1 || p7 == 1 || p8 == 1 || p9 == 1)))
  533. is8simple = 0;
  534. else if ((p8 == 0 && p6 == 0) && (p7 == 1 && (p3 == 9 || p2 == 1 || p3 == 1 || p4 == 1 || p5 == 1)))
  535. is8simple = 0;
  536. else if ((p4 == 0 && p6 == 0) && (p5 == 1 && (p7 == 1 || p8 == 1 || p9 == 1 || p2 == 1 || p3 == 1)))
  537. is8simple = 0;
  538. if (is8simple == 1)
  539. {
  540. dst.Set<byte>(i, j, 0); //满足删除条件,设置当前像素为0
  541. ifEnd = true;
  542. }
  543. }
  544. }
  545. }
  546. }
  547. } while (ifEnd && (times == 0 || count < times));//已经没有可以细化的像素了,则退出迭代
  548. }
  549. dst = new Mat(dst, new Rect(edge, edge, src.Width, src.Height));
  550. return count;
  551. }
  552. /// <summary>
  553. /// OpenCV's Thinning
  554. /// </summary>
  555. private static Mat ThinningCv(Mat src)
  556. {
  557. Mat dst = new Mat(src.Size(), src.Type());
  558. Mat[] arr = src.Split();
  559. CvXImgProc.Thinning(arr[0], dst, ThinningTypes.ZHANGSUEN);
  560. return dst;
  561. }
  562. #endregion
  563. #region 划痕处理 & 污迹处理
  564. /// <summary>
  565. /// 污迹处理
  566. /// </summary>
  567. /// <param name="mat"></param>
  568. /// <param name="lists"></param>
  569. /// <param name="mask">除了需要修复的部分之外其他部分的像素值全部为0</param>
  570. /// <returns></returns>
  571. public static Mat SmudgeTreatment(Mat mat, List<Args> lists, Mat mask)
  572. {
  573. //获取通道数量
  574. int channels = mat.Channels();
  575. //如果是四通道转成三通道
  576. if (channels == 4)
  577. OpenCvSharp.Cv2.CvtColor(mat, mat, OpenCvSharp.ColorConversionCodes.BGRA2BGR);
  578. //处理因子
  579. double inpaintRadius = 5.0;
  580. //读取参数信息
  581. for (int i = 0; i < lists.Count; i++)
  582. {
  583. Args args = lists[i];
  584. switch (args.Key)
  585. {
  586. case "InpaintRadius":
  587. inpaintRadius = double.Parse(args.Value.ToString());
  588. break;
  589. }
  590. }
  591. Mat matCopy = mat.Clone();
  592. //图像修复
  593. Cv2.Inpaint(mat, mask, matCopy, inpaintRadius, InpaintMethod.Telea);
  594. //如果原图是四通道,将处理完之后mat转为四通道
  595. if (channels == 4)
  596. OpenCvSharp.Cv2.CvtColor(matCopy, matCopy, OpenCvSharp.ColorConversionCodes.BGR2BGRA);
  597. return matCopy;
  598. }
  599. /// <summary>
  600. /// 划痕处理
  601. /// </summary>
  602. /// <param name="mat"></param>
  603. /// <param name="lists"></param>
  604. /// <param name="mask">除了需要修复的部分之外其他部分的像素值全部为0</param>
  605. /// <returns></returns>
  606. public static Mat ScratchTreatment(Mat mat, List<Args> lists, Mat mask)
  607. {
  608. //获取通道数量
  609. int channels = mat.Channels();
  610. //如果是四通道转成三通道
  611. if (channels == 4)
  612. OpenCvSharp.Cv2.CvtColor(mat, mat, OpenCvSharp.ColorConversionCodes.BGRA2BGR);
  613. Mat matCopy = mat.Clone();
  614. ////痕宽
  615. //double inpaintRadius = 5.0;
  616. ////读取参数信息
  617. //for (int i = 0; i < lists.Count; i++)
  618. //{
  619. // Args args = lists[i];
  620. // switch (args.Key)
  621. // {
  622. // case "InpaintRadius":
  623. // inpaintRadius = double.Parse(args.Value.ToString());
  624. // break;
  625. // }
  626. //}
  627. //Cv2.ImShow("mat", mat);
  628. //图像修复
  629. Cv2.Inpaint(mat, mask, matCopy/*, inpaintRadius*/, 5.0, InpaintMethod.Telea);
  630. //Cv2.ImShow("matCopy", matCopy);
  631. //如果原图是四通道,将处理完之后mat转为四通道
  632. if (channels == 4)
  633. OpenCvSharp.Cv2.CvtColor(matCopy, matCopy, OpenCvSharp.ColorConversionCodes.BGR2BGRA);
  634. return matCopy;
  635. }
  636. #endregion
  637. #region 分水岭分割
  638. /** the following constants are used to set bits corresponding to pixel types */
  639. static byte MAXIMUM = (byte)1; // marks local maxima (irrespective of noise tolerance)
  640. static byte LISTED = (byte)2; // marks points currently in the list
  641. static byte PROCESSED = (byte)4; // marks points processed previously
  642. static byte MAX_AREA = (byte)8; // marks areas near a maximum, within the tolerance
  643. //static byte EQUAL = (byte)16; // marks contigous maximum points of equal level
  644. //static byte MAX_POINT = (byte)32; // marks a single point standing for a maximum
  645. static byte ELIMINATED = (byte)64; // marks maxima that have been eliminated before watershed
  646. /// <summary>
  647. /// 分水岭分割
  648. /// </summary>
  649. /// <param name="mat"></param>
  650. /// <param name="lists"></param>
  651. /// <returns></returns>
  652. public static Mat WatershedSegment(Mat mat, PhaseModel phase, List<Args> lists)
  653. {
  654. //中间变量
  655. //Mat temp = new Mat();
  656. int paramCount = 0;
  657. //读取参数信息
  658. for (int i = 0; i < lists.Count; i++)
  659. {
  660. Args args = lists[i];
  661. switch (args.Key)
  662. {
  663. case "Count":
  664. paramCount = int.Parse(args.Value.ToString());
  665. break;
  666. }
  667. }
  668. //灰度图
  669. Mat Inmat = phase.mat.CvtColor(ColorConversionCodes.BGR2GRAY);
  670. int width = Inmat.Width;
  671. int height = Inmat.Height;
  672. Mat distance_temp = new Mat();
  673. //Cv2.ImShow("Inmat", Inmat);
  674. Cv2.DistanceTransform(Inmat, distance_temp, DistanceTypes.L2, DistanceMaskSize.Precise);
  675. //Mat dst_temp = new Mat();
  676. //Cv2.Normalize(src_temp, dst_temp, 0, 255, NormTypes.MinMax);
  677. //Mat dst = new Mat();
  678. //dst_temp.ConvertTo(dst, MatType.CV_8UC1);
  679. //Cv2.ImShow("DistanceTransform", dst);
  680. //getSortedMaxPoints............
  681. BitMap2d ip = new BitMap2d(distance_temp);
  682. MaximunFinder maximunFinder = new MaximunFinder(ip);
  683. List<Int16DoubleWithValue> maxPoints = maximunFinder.FindMaxima();
  684. //AnalyzeAndMarkMaxima.............
  685. BitMap2d types = new BitMap2d(width, height, 0);
  686. float globalMin = float.MaxValue;
  687. float globalMax = float.MinValue;
  688. foreach (Int16DoubleWithValue item in maxPoints)
  689. {
  690. if (item.V < globalMin) globalMin = item.V;
  691. if (item.V > globalMax) globalMax = item.V;
  692. types.SetPixel(item.O, MAXIMUM);
  693. }
  694. int nMax = maxPoints.Count();
  695. int[] pList = new int[width * height]; //here we enter points starting from a maximum
  696. int[] dirOffset = new int[] { -width, -width + 1, +1, +width + 1, +width, +width - 1, -1, -width - 1 };
  697. float maxSortingError = (float)(1.1 * (Math.Sqrt(2) / 2));//sorted sequence may be inaccurate by this value
  698. float tolerance = (float)0.5;// 05;
  699. for (int iMax = nMax - 1; iMax >= 0; iMax--)
  700. { //process all maxima now, starting from the highest
  701. int offset0 = maxPoints[iMax].O;
  702. if (((byte)types.GetPixel(offset0) & PROCESSED) != 0) //this maximum has been reached from another one, skip it
  703. continue;
  704. float v0 = ip.GetPixel(offset0);
  705. Boolean sortingError = false;
  706. do
  707. {
  708. pList[0] = offset0;
  709. types.SetPixel(offset0, (byte)((byte)types.GetPixel(offset0) | LISTED)); //mark first point as equal height (to itself) and listed
  710. int listLen = 1; //number of elements in the list
  711. int listI = 0; //index of current element in the list
  712. sortingError = false;
  713. Boolean maxPossible = true; //it may be a true maximum
  714. do
  715. { //while neigbor list is not fully processed (to listLen)
  716. int offset = pList[listI];
  717. int x = offset % width;
  718. int y = offset / width;
  719. Boolean isInner = (y != 0 && y != height - 1) && (x != 0 && x != width - 1); //not necessary, but faster than isWithin
  720. for (int d = 0; d < 8; d++)
  721. { //analyze all neighbors (in 8 directions) at the same level
  722. int offset2 = offset + dirOffset[d];
  723. if ((isInner || isWithin(x, y, d, width, height)) && ((byte)types.GetPixel(offset2) & LISTED) == 0)
  724. {
  725. float v2 = ip.GetPixel(offset2);
  726. if (ip.GetPixel(offset2) <= 0)
  727. {
  728. continue; //ignore the background (non-particles)
  729. }
  730. if (((byte)types.GetPixel(offset2) & PROCESSED) != 0)
  731. {
  732. maxPossible = false; //we have reached a point processed previously, thus it is no maximum now
  733. break;
  734. }
  735. if (v2 > v0 + maxSortingError)
  736. {
  737. maxPossible = false; //we have reached a higher point, thus it is no maximum
  738. break;
  739. }
  740. else if (v2 >= v0 - tolerance)
  741. {
  742. if (v2 > v0)
  743. {
  744. sortingError = true;
  745. offset0 = offset2;
  746. v0 = v2;
  747. }
  748. pList[listLen] = offset2;
  749. listLen++; //we have found a new point within the tolerance
  750. types.SetPixel(offset2, (byte)((byte)types.GetPixel(offset2) | LISTED));
  751. }
  752. } // if isWithin & not LISTED
  753. } // for directions d
  754. listI++;
  755. } while (listI < listLen);
  756. if (sortingError)
  757. { //if x0,y0 was not the true maximum but we have reached a higher one
  758. for (listI = 0; listI < listLen; listI++)
  759. types.SetPixel(pList[listI], (byte)0); //reset all points encountered, then retry
  760. }
  761. else
  762. {
  763. //...............................................................................//
  764. int resetMask = ~LISTED;
  765. for (listI = 0; listI < listLen; listI++)
  766. {
  767. int offset = pList[listI];
  768. types.SetPixel(offset, (byte)((byte)types.GetPixel(offset) & resetMask)); //reset attributes no longer needed
  769. types.SetPixel(offset, (byte)((byte)types.GetPixel(offset) | PROCESSED)); //mark as processed
  770. if (maxPossible)
  771. {
  772. types.SetPixel(offset, (byte)((byte)types.GetPixel(offset) | MAX_AREA)); //reset attributes no longer needed
  773. }
  774. } // for listI
  775. }
  776. }
  777. while (sortingError);
  778. }// for all maxima iMax
  779. //if (nMax == 0) //no initial maxima at all? then consider all as 'within tolerance'
  780. // Arrays.fill(types, (byte)(PROCESSED | MAX_AREA));
  781. //makeUEPs:::
  782. double threshold = 0.5;
  783. //make8bit............
  784. double offset01 = globalMin - (globalMax - globalMin) * (1.0 / 253 / 2 - 1e-6); //everything above minValue should become >(byte)0
  785. double factor = 253 / (globalMax - globalMin);
  786. BitMap2d pixels = new BitMap2d(width, height, 0);
  787. int dataLen = height * width;
  788. for (int offset = 0; offset < dataLen; offset++)
  789. {
  790. float rawValue = ip.GetPixel(offset);
  791. if (rawValue < threshold) { }
  792. else if (((byte)types.GetPixel(offset) & MAX_AREA) != 0)
  793. pixels.SetPixel(offset, (byte)255); //prepare watershed by setting "true" maxima+surroundings to 255
  794. else
  795. {
  796. long v = (long)(1 + Math.Round((rawValue - offset01) * factor));
  797. if (v < 1) pixels.SetPixel(offset, (byte)1);
  798. else if (v <= 254) pixels.SetPixel(offset, (byte)(v & 255));
  799. else pixels.SetPixel(offset, (byte)254);
  800. }
  801. }
  802. //cleanupMaxima............
  803. for (int iMax = nMax - 1; iMax >= 0; iMax--)
  804. {
  805. int offset0 = maxPoints[iMax].O; //type cast gets lower 32 bits where pixel offset is encoded
  806. if (((int)types.GetPixel(offset0) & (MAX_AREA | ELIMINATED)) != 0) continue;
  807. int level = (byte)pixels.GetPixel(offset0) & 255;
  808. int loLevel = level + 1;
  809. pList[0] = offset0; //we start the list at the current maximum
  810. types.SetPixel(offset0, (byte)((byte)types.GetPixel(offset0) | LISTED)); //mark first point as listed
  811. int listLen = 1; //number of elements in the list
  812. int lastLen = 1;
  813. int listI = 0; //index of current element in the list
  814. Boolean saddleFound = false;
  815. while (!saddleFound && loLevel > 0)
  816. {
  817. loLevel--;
  818. lastLen = listLen; //remember end of list for previous level
  819. listI = 0; //in each level, start analyzing the neighbors of all pixels
  820. do
  821. { //for all pixels listed so far
  822. int offset = pList[listI];
  823. int x = offset % width;
  824. int y = offset / width;
  825. Boolean isInner = (y != 0 && y != height - 1) && (x != 0 && x != width - 1); //not necessary, but faster than isWithin
  826. for (int d = 0; d < 8; d++)
  827. { //analyze all neighbors (in 8 directions) at the same level
  828. int offset2 = offset + dirOffset[d];
  829. if ((isInner || isWithin(x, y, d, width, height)) && ((byte)types.GetPixel(offset2) & LISTED) == 0)
  830. {
  831. if (((byte)types.GetPixel(offset2) & MAX_AREA) != 0 || ((((byte)types.GetPixel(offset2) & ELIMINATED) != 0) && ((byte)pixels.GetPixel(offset2) & 255) >= loLevel))
  832. {
  833. saddleFound = true; //we have reached a point touching a "true" maximum...
  834. break; //...or a level not lower, but touching a "true" maximum
  835. }
  836. else if (((byte)pixels.GetPixel(offset2) & 255) >= loLevel && ((byte)types.GetPixel(offset2) & ELIMINATED) == 0)
  837. {
  838. pList[listLen] = offset2;
  839. listLen++; //we have found a new point to be processed
  840. types.SetPixel(offset2, (byte)((byte)types.GetPixel(offset2) | LISTED));
  841. }
  842. } // if isWithin & not LISTED
  843. } // for directions d
  844. if (saddleFound) break; //no reason to search any further
  845. listI++;
  846. } while (listI < listLen);
  847. } // while !levelFound && loLevel>=0
  848. for (listI = 0; listI < listLen; listI++) //reset attribute since we may come to this place again
  849. types.SetPixel(pList[listI], (byte)((byte)types.GetPixel(pList[listI]) & ~LISTED));
  850. for (listI = 0; listI < lastLen; listI++)
  851. { //for all points higher than the level of the saddle point
  852. int offset = pList[listI];
  853. pixels.SetPixel(offset, (byte)loLevel); //set pixel value to the level of the saddle point
  854. types.SetPixel(offset, (byte)((byte)types.GetPixel(offset) | ELIMINATED)); //mark as processed: there can't be a local maximum in this area
  855. }
  856. } // for all maxima iMax
  857. //watershedSegment
  858. int[] histogram = new int[256];
  859. for (int v1 = 0; v1 < 255; v1++)
  860. {
  861. histogram[v1] = 0;
  862. }
  863. for (int offset = 0; offset < dataLen; offset++)
  864. {
  865. int v1 = (byte)pixels.GetPixel(offset) & 255;
  866. if (v1 > 0 && v1 < 255)
  867. {
  868. histogram[v1]++;
  869. }
  870. }
  871. int arraySize = width * height - histogram[0] - histogram[255];
  872. int[] coordinates = new int[arraySize]; //from pixel coordinates, low bits x, high bits y
  873. int highestValue = 0;
  874. int maxBinSize = 0;
  875. int offset02 = 0;
  876. int[] levelStart = new int[256];
  877. for (int v1 = 1; v1 < 255; v1++)
  878. {
  879. levelStart[v1] = offset02;
  880. offset02 += histogram[v1];
  881. if (histogram[v1] > 0) highestValue = v1;
  882. if (histogram[v1] > maxBinSize) maxBinSize = histogram[v1];
  883. }
  884. int[] levelOffset = new int[highestValue + 1];
  885. for (int y = 0, i = 0; y < height; y++)
  886. {
  887. for (int x = 0; x < width; x++, i++)
  888. {
  889. int v1 = (byte)pixels.GetPixel(i) & 255;
  890. if (v1 > 0 && v1 < 255)
  891. {
  892. offset02 = levelStart[v1] + levelOffset[v1];
  893. coordinates[offset02] = x + y * width;
  894. levelOffset[v1]++;
  895. }
  896. } //for x
  897. } //for y
  898. // Create an array of the points (pixel offsets) that we set to 255 in one pass.
  899. // If we remember this list we need not create a snapshot of the ImageProcessor.
  900. int[] setPointList = new int[Math.Min(maxBinSize, (width * height + 2) / 3)];
  901. // now do the segmentation, starting at the highest level and working down.
  902. // At each level, dilate the particle (set pixels to 255), constrained to pixels
  903. // whose values are at that level and also constrained (by the fateTable)
  904. // to prevent features from merging.
  905. int[] table = makeFateTable();
  906. //IJ.showStatus("Segmenting (Esc to cancel)");
  907. /*final */
  908. int[] directionSequence = new int[] { 7, 3, 1, 5, 0, 4, 2, 6 }; // diagonal directions first
  909. for (int level = highestValue; level >= 1; level--)
  910. {
  911. int remaining = histogram[level]; //number of points in the level that have not been processed
  912. int idle = 0;
  913. while (remaining > 0 && idle < 8)
  914. {
  915. int sumN = 0;
  916. int dIndex = 0;
  917. do
  918. { // expand each level in 8 directions
  919. int n = processLevel(directionSequence[dIndex % 8], pixels, table,
  920. levelStart[level], remaining, coordinates, setPointList, width, height);
  921. //IJ.log("level="+level+" direction="+directionSequence[dIndex%8]+" remain="+remaining+"-"+n);
  922. remaining -= n; // number of points processed
  923. sumN += n;
  924. if (n > 0) idle = 0; // nothing processed in this direction?
  925. dIndex++;
  926. } while (remaining > 0 && idle++ < 8);
  927. }
  928. if (remaining > 0 && level > 1)
  929. { // any pixels that we have not reached?
  930. int nextLevel = level; // find the next level to process
  931. do
  932. nextLevel--;
  933. while (nextLevel > 1 && histogram[nextLevel] == 0);
  934. // in principle we should add all unprocessed pixels of this level to the
  935. // tasklist of the next level. This would make it very slow for some images,
  936. // however. Thus we only add the pixels if they are at the border (of the
  937. // image or a thresholded area) and correct unprocessed pixels at the very
  938. // end by CleanupExtraLines
  939. if (nextLevel > 0)
  940. {
  941. int newNextLevelEnd = levelStart[nextLevel] + histogram[nextLevel];
  942. for (int i = 0, p = levelStart[level]; i < remaining; i++, p++)
  943. {
  944. int pOffset = coordinates[p];
  945. int x = pOffset % width;
  946. int y = pOffset / width;
  947. //if ((pixels[pOffset] & 255) == 255) IJ.log("ERROR");
  948. Boolean addToNext = false;
  949. if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
  950. addToNext = true; //image border
  951. else for (int d = 0; d < 8; d++)
  952. if (isWithin(x, y, d, width, height) && pixels.GetPixel(pOffset + dirOffset[d]) == 0)
  953. {
  954. addToNext = true; //border of area below threshold
  955. break;
  956. }
  957. if (addToNext)
  958. coordinates[newNextLevelEnd++] = pOffset;
  959. }
  960. //tasklist for the next level to process becomes longer by this:
  961. histogram[nextLevel] = newNextLevelEnd - levelStart[nextLevel];
  962. }
  963. }
  964. }
  965. System.Drawing.Color color = System.Drawing.Color.FromArgb(phase.color);
  966. Mat matPixels = OpenCvSharp.Extensions.BitmapConverter.ToMat(pixels.MakeBmp());
  967. for (int h = 0; h < matPixels.Height; h++)
  968. {
  969. for (int w = 0; w < matPixels.Width; w++)
  970. {
  971. if (matPixels.At<byte>(h, w) == 0)
  972. matPixels.Set<Vec4b>(h, w, new Vec4b(color.B, color.G, color.R, 255));
  973. else
  974. matPixels.Set<Vec4b>(h, w, new Vec4b(0, 0, 0, 0));
  975. }
  976. }
  977. return matPixels;
  978. }
  979. /** returns whether the neighbor in a given direction is within the image
  980. * NOTE: it is assumed that the pixel x,y itself is within the image!
  981. * Uses class variables width, height: dimensions of the image
  982. * @param x x-coordinate of the pixel that has a neighbor in the given direction
  983. * @param y y-coordinate of the pixel that has a neighbor in the given direction
  984. * @param direction the direction from the pixel towards the neighbor (see makeDirectionOffsets)
  985. * @return true if the neighbor is within the image (provided that x, y is within)
  986. */
  987. public static Boolean isWithin(int x, int y, int direction, int width, int height)
  988. {
  989. int xmax = width - 1;
  990. int ymax = height - 1;
  991. switch (direction)
  992. {
  993. case 0:
  994. return (y > 0);
  995. case 1:
  996. return (x < xmax && y > 0);
  997. case 2:
  998. return (x < xmax);
  999. case 3:
  1000. return (x < xmax && y < ymax);
  1001. case 4:
  1002. return (y < ymax);
  1003. case 5:
  1004. return (x > 0 && y < ymax);
  1005. case 6:
  1006. return (x > 0);
  1007. case 7:
  1008. return (x > 0 && y > 0);
  1009. }
  1010. return false; //to make the compiler happy :-)
  1011. } // isWithin
  1012. /** dilate the UEP on one level by one pixel in the direction specified by step, i.e., set pixels to 255
  1013. * @param pass gives direction of dilation, see makeFateTable
  1014. * @param ip the EDM with the segmeted blobs successively getting set to 255
  1015. * @param table The fateTable
  1016. * @param levelStart offsets of the level in pixelPointers[]
  1017. * @param levelNPoints number of points in the current level
  1018. * @param pixelPointers[] list of pixel coordinates (x+y*width) sorted by level (in sequence of y, x within each level)
  1019. * @param xCoordinates list of x Coorinates for the current level only (no offset levelStart)
  1020. * @return number of pixels that have been changed
  1021. */
  1022. public static int processLevel(int pass, BitMap2d pixels, int[] fateTable,
  1023. int levelStart, int levelNPoints, int[] coordinates, int[] setPointList, int width, int height)
  1024. {
  1025. int xmax = width - 1;
  1026. int ymax = height - 1;
  1027. //byte[] pixels = (byte[])ip.getPixels();
  1028. ////byte[] pixels2 = (byte[])ip2.getPixels();
  1029. int nChanged = 0;
  1030. int nUnchanged = 0;
  1031. for (int i = 0, p = levelStart; i < levelNPoints; i++, p++)
  1032. {
  1033. int offset = coordinates[p];
  1034. int x = offset % width;
  1035. int y = offset / width;
  1036. int index = 0; //neighborhood pixel ocupation: index in fateTable
  1037. if (y > 0 && ((byte)pixels.GetPixel(offset - width) & 255) == 255)
  1038. index ^= 1;
  1039. if (x < xmax && y > 0 && ((byte)pixels.GetPixel(offset - width + 1) & 255) == 255)
  1040. index ^= 2;
  1041. if (x < xmax && ((byte)pixels.GetPixel(offset + 1) & 255) == 255)
  1042. index ^= 4;
  1043. if (x < xmax && y < ymax && ((byte)pixels.GetPixel(offset + width + 1) & 255) == 255)
  1044. index ^= 8;
  1045. if (y < ymax && ((byte)pixels.GetPixel(offset + width) & 255) == 255)
  1046. index ^= 16;
  1047. if (x > 0 && y < ymax && ((byte)pixels.GetPixel(offset + width - 1) & 255) == 255)
  1048. index ^= 32;
  1049. if (x > 0 && ((byte)pixels.GetPixel(offset - 1) & 255) == 255)
  1050. index ^= 64;
  1051. if (x > 0 && y > 0 && ((byte)pixels.GetPixel(offset - width - 1) & 255) == 255)
  1052. index ^= 128;
  1053. int mask = 1 << pass;
  1054. if ((fateTable[index] & mask) == mask)
  1055. setPointList[nChanged++] = offset; //remember to set pixel to 255
  1056. else
  1057. coordinates[levelStart + (nUnchanged++)] = offset; //keep this pixel for future passes
  1058. } // for pixel i
  1059. //IJ.log("pass="+pass+", changed="+nChanged+" unchanged="+nUnchanged);
  1060. for (int i = 0; i < nChanged; i++)
  1061. pixels.SetPixel(setPointList[i], (byte)255);
  1062. return nChanged;
  1063. } //processLevel
  1064. static public int[] makeFateTable()
  1065. {
  1066. int[] table = new int[256];
  1067. Boolean[] isSet = new Boolean[8];
  1068. for (int item = 0; item < 256; item++)
  1069. { //dissect into pixels
  1070. for (int i = 0, mask = 1; i < 8; i++)
  1071. {
  1072. isSet[i] = (item & mask) == mask;
  1073. mask *= 2;
  1074. }
  1075. for (int i = 0, mask = 1; i < 8; i++)
  1076. { //we dilate in the direction opposite to the direction of the existing neighbors
  1077. if (isSet[(i + 4) % 8]) table[item] |= mask;
  1078. mask *= 2;
  1079. }
  1080. for (int i = 0; i < 8; i += 2) //if side pixels are set, for counting transitions it is as good as if the adjacent edges were also set
  1081. if (isSet[i])
  1082. {
  1083. isSet[(i + 1) % 8] = true;
  1084. isSet[(i + 7) % 8] = true;
  1085. }
  1086. int transitions = 0;
  1087. for (int i = 0; i < 8; i++)
  1088. {
  1089. if (isSet[i] != isSet[(i + 1) % 8])
  1090. transitions++;
  1091. }
  1092. if (transitions >= 4)
  1093. { //if neighbors contain more than one region, dilation ito this pixel is forbidden
  1094. table[item] = 0;
  1095. }
  1096. else
  1097. {
  1098. }
  1099. }
  1100. return table;
  1101. } // int[] makeFateTable
  1102. /// <summary>
  1103. /// 分水岭分割
  1104. /// </summary>
  1105. /// <param name="mat"></param>
  1106. /// <param name="lists"></param>
  1107. /// <returns></returns>
  1108. public static Mat WatershedSegment(Mat mat, List<Args> lists)
  1109. {
  1110. //中间变量
  1111. //Mat temp = new Mat();
  1112. int paramCount = 0;
  1113. //读取参数信息
  1114. for (int i = 0; i < lists.Count; i++)
  1115. {
  1116. Args args = lists[i];
  1117. switch (args.Key)
  1118. {
  1119. case "Count":
  1120. paramCount = int.Parse(args.Value.ToString());
  1121. break;
  1122. }
  1123. }
  1124. //灰度图
  1125. Mat Inmat = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
  1126. //BGR
  1127. Mat Src_3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);// .Clone();
  1128. //二值图
  1129. Mat mat_bw = GetBW(Inmat);
  1130. //Cv2.ImShow("mat_bw00", mat_bw);
  1131. Mat result = Oper_Deal(mat_bw, Src_3);
  1132. //mat.CopyTo(temp);
  1133. return result;// temp;
  1134. }
  1135. private static Mat Oper_Deal(Mat ImIn, Mat src_3)
  1136. {
  1137. #region 距离变换
  1138. Mat Im1 = new Mat(ImIn.Size(), ImIn.Type());
  1139. //归一化
  1140. Cv2.Normalize(ImIn, Im1, 0, 1, NormTypes.MinMax);
  1141. Mat Im_dis = new Mat(ImIn.Size(), MatType.CV_32FC1);
  1142. Cv2.DistanceTransform(ImIn, Im_dis, DistanceTypes.L2, DistanceMaskSize.Precise);
  1143. Cv2.Normalize(Im_dis, Im_dis, 0, 1, NormTypes.MinMax);
  1144. Mat conv = new Mat(Im_dis.Size(), MatType.CV_8UC1);
  1145. Im_dis.ConvertTo(conv, MatType.CV_8UC1);
  1146. Cv2.Threshold(conv, conv, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
  1147. #endregion
  1148. #region 轮廓标记
  1149. Mat dis_8U = conv;
  1150. //提取标记
  1151. Point[][] contours; HierarchyIndex[] hierarchy;
  1152. Cv2.FindContours(dis_8U, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple, new Point());
  1153. #endregion
  1154. #region 将标记存入markers,作分水岭注水点用
  1155. var markers = new Mat(ImIn.Size(), MatType.CV_32SC1, Scalar.All(0));
  1156. for (int i = 0; i < contours.Length; i++)
  1157. {
  1158. Cv2.DrawContours(markers, contours, i, Scalar.All(i + 1), 10, LineTypes.Link8, hierarchy);
  1159. }
  1160. #endregion
  1161. Cv2.Watershed(src_3, markers);
  1162. #region 分水岭结果图处理
  1163. //连通域为1,线条为0
  1164. var markers_ind = markers.GetGenericIndexer<int>();
  1165. for (int i = 0; i < markers.Rows; i++)
  1166. {
  1167. for (int j = 0; j < markers.Cols; j++)
  1168. {
  1169. if (markers_ind[i, j] != -1)
  1170. {
  1171. markers_ind[i, j] = int.MaxValue;
  1172. }
  1173. else if (markers_ind[i, j] == -1)
  1174. {
  1175. markers_ind[i, j] = 0;
  1176. }
  1177. }
  1178. }
  1179. //结合初始二值图背景为0
  1180. var ImIn_ind = ImIn.GetGenericIndexer<byte>();
  1181. for (int i = 0; i < markers.Rows; i++)
  1182. {
  1183. for (int j = 0; j < markers.Cols; j++)
  1184. {
  1185. if (ImIn_ind[i, j] == 0)
  1186. {
  1187. markers_ind[i, j] = 0;
  1188. }
  1189. }
  1190. }
  1191. #endregion
  1192. #region 连通域信息
  1193. Mat water = new Mat(markers.Size(), MatType.CV_8UC1);
  1194. markers.ConvertTo(water, MatType.CV_8UC1);
  1195. var water_ind = water.GetGenericIndexer<byte>();
  1196. Mat water_bw = new Mat();
  1197. Cv2.Threshold(water, water_bw, 0, 255, ThresholdTypes.Otsu);
  1198. //连通图的信息获取
  1199. Mat labels = new Mat(); Mat stats = new Mat(); Mat centroids = new Mat();
  1200. int num = Cv2.ConnectedComponentsWithStats(water_bw, labels, stats, centroids);
  1201. #endregion
  1202. #region
  1203. Vec3b[] color = new Vec3b[num + 1];
  1204. color[0] = new Vec3b(0, 0, 0);
  1205. var stats_ind = stats.GetGenericIndexer<int>();
  1206. Random rand = new Random();
  1207. byte ranB = (byte)rand.Next(100, 255); byte ranG = (byte)rand.Next(100, 255); byte ranR = (byte)rand.Next(100, 255);
  1208. for (int i = 1; i < num; i++)
  1209. {
  1210. color[i] = new Vec3b(ranB, ranG, ranR);
  1211. int S = stats_ind[i, 4];
  1212. if (S < 200)
  1213. {
  1214. color[i] = new Vec3b(0, 0, 0);
  1215. }
  1216. }
  1217. #endregion
  1218. #region mat填色
  1219. Mat final = new Mat(water.Size(), MatType.CV_8UC3);
  1220. for (int i = 0; i < final.Rows; i++)
  1221. {
  1222. for (int j = 0; j < final.Cols; j++)
  1223. {
  1224. int label = labels.Get<int>(i, j);
  1225. final.Set<Vec3b>(i, j, color[label]);
  1226. }
  1227. }
  1228. #endregion
  1229. return final;
  1230. }
  1231. private static Mat GetBW(Mat Src)
  1232. {
  1233. //(最大类间方差)二值化
  1234. //Mat result = Src.Threshold(109.242, 255, ThresholdTypes.Otsu);
  1235. Mat result = Src.AdaptiveThreshold(255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 35, 5);
  1236. //Cv2.ImShow("test", result); Cv2.WaitKey();
  1237. return result;
  1238. }
  1239. #endregion
  1240. #region 去碎屑
  1241. /// <summary>
  1242. /// 去碎屑(功能实际是颗粒筛选的功能)
  1243. /// 需要传进来二值的图
  1244. /// </summary>
  1245. /// <param name="mat"></param>
  1246. /// <param name="lists"></param>
  1247. /// <returns></returns>
  1248. public static Mat Debris(Mat mat, List<Args> lists, int color, double rule)
  1249. {
  1250. //相颜色
  1251. System.Drawing.Color color1 = System.Drawing.Color.FromArgb(color);
  1252. //原始轮廓信息
  1253. OpenCvSharp.Point[][] contours;
  1254. //轮廓的拓扑信息
  1255. HierarchyIndex[] hierachy;
  1256. //筛选参数
  1257. FilterParameters filterParameters = FilterParameters.Area;
  1258. //筛选范围
  1259. double min = 0, max = 0;
  1260. //筛选单位
  1261. MeasurementUnit measurementUnit = MeasurementUnit.Pixel;
  1262. //筛选单方式
  1263. FunctionParameters functionParameters = FunctionParameters.Choise;
  1264. //边界保留
  1265. bool boundaryPreservation = false;
  1266. //中间变量
  1267. Mat temp = new Mat();
  1268. //轮廓总面积
  1269. //double areas = 0;
  1270. //删除的边界
  1271. List<int> deleteIndexs = new List<int>();
  1272. //读取参数信息
  1273. for (int i = 0; i < lists.Count; i++)
  1274. {
  1275. Args args = lists[i];
  1276. switch (args.Key)
  1277. {
  1278. case "FilterParameters":
  1279. filterParameters = (FilterParameters)args.Value;
  1280. break;
  1281. case "Scope":
  1282. min = ((List<double>)args.Value)[0];
  1283. max = ((List<double>)args.Value)[1];
  1284. break;
  1285. case "UnitParameters":
  1286. measurementUnit = (MeasurementUnit)args.Value;
  1287. break;
  1288. case "FunctionParameters":
  1289. functionParameters = (FunctionParameters)args.Value;
  1290. break;
  1291. case "BoundaryPreservation":
  1292. boundaryPreservation = (bool)args.Value;
  1293. break;
  1294. }
  1295. }
  1296. mat.CopyTo(temp);
  1297. Cv2.FindContours(mat.CvtColor(ColorConversionCodes.BGR2GRAY), out contours, out hierachy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone);
  1298. //没有选中边界保留
  1299. if (!boundaryPreservation)
  1300. {
  1301. if (contours.Length > 0)
  1302. {
  1303. for (int i = 0; i < contours.Length; i++)
  1304. {
  1305. for (int y = 0; y < contours[i].Length; y++)
  1306. {
  1307. if (contours[i][y].X == 0 || contours[i][y].X == temp.Width - 1 || contours[i][y].Y == 0 || contours[i][y].Y == temp.Height - 1)
  1308. {
  1309. deleteIndexs.Add(i);
  1310. List<OpenCvSharp.Point[]> pointsTemp = new List<OpenCvSharp.Point[]>();
  1311. RecursiveFindChildContours(contours.ToList(), hierachy, i, deleteIndexs);
  1312. break;
  1313. }
  1314. }
  1315. }
  1316. }
  1317. //用于绘制的轮廓
  1318. List<OpenCvSharp.Point[]> drawContours = contours.ToList<OpenCvSharp.Point[]>();
  1319. //循环处理轮廓,过滤到被删除的轮廓及其子轮廓
  1320. if (deleteIndexs.Count > 0)
  1321. {
  1322. drawContours.Clear();
  1323. for (int i = 0; i < contours.Length; i++)
  1324. {
  1325. if (!deleteIndexs.Exists(a => a == i))// && !deleteIndexs.Exists(a => a == hierachy[i].Parent)
  1326. {
  1327. drawContours.Add(contours[i]);
  1328. }
  1329. }
  1330. }
  1331. temp = new Mat(mat.Size(), mat.Type());
  1332. Cv2.FillPoly(temp, drawContours, new Scalar(color1.B, color1.G, color1.R, 255), LineTypes.Link8);
  1333. }
  1334. /*//计算总面积
  1335. foreach (Point[] points in contours)
  1336. {
  1337. areas += Math.Abs(Cv2.ContourArea(points));
  1338. }
  1339. if (measurementUnit == MeasurementUnit.Micron) areas = areas * rule;*/
  1340. List<List<OpenCvSharp.Point>> ps = new List<List<OpenCvSharp.Point>>();
  1341. for (int i = 0; i < hierachy.Length; i++)
  1342. {
  1343. if (deleteIndexs.Exists(a => a == i))
  1344. continue;
  1345. //计算面积
  1346. if (filterParameters == FilterParameters.Area)
  1347. {
  1348. double area = Math.Abs(Cv2.ContourArea(contours[i]));
  1349. if (measurementUnit == MeasurementUnit.Micron) area = area * rule * rule;
  1350. if (functionParameters == FunctionParameters.Remove)
  1351. {
  1352. if (area >= min && area <= max && hierachy[i].Parent == -1)
  1353. {
  1354. ps.Add(contours[i].ToList());
  1355. }
  1356. }
  1357. else if (functionParameters == FunctionParameters.Choise)
  1358. {
  1359. if (area <= min || area >= max && hierachy[i].Parent == -1)
  1360. {
  1361. ps.Add(contours[i].ToList());
  1362. }
  1363. }
  1364. }
  1365. //计算面积比
  1366. else if (filterParameters == FilterParameters.AreaRatio)
  1367. {
  1368. double area = Math.Abs(Cv2.ContourArea(contours[i]));
  1369. Point2f center;
  1370. float radius;
  1371. Cv2.MinEnclosingCircle(contours[i], out center, out radius);
  1372. double areas = Math.PI * radius * radius;
  1373. if (measurementUnit == MeasurementUnit.Micron)
  1374. {
  1375. area = area * rule * rule;
  1376. areas = areas * rule * rule;
  1377. }
  1378. if (functionParameters == FunctionParameters.Remove)
  1379. {
  1380. if (area / areas > min && area / areas < max && hierachy[i].Parent == -1)
  1381. {
  1382. ps.Add(contours[i].ToList());
  1383. }
  1384. }
  1385. else if (functionParameters == FunctionParameters.Choise)
  1386. {
  1387. if (area / areas < min || area / areas > max && hierachy[i].Parent == -1)
  1388. {
  1389. ps.Add(contours[i].ToList());
  1390. }
  1391. }
  1392. }
  1393. //计算宽高比
  1394. else if (filterParameters == FilterParameters.AspectRatio)
  1395. {
  1396. double area = BasicCalculationHelper.CalcAspectRatio(contours[i]);
  1397. if (functionParameters == FunctionParameters.Remove)
  1398. {
  1399. if (area > min && area < max && hierachy[i].Parent == -1)
  1400. {
  1401. ps.Add(contours[i].ToList());
  1402. }
  1403. }
  1404. else if (functionParameters == FunctionParameters.Choise)
  1405. {
  1406. if (area < min || area > max && hierachy[i].Parent == -1)
  1407. {
  1408. ps.Add(contours[i].ToList());
  1409. }
  1410. }
  1411. }
  1412. //计算最大卡规直径(长径)
  1413. else if (filterParameters == FilterParameters.LongTrail)
  1414. {
  1415. double area = BasicCalculationHelper.CalcLongTrail(contours[i]) * 2;
  1416. if (measurementUnit == MeasurementUnit.Micron) area = area * rule;
  1417. if (functionParameters == FunctionParameters.Remove)
  1418. {
  1419. if (area > min && area < max && hierachy[i].Parent == -1)
  1420. {
  1421. ps.Add(contours[i].ToList());
  1422. }
  1423. }
  1424. else if (functionParameters == FunctionParameters.Choise)
  1425. {
  1426. if (area < min || area > max && hierachy[i].Parent == -1)
  1427. {
  1428. ps.Add(contours[i].ToList());
  1429. }
  1430. }
  1431. }
  1432. }
  1433. if (functionParameters == FunctionParameters.Choise)
  1434. Cv2.FillPoly(temp, ps, Scalar.Red);
  1435. else if (functionParameters == FunctionParameters.Remove)
  1436. Cv2.FillPoly(temp, ps, new Scalar(0, 0, 0, 0));
  1437. return temp;
  1438. }
  1439. private static void RecursiveFindChildContours(
  1440. List<OpenCvSharp.Point[]> drawContours,
  1441. HierarchyIndex[] hierachy,
  1442. int position,
  1443. List<int> points
  1444. )
  1445. {
  1446. int m = 0;
  1447. foreach (HierarchyIndex index in hierachy)
  1448. {
  1449. if (index.Parent == position)
  1450. {
  1451. points.Add(m);
  1452. RecursiveFindChildContours(drawContours, hierachy, m, points);
  1453. }
  1454. m++;
  1455. }
  1456. }
  1457. #endregion
  1458. #region 孔洞删除
  1459. /// <summary>
  1460. /// 孔洞删除,用其它颜色进行填充
  1461. /// </summary>
  1462. /// <param name="mat"></param>
  1463. /// <param name="lists"></param>
  1464. /// <returns></returns>
  1465. public static Mat HoleRemoval(Mat mat, List<Args> lists, int pColor, double rule, out double outmin, out double outmax)
  1466. {
  1467. //原始轮廓信息
  1468. OpenCvSharp.Point[][] contours;
  1469. //轮廓的拓扑信息
  1470. HierarchyIndex[] hierachy;
  1471. //筛选参数
  1472. FilterParameters filterParameters = FilterParameters.Area;
  1473. //筛选范围
  1474. double min = 0, max = 0;
  1475. //输出的值
  1476. outmin = -1;
  1477. outmax = -1;
  1478. //筛选单位
  1479. MeasurementUnit measurementUnit = MeasurementUnit.Pixel;
  1480. //孔洞颜色
  1481. int color = 0;
  1482. //面积合计大小
  1483. //double areas = 0;
  1484. //读取参数信息
  1485. for (int i = 0; i < lists.Count; i++)
  1486. {
  1487. Args args = lists[i];
  1488. switch (args.Key)
  1489. {
  1490. case "FilterParameters":
  1491. filterParameters = (FilterParameters)args.Value;
  1492. break;
  1493. case "Scope":
  1494. min = ((List<double>)args.Value)[0];
  1495. max = ((List<double>)args.Value)[1];
  1496. break;
  1497. case "UnitParameters":
  1498. measurementUnit = (MeasurementUnit)args.Value;
  1499. break;
  1500. case "HoleColor":
  1501. color = (int)args.Value;
  1502. break;
  1503. }
  1504. }
  1505. System.Drawing.Color color1 = System.Drawing.Color.FromArgb(color);
  1506. System.Drawing.Color color2 = System.Drawing.Color.FromArgb(pColor);
  1507. Mat dst = new Mat();
  1508. mat.CopyTo(dst);
  1509. Cv2.FindContours(dst.CvtColor(ColorConversionCodes.BGR2GRAY), out contours, out hierachy, RetrievalModes.Tree, ContourApproximationModes.ApproxNone);
  1510. /*//计算总面积
  1511. foreach (Point[] points in contours)
  1512. {
  1513. areas += Math.Abs(Cv2.ContourArea(points));
  1514. }
  1515. if (measurementUnit == MeasurementUnit.Micron) areas = areas * rule * rule;*/
  1516. List<int> ints = new List<int>();
  1517. List<List<OpenCvSharp.Point>> ps = new List<List<OpenCvSharp.Point>>();
  1518. List<List<OpenCvSharp.Point>> ps1 = new List<List<OpenCvSharp.Point>>();
  1519. for (int i = 0; i < hierachy.Length; i++)
  1520. {
  1521. if (hierachy[i].Parent > -1)
  1522. {
  1523. ps1.Add(contours[i].ToList());
  1524. //计算面积
  1525. if (filterParameters == FilterParameters.Area)
  1526. {
  1527. double area = Math.Abs(Cv2.ContourArea(contours[i]));
  1528. //double area = BasicCalculationHelper.DecimalCeiling(Math.Abs(Cv2.ContourArea(contours[i])));
  1529. if (measurementUnit == MeasurementUnit.Micron) area = area * rule * rule;
  1530. if (outmin == -1)
  1531. {
  1532. outmin = area;
  1533. outmax = area;
  1534. }
  1535. else
  1536. {
  1537. if (outmin > area) outmin = BasicCalculationHelper.DecimalFloor(area);
  1538. if (outmax < area) outmax = BasicCalculationHelper.DecimalCeiling(area);
  1539. }
  1540. if (area >= min && area <= max)
  1541. {
  1542. ints.Add(i);
  1543. //ps.Add(contours[i].ToList());
  1544. }
  1545. }
  1546. //计算面积比
  1547. else if (filterParameters == FilterParameters.AreaRatio)
  1548. {
  1549. double area = Math.Abs(Cv2.ContourArea(contours[i]));
  1550. Point2f point;
  1551. float radius;
  1552. Cv2.MinEnclosingCircle(contours[i], out point, out radius);
  1553. double areas = Math.PI * radius * radius;
  1554. if (outmin == -1)
  1555. {
  1556. outmin = area / areas;
  1557. outmax = Math.Round(area / areas, 2);
  1558. }
  1559. else
  1560. {
  1561. if (outmin > area / areas) outmin = area / areas;
  1562. if (outmax < area / areas) outmax = Math.Round(area / areas, 2);
  1563. }
  1564. if (area / areas >= min && Math.Round(area / areas, 2) <= max)
  1565. {
  1566. ints.Add(i);
  1567. //ps.Add(contours[i].ToList());
  1568. }
  1569. }
  1570. //计算宽高比
  1571. else if (filterParameters == FilterParameters.AspectRatio)
  1572. {
  1573. double area = Math.Round(BasicCalculationHelper.CalcAspectRatio(contours[i]), 2);
  1574. if (outmin == -1)
  1575. {
  1576. outmin = area;
  1577. outmax = area;
  1578. }
  1579. else
  1580. {
  1581. if (outmin > area) outmin = area;
  1582. if (outmax < area) outmax = area;
  1583. }
  1584. if (area >= min && area <= max)
  1585. {
  1586. ints.Add(i);
  1587. //ps.Add(contours[i].ToList());
  1588. }
  1589. }
  1590. //计算最大卡规直径(长径)
  1591. else if (filterParameters == FilterParameters.LongTrail)
  1592. {
  1593. double area = BasicCalculationHelper.CalcLongTrail(contours[i]) * 2;
  1594. if (measurementUnit == MeasurementUnit.Micron) area = area * rule;
  1595. if (outmin == -1)
  1596. {
  1597. outmin = area;
  1598. outmax = area;
  1599. }
  1600. else
  1601. {
  1602. if (outmin > area) outmin = BasicCalculationHelper.DecimalFloor(area);
  1603. if (outmax < area) outmax = BasicCalculationHelper.DecimalCeiling(area);
  1604. }
  1605. if (area >= min && area <= max)
  1606. {
  1607. ints.Add(i);
  1608. //his.Add(hierachy[i]);
  1609. //ps.Add(contours[i].ToList());
  1610. }
  1611. }
  1612. }
  1613. }
  1614. Cv2.FillPoly(mat, ps1, new Scalar(color1.B, color1.G, color1.R, color1.A));
  1615. for (int k = 0; k < ints.Count(); k++)
  1616. {
  1617. Cv2.DrawContours(mat, contours, ints[k], new Scalar(color2.B, color2.G, color2.R, 255), -1, LineTypes.Link8, hierachy, 0);
  1618. }
  1619. //foreach (List<Point> points in ps)
  1620. //{
  1621. //Cv2.FillPoly(mat, InputArray.Create(ps[0]), new Scalar(color2.B, color2.G, color2.R, 255));
  1622. //}
  1623. //Cv2.DrawContours(mat, ps, -1, new Scalar(color2.B, color2.G, color2.R, 255), -1, LineTypes.Link8, his, 1);
  1624. //Cv2.FillPoly(mat, ps, new Scalar(color2.B, color2.G, color2.R, 255));
  1625. return mat;
  1626. }
  1627. #endregion
  1628. #region 抽骨架
  1629. unsafe byte* pixels;
  1630. int foreground;
  1631. int width, height;
  1632. int xMin, xMax, yMin, yMax;
  1633. Mat dst;
  1634. /// <summary>
  1635. /// 抽骨架
  1636. /// 使用demo里面的form26里面的ImageJ查表法
  1637. /// </summary>
  1638. /// <param name="mat"></param>
  1639. /// <param name="lists"></param>
  1640. /// <returns></returns>
  1641. public unsafe Mat ImageSkeleton(Mat mat, List<Args> lists, int color)
  1642. {
  1643. //如果不是单通道,转单通道
  1644. if (mat.Type() != MatType.CV_8UC1)
  1645. {
  1646. Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
  1647. }
  1648. //判断是否二值化图像
  1649. if (!BaseTools.DetermineBinaryImageByHist(mat))
  1650. {
  1651. MessageBox.Show("Please enter abinarization image");
  1652. return mat;
  1653. }
  1654. //判断是否黑白的二值图
  1655. if (!BaseTools.DetermineBinaryImage(mat))
  1656. {
  1657. //处理为黑/白二值化的图像
  1658. for (int o = 0; o < mat.Height; o++)
  1659. {
  1660. for (int p = 0; p < mat.Width; p++)
  1661. {
  1662. byte v = mat.At<byte>(o, p);
  1663. if (v > 0)
  1664. {
  1665. mat.Set<byte>(o, p, 255);
  1666. }
  1667. }
  1668. }
  1669. }
  1670. //背景颜色
  1671. int fg = 0;
  1672. //前景颜色
  1673. foreground = 255 - fg;
  1674. int pass = 0;
  1675. int pixelsRemoved;
  1676. dst = new Mat();
  1677. bool edgePixels = hasEdgePixels(mat);
  1678. if (edgePixels)
  1679. {
  1680. dst = new Mat(new OpenCvSharp.Size(mat.Width + 2, mat.Height + 2), MatType.CV_8UC1, Scalar.All(0));
  1681. Cv2.CopyMakeBorder(mat, dst, 1, 1, 1, 1, BorderTypes.Constant, Scalar.All(0));
  1682. }
  1683. else
  1684. {
  1685. mat.CopyTo(dst);
  1686. }
  1687. width = dst.Width;
  1688. height = dst.Height;
  1689. xMin = 1;
  1690. xMax = width - 2;
  1691. yMin = 1;
  1692. yMax = height - 2;
  1693. pixels = (byte*)dst.Data;
  1694. do
  1695. {
  1696. pixelsRemoved = thin(pass++, BaseTools.table);
  1697. pixelsRemoved += thin(pass++, BaseTools.table);
  1698. } while (pixelsRemoved > 0);
  1699. do
  1700. {
  1701. pixelsRemoved = thin(pass++, BaseTools.table2);
  1702. pixelsRemoved += thin(pass++, BaseTools.table2);
  1703. } while (pixelsRemoved > 0);
  1704. BaseTools.shrink(mat, dst, edgePixels);
  1705. System.Drawing.Color color1 = System.Drawing.Color.FromArgb(color);
  1706. Mat temp1 = new Mat(mat.Size(), OpenCvSharp.MatType.CV_8UC4);
  1707. for (int o = 0; o < mat.Height; o++)
  1708. {
  1709. for (int p = 0; p < mat.Width; p++)
  1710. {
  1711. byte v = dst.At<byte>(o, p);
  1712. if (v > 0)
  1713. {
  1714. temp1.Set<Vec4b>(o, p, new Vec4b(color1.B, color1.G, color1.R, 255));
  1715. }
  1716. else
  1717. {
  1718. temp1.Set<Vec4b>(o, p, new Vec4b(0, 0, 0, 0));
  1719. }
  1720. }
  1721. }
  1722. temp1.CopyTo(mat);
  1723. return mat;
  1724. }
  1725. bool hasEdgePixels(Mat ip)
  1726. {
  1727. int width = ip.Width;
  1728. int height = ip.Height;
  1729. bool edgePixels = false;
  1730. for (int x = 0; x < width; x++)
  1731. { // top edge
  1732. if (ip.At<byte>(0, x) == foreground)
  1733. edgePixels = true;
  1734. }
  1735. for (int x = 0; x < width; x++)
  1736. { // bottom edge
  1737. if (ip.At<byte>(height - 1, x) == foreground)
  1738. edgePixels = true;
  1739. }
  1740. for (int y = 0; y < height; y++)
  1741. { // left edge
  1742. if (ip.At<byte>(y, 0) == foreground)
  1743. edgePixels = true;
  1744. }
  1745. for (int y = 0; y < height; y++)
  1746. { // right edge
  1747. if (ip.At<byte>(y, width - 1) == foreground)
  1748. edgePixels = true;
  1749. }
  1750. return edgePixels;
  1751. }
  1752. unsafe int thin(int pass, int[] table)
  1753. {
  1754. int p1, p2, p3, p4, p5, p6, p7, p8, p9;
  1755. int bgColor = 0; //255
  1756. //if (parent.isInvertedLut())
  1757. // bgColor = 0;
  1758. Mat temp = new Mat();
  1759. dst.CopyTo(temp);
  1760. byte* pixels2 = (byte*)temp.Data;
  1761. int v, index, code;
  1762. int offset, rowOffset = temp.Width;
  1763. int pixelsRemoved = 0;
  1764. for (int y = yMin; y <= yMax; y++)
  1765. {
  1766. offset = xMin + y * temp.Width;
  1767. for (int x = xMin; x <= xMax; x++)
  1768. {
  1769. p5 = pixels2[offset];
  1770. v = p5;
  1771. if (v != bgColor)
  1772. {
  1773. p1 = pixels2[offset - rowOffset - 1];
  1774. p2 = pixels2[offset - rowOffset];
  1775. p3 = pixels2[offset - rowOffset + 1];
  1776. p4 = pixels2[offset - 1];
  1777. p6 = pixels2[offset + 1];
  1778. p7 = pixels2[offset + rowOffset - 1];
  1779. p8 = pixels2[offset + rowOffset];
  1780. p9 = pixels2[offset + rowOffset + 1];
  1781. index = 0;
  1782. if (p1 != bgColor) index |= 1;
  1783. if (p2 != bgColor) index |= 2;
  1784. if (p3 != bgColor) index |= 4;
  1785. if (p6 != bgColor) index |= 8;
  1786. if (p9 != bgColor) index |= 16;
  1787. if (p8 != bgColor) index |= 32;
  1788. if (p7 != bgColor) index |= 64;
  1789. if (p4 != bgColor) index |= 128;
  1790. code = table[index];
  1791. if ((pass & 1) == 1)
  1792. { //odd pass
  1793. if (code == 2 || code == 3)
  1794. {
  1795. v = bgColor;
  1796. pixelsRemoved++;
  1797. }
  1798. }
  1799. else
  1800. { //even pass
  1801. if (code == 1 || code == 3)
  1802. {
  1803. v = bgColor;
  1804. pixelsRemoved++;
  1805. }
  1806. }
  1807. }
  1808. pixels[offset++] = (byte)v;
  1809. }
  1810. }
  1811. return pixelsRemoved;
  1812. }
  1813. #endregion
  1814. #region 空洞填充
  1815. /// <summary>
  1816. /// 孔洞填充
  1817. /// </summary>
  1818. /// <param name="mat"></param>
  1819. /// <param name="c"></param>
  1820. /// <returns></returns>
  1821. public static Mat HolesFill(Mat mat, int c)
  1822. {
  1823. Mat temp = null;
  1824. try
  1825. {
  1826. //mat的颜色
  1827. System.Drawing.Color color = System.Drawing.Color.FromArgb(c);
  1828. //原始轮廓信息
  1829. OpenCvSharp.Point[][] contours;
  1830. //轮廓的拓扑信息
  1831. HierarchyIndex[] hierachy;
  1832. //中间变量
  1833. temp = new Mat();
  1834. mat.CopyTo(temp);
  1835. Cv2.FindContours(temp.CvtColor(ColorConversionCodes.BGRA2GRAY), out contours, out hierachy, RetrievalModes.Tree, ContourApproximationModes.ApproxNone);
  1836. if (hierachy != null)
  1837. {
  1838. for (int i = 0; i < hierachy.Length; i++)
  1839. {
  1840. //如果需要还可以判断面积范围
  1841. if (hierachy[i].Parent > -1)
  1842. {
  1843. Vec3b vec3B = mat.At<Vec3b>(contours[i][0].Y, contours[i][0].X);
  1844. if ((vec3B.Item0 == (byte)color.B) && (vec3B.Item1 == (byte)color.G) && (vec3B.Item2 == (byte)(color.R)))
  1845. {
  1846. List<List<OpenCvSharp.Point>> ps = new List<List<OpenCvSharp.Point>>();
  1847. ps.Add(contours[i].ToList());
  1848. Cv2.FillPoly(mat, ps, new Scalar(color.B, color.G, color.R, 255));
  1849. }
  1850. }
  1851. }
  1852. }
  1853. }
  1854. catch (Exception)
  1855. {
  1856. System.Windows.Forms.MessageBox.Show("Abnormal program");
  1857. }
  1858. finally
  1859. {
  1860. if (temp != null && !temp.IsDisposed) temp.Dispose();
  1861. }
  1862. return mat;
  1863. }
  1864. #endregion
  1865. #region 形态学分割
  1866. public static Mat MorphologySegment(Mat mat, PhaseModel model, List<Args> lists)
  1867. {
  1868. //获取参数
  1869. int paramCount = 0;
  1870. //读取参数信息
  1871. for (int i = 0; i < lists.Count; i++)
  1872. {
  1873. Args args = lists[i];
  1874. switch (args.Key)
  1875. {
  1876. case "Count":
  1877. paramCount = int.Parse(args.Value.ToString());
  1878. break;
  1879. }
  1880. }
  1881. //处理相
  1882. for (int h = 0; h < model.mat.Height; h++)
  1883. {
  1884. for (int w = 0; w < model.mat.Width; w++)
  1885. {
  1886. Vec4b vec4B = model.mat.At<Vec4b>(h, w);
  1887. if (vec4B.Item3 == 0)
  1888. {
  1889. model.mat.Set<Vec4b>(h, w, new Vec4b(255, 255, 255, 255));
  1890. }
  1891. else
  1892. {
  1893. model.mat.Set<Vec4b>(h, w, new Vec4b(0, 0, 0, 255));
  1894. }
  1895. }
  1896. }
  1897. //构造八边形的卷积核
  1898. InputArray kernel = InputArray.Create<int>(new int[5, 5] {
  1899. { 0, 1, 1, 1, 0 },
  1900. { 1, 1, 1, 1, 1 },
  1901. { 1, 1, 1, 1, 1 },
  1902. { 1, 1, 1, 1, 1 },
  1903. { 0, 1, 1, 1, 0 } });
  1904. Mat element = kernel.GetMat();
  1905. element.ConvertTo(element, MatType.CV_8UC1);
  1906. Mat lab1Img = new Mat();
  1907. model.mat.CopyTo(lab1Img);
  1908. //原图灰度化
  1909. Mat img = lab1Img.CvtColor(ColorConversionCodes.BGR2GRAY);
  1910. //用来判断极限腐蚀是否完成的中间变量
  1911. Mat erode = new Mat();
  1912. img.CopyTo(erode);
  1913. //用来观察腐蚀次数
  1914. int h1 = 0;
  1915. Mat temp = new Mat();
  1916. //开始
  1917. while (Cv2.CountNonZero(erode) > 0)
  1918. {
  1919. //寻找并标记区域个数
  1920. Mat labelMat = new Mat();
  1921. Mat stats = new Mat();
  1922. Mat centroids = new Mat();
  1923. int num = Cv2.ConnectedComponentsWithStats(erode, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  1924. //进行腐蚀
  1925. temp = erode.Erode(element, null, 1);
  1926. //跳出循环的条件
  1927. int count = Cv2.CountNonZero(temp);
  1928. //循环质心,和腐蚀后的图片进行比较,如果腐蚀后的图片质心为黑色了,那说明被腐蚀掉了,则在下面需要被还原回来
  1929. for (int h = 1; h < centroids.Height; h++)
  1930. {
  1931. double a = centroids.At<double>(h, 0);
  1932. double b = centroids.At<double>(h, 1);
  1933. OpenCvSharp.Point point = new OpenCvSharp.Point(a, b);
  1934. //计算每个stats范围内的像素和是否为0
  1935. int x = stats.At<int>(h, 0);
  1936. int y = stats.At<int>(h, 1);
  1937. int width = stats.At<int>(h, 2);
  1938. int height = stats.At<int>(h, 3);
  1939. System.Console.WriteLine("x:" + x + " y:" + y);
  1940. Rect roi1 = new Rect(x, y, width, height);
  1941. Mat ImageROI1 = new Mat(temp, roi1);
  1942. int cc1 = Cv2.CountNonZero(ImageROI1);
  1943. //代表区域已经消失了,需要还原回来
  1944. if (cc1 == 0)
  1945. {
  1946. Rect roi = new Rect(x, y, width, height);
  1947. Mat ImageROI = new Mat(erode, roi);
  1948. Rect rect = new Rect(x, y, width, height);
  1949. Mat pos = new Mat(temp, rect);
  1950. ImageROI.CopyTo(pos);
  1951. }
  1952. }
  1953. if (h1 == paramCount && paramCount > 0) break;
  1954. temp.CopyTo(erode);
  1955. h1++;
  1956. if (count == 0)
  1957. {
  1958. break;
  1959. }
  1960. }
  1961. Mat fffff = new Mat();
  1962. Mat labels = new Mat();
  1963. Cv2.DistanceTransformWithLabels(~temp, fffff, labels, DistanceTypes.L1, DistanceMaskSize.Precise);
  1964. //labels.ConvertTo(labels, MatType.CV_8UC3);
  1965. //找到轮廓
  1966. OpenCvSharp.Point[][] contours;
  1967. HierarchyIndex[] hierachy;
  1968. Cv2.FindContours(labels, out contours, out hierachy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone);
  1969. Mat lk = new Mat(labels.Size(), MatType.CV_8UC1, Scalar.All(255));
  1970. Cv2.DrawContours(lk, contours, -1, Scalar.All(0), 1, LineTypes.Link8, hierachy);
  1971. //Cv2.MorphologyEx(img, img, MorphTypes.Open, element, null, 1);
  1972. //Cv2.Dilate(img, img, element, null, 1);
  1973. System.Drawing.Color color = System.Drawing.Color.FromArgb(model.color);
  1974. for (int h = 0; h < lab1Img.Height; h++)
  1975. {
  1976. for (int w = 0; w < lab1Img.Width; w++)
  1977. {
  1978. if (lab1Img.At<byte>(h, w) == 0)
  1979. lab1Img.Set<Vec3b>(h, w, new Vec3b(color.B, color.G, color.R));
  1980. /*if (lab1Img.At<byte>(h, w) == 0 || lk.At<byte>(h, w) == 0)
  1981. lab1Img.Set<Vec4b>(h, w, new Vec4b(color.B, color.G, color.R, 255));
  1982. else
  1983. lab1Img.Set<Vec4b>(h, w, new Vec4b(0, 0, 0, 0));*/
  1984. }
  1985. }
  1986. for (int h = 0; h < lk.Height; h++)
  1987. {
  1988. for (int w = 0; w < lk.Width; w++)
  1989. {
  1990. if (lk.At<byte>(h, w) == 0)
  1991. lab1Img.Set<Vec3b>(h, w, new Vec3b(color.B, color.G, color.R));
  1992. }
  1993. }
  1994. Cv2.Erode(lab1Img, lab1Img, null, null, 1);
  1995. Cv2.Dilate(lab1Img, lab1Img, null, null, 1);
  1996. //Cv2.ImShow("dddd", lk);
  1997. //Cv2.ImShow("粗化操作1", lab1Img);
  1998. return lab1Img;
  1999. }
  2000. #endregion
  2001. }
  2002. public struct Int16DoubleWithValue : IComparable<Int16DoubleWithValue>
  2003. {
  2004. public int O;
  2005. public float V;
  2006. public Int16DoubleWithValue(int offset, float value)
  2007. {
  2008. O = offset;
  2009. V = value;
  2010. }
  2011. public int CompareTo(Int16DoubleWithValue other)
  2012. {
  2013. return this.V.CompareTo(other.V);
  2014. }
  2015. }
  2016. public class BitMap2d
  2017. {
  2018. public float[] data;
  2019. public int width;
  2020. public int height;
  2021. /// <summary>
  2022. /// 初始化操作对象
  2023. /// </summary>
  2024. /// <param name="width"></param>
  2025. /// <param name="height"></param>
  2026. /// <param name="v">初始值</param>
  2027. public BitMap2d(int width, int height, float v)
  2028. {
  2029. this.width = width;
  2030. this.height = height;
  2031. data = new float[width * height];
  2032. for (int i = 0; i < width * height; i++)
  2033. data[i] = v;
  2034. }
  2035. /// <summary>
  2036. /// 根据mat初始化
  2037. /// </summary>
  2038. /// <param name="mat">初始EDM对象</param>
  2039. public unsafe BitMap2d(Mat mat)
  2040. {
  2041. this.width = mat.Width;
  2042. this.height = mat.Height;
  2043. data = new float[width * height];
  2044. mat.ForEachAsFloat(FunctionForEachAsFloat);
  2045. }
  2046. private unsafe void FunctionForEachAsFloat(float* value, int* position)
  2047. {
  2048. data[position[0] * width + position[1]] = *value;
  2049. }
  2050. public void SetPixel(int x, int y, byte v)
  2051. {
  2052. data[x + y * width] = v;
  2053. }
  2054. public float GetPixel(int x, int y)
  2055. {
  2056. return data[x + y * width];
  2057. }
  2058. public void SetPixel(int offset, byte v)
  2059. {
  2060. data[offset] = v;
  2061. }
  2062. public float GetPixel(int offset)
  2063. {
  2064. return data[offset];
  2065. }
  2066. public System.Drawing.Bitmap MakeBmp()
  2067. {
  2068. float min = float.MaxValue;
  2069. float max = float.MinValue;
  2070. for (int i = 0; i < width; i++)
  2071. {
  2072. for (int j = 0; j < height; j++)
  2073. {
  2074. float r = this.GetPixel(i, j);
  2075. if (r > max)
  2076. max = r;
  2077. if (r < min)
  2078. min = r;
  2079. }
  2080. }
  2081. float delta = max - min;
  2082. System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(this.width, this.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  2083. for (int i = 0; i < width; i++)
  2084. {
  2085. for (int j = 0; j < height; j++)
  2086. {
  2087. float r = this.GetPixel(i, j);
  2088. int b = 255 - (int)(255 * (r - min) / delta);
  2089. System.Drawing.Color c = System.Drawing.Color.FromArgb((byte)b, (byte)b, (byte)b);
  2090. bmp.SetPixel(i, j, c);
  2091. }
  2092. }
  2093. return bmp;
  2094. }
  2095. }
  2096. public class MaximunFinder
  2097. {
  2098. BitMap2d bmp;
  2099. int width;
  2100. int height;
  2101. public MaximunFinder(BitMap2d bmp)
  2102. {
  2103. this.bmp = bmp;
  2104. this.width = bmp.width;
  2105. this.height = bmp.height;
  2106. }
  2107. public List<Int16DoubleWithValue> FindMaxima()
  2108. {
  2109. List<Int16DoubleWithValue> list = new List<Int16DoubleWithValue>();
  2110. int offset = 0;
  2111. for (int j = 0; j < height; j++)
  2112. {
  2113. for (int i = 0; i < width; i++, offset++)
  2114. {
  2115. if (IsMaxima(i, j, offset))
  2116. {
  2117. list.Add(new Int16DoubleWithValue(offset, bmp.GetPixel(offset)));
  2118. }
  2119. }
  2120. }
  2121. list.Sort();
  2122. return list;
  2123. }
  2124. private bool IsMaxima(int i, int j, int offset)
  2125. {
  2126. float v = bmp.GetPixel(offset);
  2127. if (v == 0) return false;
  2128. bool b1 = v >= bmp.GetPixel(Math.Max(0, i - 1), Math.Max(0, j - 1));
  2129. bool b2 = v >= bmp.GetPixel(i, Math.Max(0, j - 1));
  2130. bool b3 = v >= bmp.GetPixel(Math.Min(width - 1, i + 1), Math.Max(0, j - 1));
  2131. bool b4 = v >= bmp.GetPixel(Math.Max(0, i - 1), j);
  2132. bool b5 = v >= bmp.GetPixel(Math.Min(width - 1, i + 1), j);
  2133. bool b6 = v >= bmp.GetPixel(Math.Max(0, i - 1), Math.Min(height - 1, j + 1));
  2134. bool b7 = v >= bmp.GetPixel(i, Math.Min(height - 1, j + 1));
  2135. bool b8 = v >= bmp.GetPixel(Math.Min(width - 1, i + 1), Math.Min(height - 1, j + 1));
  2136. return b1 && b2 && b3 && b4 && b5 && b6 && b7 && b8 && (v > 0);
  2137. }
  2138. }
  2139. }