Battery.cs 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245
  1. using OpenCvSharp;
  2. using PaintDotNet.Adjust.BaseImage;
  3. using PaintDotNet.Base;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Drawing;
  7. using System.Linq;
  8. namespace PaintDotNet.Adjust
  9. {
  10. public unsafe class Battery
  11. {
  12. /// <summary>
  13. /// 全局中间变量
  14. /// 不带视场的时候就是原图/二值图
  15. /// 带视场的时候就是原图/二值图
  16. /// </summary>
  17. public static Mat temp, temp_view;
  18. /// <summary>
  19. /// 用来存储透明图
  20. /// </summary>
  21. public static Mat alpha;
  22. /// <summary>
  23. /// 1个颜色区间还是2个
  24. /// </summary>
  25. public static int colorInterval;
  26. /// <summary>
  27. /// 1个颜色区间时的起始值
  28. /// </summary>
  29. public static int colorOneStart;
  30. /// <summary>
  31. /// 1个颜色区间时的结止值
  32. /// </summary>
  33. public static int colorOneEnd;
  34. /// <summary>
  35. /// 2个颜色区间时的第1个区间的起始值
  36. /// </summary>
  37. public static int colorTwoStart = 0;
  38. /// <summary>
  39. /// 2个颜色区间时的第1个区间的结止值
  40. /// </summary>
  41. public static int colorTwoEnd = 0;
  42. /// <summary>
  43. /// 2个颜色区间时的第2个区间的起始值
  44. /// </summary>
  45. public static int colorThreeStart = 0;
  46. /// <summary>
  47. /// 2个颜色区间时的第2个区间的起始值
  48. /// </summary>
  49. public static int colorThreeEnd = 0;
  50. //碎屑删除面积起
  51. public static int debrisAreaStart = 0;
  52. //图片类型,1同心圆孔隙2单晶3二次球与单晶
  53. public static int imageType = 1;
  54. //碎屑删除面积止
  55. public static int debrisAreaEnd = 0;
  56. /// <summary>
  57. /// 默认相颜色
  58. /// </summary>
  59. public static Vec4b vec4B = new Vec4b(255, 0, 0, 255);
  60. /// <summary>
  61. /// 默认相颜色
  62. /// </summary>
  63. public static Vec4b vec4Bw = new Vec4b(0, 0, 0, 0);
  64. /// <summary>
  65. /// 新增的参数,用于FloodFill方法
  66. /// </summary>
  67. public static Rect rect;
  68. /// <summary>
  69. /// 各个连通域的代表点
  70. /// </summary>
  71. public static List<OpenCvSharp.Point> points;
  72. /// <summary>
  73. /// 用来记录需要删除的连通区域的编号
  74. /// </summary>
  75. public static Dictionary<int, int> keyValuePairs = new Dictionary<int, int>();
  76. /// <summary>
  77. /// 用来记录选择的连通区域的编号
  78. /// </summary>
  79. public static Dictionary<int, int> keyValueSel = new Dictionary<int, int>();
  80. public static Mat rgb_ap;
  81. public static Mat temp_ap;
  82. //碎屑删除面积止
  83. public static int poArea = 0;
  84. //孔隙同心圆面积
  85. public static List<int> poAreaList = new List<int>() { };
  86. //孔隙信息,孔隙的x,y,width,height,area,id
  87. public static List<List<int>> poList = new List<List<int>> { };
  88. //开裂球历史记录
  89. public static List<List<int>> poListHis = new List<List<int>> { };
  90. //同心圆数
  91. public static int circleCount = 0;
  92. //最大轮廓
  93. public static OpenCvSharp.Point[] maxContour = new OpenCvSharp.Point[] { };
  94. //同心圆半径
  95. public static int CircleR = 0;
  96. //同心圆半径
  97. public static OpenCvSharp.Point center = new OpenCvSharp.Point();
  98. //删除孔隙
  99. public static List<PointF> delPointFs = new List<PointF>();
  100. //选择孔隙
  101. public static int selPointFs = -1;
  102. //记录联通区域
  103. public static Mat labelMatForSel = new Mat();
  104. //记录新增联通区域
  105. public static OpenCvSharp.Point[][] labelMatForSelAdd;
  106. //记录联通区域数量
  107. public static int fieldsCount = 0;
  108. //处理后的mat
  109. public static Mat retMat = new Mat();
  110. //同心圆颜色列表
  111. public static List<Scalar> colorList = new List<Scalar>() { new Scalar(0, 0, 255, 255), new Scalar(0, 255, 0, 255), new Scalar(0, 0, 139, 255), new Scalar(128, 0, 128, 255), new Scalar(255, 160, 122, 255) };
  112. public static List<Vec4b> vec4BList = new List<Vec4b>() { new Vec4b(0, 0, 255, 255), new Vec4b(0, 255, 0, 255), new Vec4b(0, 0, 139, 255), new Vec4b(128, 0, 128, 255), new Vec4b(255, 160, 122, 255) };
  113. //所有点
  114. public static Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
  115. //轮廓面积
  116. public static int maxArea = 0;
  117. //图像高度
  118. public static int imageHight = 0;
  119. //图像高度
  120. public static int imageWidth = 0;
  121. //二次球点
  122. public static List<PointF> BallPointFs = new List<PointF>();
  123. //二次球单晶点
  124. public static List<PointF> CrystalPointFs = new List<PointF>();
  125. //二次球轮廓
  126. public static List<List<PointF>> CrystalLunkuo = new List<List<PointF>>();
  127. //二次球模糊系数
  128. public static int BlurSiaze = 15;
  129. //二次球阈值
  130. public static int param2 = 24;
  131. //二次球最小半径
  132. public static int minRadius = 33;
  133. //二次球最大半径
  134. public static int maxRadius = 52;
  135. //去边界
  136. public static int boundary = 0;
  137. //去底边
  138. public static double borderBottom = 0;
  139. //忽略开裂球
  140. public static List<PointF> CreackBallPointFs = new List<PointF>();
  141. //设为开裂球
  142. public static List<PointF> CreackBallPointFsK = new List<PointF>();
  143. //设为普通球
  144. public static List<PointF> CreackBallPointFsP = new List<PointF>();
  145. //小颗粒
  146. public static double pointsize = 0.1;
  147. //标尺
  148. public static double Micron = 0.01;
  149. //边缘
  150. public static int border = 1;
  151. //长宽比
  152. public static double HW = 1;
  153. //面积率
  154. public static double AreaRatio = 1;
  155. //添加单晶
  156. public static List<List<OpenCvSharp.Point>> AddPontins = new List<List<OpenCvSharp.Point>>();
  157. //连通域集合
  158. static List<List<OpenCvSharp.Point>> AllFields = new List<List<OpenCvSharp.Point>>();
  159. //二次球测量区域
  160. public static List<OpenCvSharp.Point> Contour = new List<OpenCvSharp.Point>();
  161. //手动画同心圆半径和颜色
  162. public static Dictionary<int, Color> ListRadiusColor = new Dictionary<int, Color>();
  163. //是否画测距
  164. public static bool isDis = false;
  165. //是否画矩形
  166. public static bool isJu = false;
  167. #region 无视场 二值提取
  168. /// <summary>
  169. /// 二值操作-二值提取-无视场
  170. /// </summary>
  171. /// <param name="src">源图像</param>
  172. /// <param name="lists">参数集合</param>
  173. /// <returns></returns>
  174. public static Mat ImageBinaryExtraction(Mat src, List<Args> lists, bool findContours = false)
  175. {
  176. //以下是参数信息---------------------
  177. ///1个颜色区间还是2个
  178. colorInterval = 1;
  179. //第一个二值区间
  180. colorOneStart = 0;
  181. colorOneEnd = 0;
  182. //第二个二值区间
  183. colorTwoStart = 0;
  184. colorTwoEnd = 0;
  185. //第三个二值区间
  186. colorThreeStart = 0;
  187. colorThreeEnd = 0;
  188. //处理细节
  189. //删除边界对象
  190. bool deleteBoundaryObject = false;
  191. //孔洞填充
  192. bool holeFilling = false;
  193. //碎屑删除
  194. bool debrisRemoval = false;
  195. //碎屑删除面积起
  196. debrisAreaStart = 0;
  197. //碎屑删除面积止
  198. debrisAreaEnd = 0;
  199. //二值样式
  200. //1实心 2边线
  201. int binaryStyle = 0;
  202. //相颜色
  203. Color phaseColor = Color.Red;
  204. //目标选择
  205. int targetSelection = 1;
  206. for (int i = 0; i < lists.Count; i++)
  207. {
  208. Args args = lists[i];
  209. switch (args.Key)
  210. {
  211. case "colorInterval":
  212. {
  213. if (args.Value is Boolean)
  214. colorInterval = (Boolean)args.Value ? 2 : 1;
  215. else
  216. colorInterval = (int)args.Value;
  217. }
  218. break;
  219. case "scope1":
  220. colorOneStart = (int)((List<double>)args.Value)[0];
  221. colorOneEnd = (int)((List<double>)args.Value)[1];
  222. break;
  223. case "scope2":
  224. colorTwoStart = (int)((List<double>)args.Value)[0];
  225. colorTwoEnd = (int)((List<double>)args.Value)[1];
  226. break;
  227. case "scope3":
  228. colorThreeStart = (int)((List<double>)args.Value)[0];
  229. colorThreeEnd = (int)((List<double>)args.Value)[1];
  230. break;
  231. case "deleteBoundaryObject":
  232. deleteBoundaryObject = (bool)args.Value;
  233. break;
  234. case "holeFilling":
  235. holeFilling = (bool)args.Value;
  236. break;
  237. case "debrisRemoval":
  238. debrisRemoval = (bool)args.Value;
  239. break;
  240. case "binaryStyle":
  241. binaryStyle = (int)args.Value;
  242. break;
  243. case "phaseColor":
  244. phaseColor = Color.FromArgb((int)args.Value);
  245. break;
  246. case "targetSelection":
  247. targetSelection = (int)args.Value;
  248. break;
  249. case "scope4":
  250. debrisAreaStart = (int)((List<double>)args.Value)[0];
  251. debrisAreaEnd = (int)((List<double>)args.Value)[1];
  252. findContours = true;
  253. break;
  254. case "imageType":
  255. imageType = (int)args.Value;
  256. break;
  257. default:
  258. break;
  259. }
  260. }
  261. if (phaseColor.A < 1)//#21321
  262. phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
  263. vec4B.Item0 = phaseColor.B;
  264. vec4B.Item1 = phaseColor.G;
  265. vec4B.Item2 = phaseColor.R;
  266. vec4B.Item3 = phaseColor.A;
  267. //中值滤波
  268. //Cv2.MedianBlur(src, src, 3);
  269. //二值提取
  270. src = Binarization(src);
  271. //碎屑删除,参考冈萨雷斯,414,9.5.3,连通分量提取
  272. // if (debrisRemoval && debrisAreaEnd > 0)
  273. src = DebrisRemoval_New(src);
  274. //实心/边线,参考冈萨雷斯,412,9.5.1,边界提取
  275. Cv2.Erode(src, temp, null);
  276. src = src - temp;
  277. src = BaseTools.MergeMatFromMatArr(src, vec4B);
  278. return src;
  279. }
  280. /// <summary>
  281. /// 前驱截面
  282. /// </summary>
  283. /// <param name="src">源图像</param>
  284. /// <param name="lists">参数集合</param>
  285. /// <returns></returns>
  286. public static Mat ImageBinaryExtraction(Mat src, List<Args> lists, out List<List<int>> data, bool findContours = false)
  287. {
  288. //以下是参数信息---------------------
  289. ///1个颜色区间还是2个
  290. colorInterval = 1;
  291. //第一个二值区间
  292. colorOneStart = 0;
  293. colorOneEnd = 0;
  294. //第二个二值区间
  295. colorTwoStart = 0;
  296. colorTwoEnd = 0;
  297. //第三个二值区间
  298. colorThreeStart = 0;
  299. colorThreeEnd = 0;
  300. boundary = 0;
  301. //处理细节
  302. //删除边界对象
  303. bool deleteBoundaryObject = false;
  304. //孔洞填充
  305. bool holeFilling = false;
  306. //碎屑删除
  307. bool debrisRemoval = false;
  308. //碎屑删除面积起
  309. debrisAreaStart = 0;
  310. //碎屑删除面积止
  311. debrisAreaEnd = 0;
  312. //二值样式
  313. //1实心 2边线
  314. int binaryStyle = 0;
  315. //相颜色
  316. Color phaseColor = Color.Red;
  317. //目标选择
  318. int targetSelection = 1;
  319. for (int i = 0; i < lists.Count; i++)
  320. {
  321. Args args = lists[i];
  322. switch (args.Key)
  323. {
  324. case "colorInterval":
  325. {
  326. if (args.Value is Boolean)
  327. colorInterval = (Boolean)args.Value ? 2 : 1;
  328. else
  329. colorInterval = (int)args.Value;
  330. }
  331. break;
  332. case "scope1":
  333. colorOneStart = (int)((List<double>)args.Value)[0];
  334. colorOneEnd = (int)((List<double>)args.Value)[1];
  335. break;
  336. case "scope2":
  337. colorTwoStart = (int)((List<double>)args.Value)[0];
  338. colorTwoEnd = (int)((List<double>)args.Value)[1];
  339. break;
  340. case "scope3":
  341. colorThreeStart = (int)((List<double>)args.Value)[0];
  342. colorThreeEnd = (int)((List<double>)args.Value)[1];
  343. break;
  344. case "deleteBoundaryObject":
  345. deleteBoundaryObject = (bool)args.Value;
  346. break;
  347. case "holeFilling":
  348. holeFilling = (bool)args.Value;
  349. break;
  350. case "debrisRemoval":
  351. debrisRemoval = (bool)args.Value;
  352. break;
  353. case "binaryStyle":
  354. binaryStyle = (int)args.Value;
  355. break;
  356. case "phaseColor":
  357. phaseColor = Color.FromArgb((int)args.Value);
  358. break;
  359. case "targetSelection":
  360. targetSelection = (int)args.Value;
  361. break;
  362. case "scope4":
  363. debrisAreaStart = (int)((List<double>)args.Value)[0];
  364. debrisAreaEnd = (int)((List<double>)args.Value)[1];
  365. findContours = true;
  366. break;
  367. case "CircleCount":
  368. circleCount = (int)args.Value;
  369. break;
  370. case "maxContour":
  371. maxContour = (OpenCvSharp.Point[])args.Value;
  372. break;
  373. case "CircleR":
  374. CircleR = (int)args.Value;
  375. break;
  376. case "Center":
  377. center = (OpenCvSharp.Point)args.Value;
  378. break;
  379. case "DelPointFs":
  380. delPointFs = (List<PointF>)args.Value;
  381. break;
  382. case "imageType":
  383. imageType = (int)args.Value;
  384. break;
  385. case "SelPointFs":
  386. selPointFs = (int)args.Value;
  387. break;
  388. case "imageTypes":
  389. imageType = (int)args.Value;
  390. break;
  391. case "BlurSiaze":
  392. BlurSiaze = (int)args.Value;
  393. break;
  394. case "param2":
  395. param2 = (int)args.Value;
  396. break;
  397. case "minRadius":
  398. minRadius = (int)args.Value;
  399. break;
  400. case "maxRadius":
  401. maxRadius = (int)args.Value;
  402. break;
  403. case "boundary":
  404. boundary = (int)args.Value;
  405. break;
  406. case "BallPointFs":
  407. BallPointFs = (List<PointF>)args.Value;
  408. break;
  409. case "CrystalPointFs":
  410. CrystalPointFs = (List<PointF>)args.Value;
  411. break;
  412. case "CrystalLunkuo":
  413. CrystalLunkuo = (List<List<PointF>>)args.Value;
  414. break;
  415. case "AddPontins":
  416. AddPontins = (List<List<OpenCvSharp.Point>>)args.Value;
  417. break;
  418. case "pointsize":
  419. pointsize = (double)args.Value;
  420. break;
  421. case "Micron":
  422. Micron = (double)args.Value;
  423. break;
  424. case "border":
  425. border = (int)args.Value;
  426. break;
  427. case "HW":
  428. HW = (double)args.Value;
  429. break;
  430. case "AreaRatio":
  431. AreaRatio = (double)args.Value;
  432. break;
  433. case "Contour":
  434. Contour = (List<OpenCvSharp.Point>)args.Value;
  435. break;
  436. case "ListRadiusColor":
  437. ListRadiusColor = (Dictionary<int, Color>)args.Value;
  438. break;
  439. case "isDis":
  440. isDis = (bool)args.Value;
  441. break;
  442. case "isJu":
  443. isJu = (bool)args.Value;
  444. break;
  445. case "borderBottom":
  446. borderBottom = (int)args.Value;
  447. break;
  448. default:
  449. break;
  450. }
  451. }
  452. if (phaseColor.A < 1)//#21321
  453. phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
  454. temp_view = src.Clone();
  455. vec4B.Item0 = phaseColor.B;
  456. vec4B.Item1 = phaseColor.G;
  457. vec4B.Item2 = phaseColor.R;
  458. vec4B.Item3 = phaseColor.A;
  459. poArea = 0;
  460. maxArea = 0;
  461. poList.Clear();
  462. poAreaList = new List<int>() { };
  463. data = poList;
  464. imageHight = src.Rows;
  465. imageWidth = src.Cols;
  466. if (imageType == 1)
  467. {
  468. if (selPointFs != -1 && retMat != null)
  469. {
  470. Mat used = retMat.Clone();
  471. keyValueSel.Add(selPointFs, 1);
  472. src = SelectPoint(used);
  473. }
  474. else
  475. {
  476. if (ListRadiusColor.Count > 0)
  477. {
  478. for (int i = 0; i < ListRadiusColor.Count; i++)
  479. {
  480. poAreaList.Add(0);
  481. }
  482. ListRadiusColor = ListRadiusColor.OrderByDescending(c => c.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
  483. }
  484. else if (circleCount > 0)
  485. {
  486. for (int i = 0; i < circleCount; i++)
  487. {
  488. poAreaList.Add(0);
  489. }
  490. }
  491. //二值提取
  492. src = Binarization(src);
  493. //using (new Window("InputImage", WindowMode.Normal, src))
  494. //{
  495. // Cv2.WaitKey(0);
  496. //}
  497. //去掉过小孔隙,计算孔隙面积
  498. src = DebrisRemoval_New(src);
  499. //using (new Window("InputImage1", WindowMode.Normal, src))
  500. //{
  501. // Cv2.WaitKey(0);
  502. //}
  503. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { maxContour };
  504. Cv2.DrawContours(src, contours, 0, new Scalar(255, 144, 30, 255), 2);
  505. if (circleCount > 1)
  506. {
  507. for (int i = 0; i < circleCount; i++)
  508. {
  509. Cv2.Circle(src, center, Convert.ToInt32(CircleR * (i + 1)), colorList[i], 2);
  510. }
  511. }
  512. poAreaList.Add(poArea);
  513. poAreaList.Add(maxArea);
  514. data.Insert(0, poAreaList);
  515. retMat = src.Clone();
  516. ListRadiusColor.Clear();
  517. }
  518. keyValueSel.Clear();
  519. selPointFs = -1;
  520. }
  521. else if (imageType == 2)
  522. {
  523. if (selPointFs != -1 && retMat != null)
  524. {
  525. Mat used = retMat.Clone();
  526. keyValueSel.Add(selPointFs, 1);
  527. src = SelectPoint(used);
  528. keyValueSel.Clear();
  529. selPointFs = -1;
  530. }
  531. else
  532. {
  533. src = WhirtBinarization(src);
  534. Mat srcGray = src.CvtColor(ColorConversionCodes.BGRA2BGR);
  535. Mat dst = new Mat();
  536. //双边滤波
  537. Cv2.BilateralFilter(srcGray, dst, 21, 132, 181);
  538. Mat canny = new Mat();
  539. Mat gray = new Mat(); Mat andmet = new Mat();
  540. Cv2.GaussianBlur(dst, canny, new OpenCvSharp.Size(3, 3), 40);
  541. Cv2.CvtColor(canny, gray, ColorConversionCodes.BGR2GRAY);
  542. andmet = gray.Clone();
  543. Cv2.Canny(gray, gray, 100, 100);
  544. Cv2.Dilate(gray, gray, null);
  545. Cv2.Dilate(gray, gray, null);
  546. Cv2.Erode(gray, gray, null);
  547. Cv2.GaussianBlur(gray, gray, new OpenCvSharp.Size(3, 3), 10);
  548. gray = DebrisRemoval_CrystCanny(gray);
  549. Mat notmet = gray.Clone();
  550. Cv2.BitwiseNot(notmet, notmet);
  551. Cv2.Threshold(andmet, andmet, colorOneStart, colorOneEnd, ThresholdTypes.Binary);
  552. for (int i = 0; i < 4; i++)
  553. {
  554. Cv2.Dilate(andmet, andmet, null);
  555. }
  556. for (int i = 0; i < 4; i++)
  557. {
  558. Cv2.Erode(andmet, andmet, null);
  559. }
  560. Cv2.BitwiseAnd(notmet, andmet, andmet);
  561. Cv2.MedianBlur(andmet, andmet, 9);
  562. //二值提取
  563. src = Binarization(andmet);
  564. }
  565. }
  566. else if (imageType == 12)
  567. {
  568. if (selPointFs != -1 && retMat != null)
  569. {
  570. Mat used = retMat.Clone();
  571. if (selPointFs >= fieldsCount)
  572. {
  573. Cv2.DrawContours(used, labelMatForSelAdd, selPointFs- fieldsCount, new Scalar(255, 255, vec4B.Item2, vec4B.Item3), -1);
  574. src= used.Clone();
  575. }
  576. else
  577. {
  578. keyValueSel.Add(selPointFs, 1);
  579. src = SelectPoint(used);
  580. keyValueSel.Clear();
  581. }
  582. selPointFs = -1;
  583. }
  584. else
  585. {
  586. src = DebrisRemoval_Cryst(src);
  587. retMat = src.Clone();
  588. }
  589. }
  590. else if (imageType == 3)
  591. {
  592. src = WhirtBinarization(src);
  593. List<int> circleList = new List<int>();
  594. List<int> circleAreaList = new List<int>();
  595. Mat dst = new Mat();
  596. Mat m1 = new Mat();
  597. Cv2.MedianBlur(src, m1, BlurSiaze); // ksize必须大于1且是奇数
  598. //2:转为灰度图像
  599. Mat hb = new Mat(src.Rows, src.Cols, MatType.CV_8UC1);
  600. Mat m2 = m1.Clone();
  601. Cv2.CvtColor(m1, m2, ColorConversionCodes.BGR2GRAY);
  602. //3:霍夫圆检测:使用霍夫变换查找灰度图像中的圆。
  603. /*
  604. * 参数:
  605. * 1:输入参数: 8位、单通道、灰度输入图像
  606. * 2:实现方法:目前,唯一的实现方法是HoughCirclesMethod.Gradient
  607. * 3: dp :累加器分辨率与图像分辨率的反比。默认=1
  608. * 4:minDist: 检测到的圆的中心之间的最小距离。(最短距离-可以分辨是两个圆的,否则认为是同心圆- src_gray.rows/8)
  609. * 5:param1: 第一个方法特定的参数。[默认值是100] canny边缘检测阈值低
  610. * 6:param2: 第二个方法特定于参数。[默认值是100] 中心点累加器阈值 – 候选圆心
  611. * 7:minRadius: 最小半径
  612. * 8:maxRadius: 最大半径
  613. *
  614. */
  615. CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 80, 70, param2, minRadius, maxRadius);
  616. src.CopyTo(dst);
  617. int one = 0;
  618. int two = 0;
  619. int three = 0;
  620. int four = 0;
  621. double oneA = 0;
  622. double twoA = 0;
  623. double threeA = 0;
  624. double fourA = 0;
  625. int helfx = src.Cols / 2;
  626. int helfy = (src.Rows - 70) / 2;
  627. List<int> delKey = new List<int>();
  628. List<List<PointF>> trmpList = new List<List<PointF>>();
  629. CrystalLunkuo.ForEach(s => trmpList.Add(s));
  630. //大圆
  631. for (int i = 0; i < cs.Length; i++)
  632. {
  633. if (CrystalPointFs.Count > 0)
  634. {
  635. int isCrystal = 0;
  636. foreach (var item in CrystalPointFs)
  637. {
  638. Point2f pin = new Point2f(item.X, item.Y);
  639. double distanc = pin.DistanceTo(cs[i].Center);
  640. if (distanc < cs[i].Radius)
  641. {
  642. isCrystal = 1;
  643. break;
  644. }
  645. }
  646. if (isCrystal == 1)
  647. {
  648. delKey.Add(i);
  649. continue;
  650. }
  651. }
  652. //手画圆轮廓
  653. if (trmpList.Count > 0)
  654. {
  655. int del = -1;
  656. for (int lk = 0; lk < trmpList.Count; lk++)
  657. {
  658. List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
  659. trmpList[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
  660. Point2f newcenter = new Point2f();
  661. float newR = 0;
  662. Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
  663. if (newcenter.DistanceTo(cs[i].Center) < cs[i].Radius)
  664. {
  665. cs[i].Center = newcenter;
  666. cs[i].Radius = newR;
  667. del = lk;
  668. break;
  669. }
  670. }
  671. if (del >= 0)
  672. {
  673. trmpList.RemoveAt(del);
  674. }
  675. }
  676. double area = Math.PI * cs[i].Radius * cs[i].Radius;
  677. if ((int)cs[i].Center.X < helfx && (int)cs[i].Center.Y < helfy)
  678. {
  679. one++;
  680. oneA = oneA + area;
  681. }
  682. if ((int)cs[i].Center.X < helfx && (int)cs[i].Center.Y > helfy)
  683. {
  684. two++;
  685. twoA = twoA + area;
  686. }
  687. if ((int)cs[i].Center.X > helfx && (int)cs[i].Center.Y < helfy)
  688. {
  689. three++;
  690. threeA = threeA + area;
  691. }
  692. if ((int)cs[i].Center.X > helfx && (int)cs[i].Center.Y > helfy)
  693. {
  694. four++;
  695. fourA = fourA + area;
  696. }
  697. //画圆
  698. Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, new Scalar(0, 0, 0), -1, LineTypes.AntiAlias);
  699. //加强圆心显示
  700. Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 0), 2, LineTypes.AntiAlias);
  701. //画圆
  702. Cv2.Circle(hb, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, new Scalar(255), -1, LineTypes.AntiAlias);
  703. }
  704. //手画圆轮廓
  705. if (trmpList.Count > 0)
  706. {
  707. for (int lk = 0; lk < trmpList.Count; lk++)
  708. {
  709. List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
  710. trmpList[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
  711. Point2f newcenter = new Point2f();
  712. float newR = 0;
  713. Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
  714. Cv2.Circle(dst, (int)newcenter.X, (int)newcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  715. //加强圆心显示
  716. Cv2.Circle(dst, (int)newcenter.X, (int)newcenter.Y, (int)newR, new Scalar(0, 0, 0), -1, LineTypes.AntiAlias);
  717. //画圆
  718. Cv2.Circle(hb, (int)newcenter.X, (int)newcenter.Y, (int)newR, new Scalar(255), -1, LineTypes.AntiAlias);
  719. double CircleArea = Math.PI * newR * newR;
  720. if ((int)newcenter.X < helfx && newcenter.Y < helfy)
  721. {
  722. one++;
  723. oneA = oneA + CircleArea;
  724. }
  725. if ((int)newcenter.X < helfx && (int)newcenter.Y > helfy)
  726. {
  727. two++;
  728. twoA = twoA + CircleArea;
  729. }
  730. if ((int)newcenter.X > helfx && (int)newcenter.Y < helfy)
  731. {
  732. three++;
  733. threeA = threeA + CircleArea;
  734. }
  735. if ((int)newcenter.X > helfx && (int)newcenter.Y > helfy)
  736. {
  737. four++;
  738. fourA = fourA + CircleArea;
  739. }
  740. }
  741. }
  742. Mat oldDst = dst.Clone();
  743. if (boundary > 0)
  744. {
  745. //去边界
  746. dst = BallCutBottor(dst);
  747. //左上
  748. Rect rectL1 = new Rect(0, 0, helfx, helfy);
  749. Mat MatL1 = new Mat(hb, rectL1);
  750. int areaAllL1 = MatL1.CountNonZero();
  751. Rect rectL1Cut = new Rect(boundary, boundary, helfx - boundary, helfy - boundary);
  752. Mat MatL1Cut = new Mat(hb, rectL1Cut);
  753. int areaCut = MatL1Cut.CountNonZero();
  754. int oneCut = areaAllL1 - areaCut;
  755. oneA = oneA - oneCut;
  756. //左下
  757. Rect rectL2 = new Rect(0, helfy, helfx, helfy);
  758. Mat MatL2 = new Mat(hb, rectL2);
  759. int areaAllL2 = MatL2.CountNonZero();
  760. Rect rectL2Cut = new Rect(boundary, helfy, helfx - boundary, helfy - boundary);
  761. Mat MatL2Cut = new Mat(hb, rectL2Cut);
  762. int areaCutL2 = MatL2Cut.CountNonZero();
  763. int oneCutL2 = areaAllL2 - areaCutL2;
  764. twoA = twoA - oneCutL2;
  765. //右上
  766. Rect rectR1 = new Rect(helfx, 0, helfx, helfy);
  767. Mat MatR1 = new Mat(hb, rectR1);
  768. int areaAllR1 = MatR1.CountNonZero();
  769. Rect rectR1Cut = new Rect(helfx, boundary, helfx - boundary, helfy - boundary);
  770. Mat MatR1Cut = new Mat(hb, rectR1Cut);
  771. int areaCutR1 = MatR1Cut.CountNonZero();
  772. int oneCutR1 = areaAllR1 - areaCutR1;
  773. threeA = threeA - oneCutR1;
  774. //右下
  775. Rect rectR2 = new Rect(helfx, helfy, helfx, helfy);
  776. Mat MatR2 = new Mat(hb, rectR2);
  777. int areaAllR2 = MatR2.CountNonZero();
  778. Rect rectR2Cut = new Rect(helfx, helfy, helfx - boundary, helfy - boundary);
  779. Mat MatR2Cut = new Mat(hb, rectR2Cut);
  780. int areaCutR2 = MatR2Cut.CountNonZero();
  781. int oneCutR2 = areaAllR2 - areaCutR2;
  782. fourA = fourA - oneCutR2;
  783. Rect cut = new Rect(boundary, boundary, src.Cols - boundary * 2, src.Rows - 70 - boundary * 2);
  784. Cv2.Rectangle(src, cut, colorList[1]);
  785. //using (new Window("MatR2Cut", WindowMode.Normal, MatR2Cut))
  786. //{
  787. // Cv2.WaitKey(0);
  788. //}
  789. }
  790. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  791. HierarchyIndex[] hierarchy;
  792. Cv2.GaussianBlur(dst, dst, new OpenCvSharp.Size(25, 25), 0, 0, BorderTypes.Default);
  793. dst = Binarization(dst);
  794. List<double> crystalList = new List<double>() { 0, 0, 0, 0 };
  795. List<int> crystalListi = new List<int>() { 0, 0, 0, 0 };
  796. int xx = 0;
  797. for (int i = 0; i < 2; i++)
  798. {
  799. for (int j = 0; j < 2; j++)
  800. {
  801. //定义截取矩形
  802. Rect m_select = new Rect(i * helfx, j * helfy, helfx, helfy);
  803. //进行裁剪
  804. Mat imgRect = new Mat(dst, m_select);
  805. Cv2.CvtColor(imgRect, imgRect, ColorConversionCodes.BGR2GRAY);
  806. Cv2.FindContours(imgRect, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  807. for (int t = 0; t < contours.Length; t++)
  808. {
  809. RotatedRect rectR = Cv2.MinAreaRect(contours[t]); //计算每个轮廓最小外接矩形
  810. float width = rectR.Size.Width;
  811. float height = rectR.Size.Height;
  812. bool isjoin = false;
  813. for (int p = 0; p < cs.Count(); p++)
  814. {
  815. if (delKey.Contains(p))
  816. continue;
  817. Point2f center = new Point2f(cs[p].Center.X, cs[p].Center.Y);
  818. double distanc = 0;
  819. for (int k = 0; k < contours[t].Length; k++)
  820. {
  821. Point2f pin = new Point2f(contours[t][k].X, contours[t][k].Y);
  822. distanc += pin.DistanceTo(center);
  823. }
  824. double dev = distanc / contours[t].Length;
  825. float mvg = width / height;
  826. if (dev < cs[p].Radius + 20)
  827. {
  828. isjoin = true;
  829. break;
  830. }
  831. }
  832. if (isjoin)
  833. {
  834. continue;
  835. }
  836. double area = Cv2.ContourArea(contours[t]);
  837. crystalList[xx] = crystalList[xx] + area;
  838. }
  839. crystalListi[xx] = Convert.ToInt32(crystalList[xx]);
  840. xx++;
  841. }
  842. }
  843. Rect m_select1 = new Rect(0, 0, dst.Cols, dst.Rows - 70);
  844. //进行裁剪
  845. Mat imgRect1 = new Mat(dst, m_select1);
  846. Cv2.CvtColor(imgRect1, imgRect1, ColorConversionCodes.BGR2GRAY);
  847. for (int i = 0; i < 6; i++)
  848. {
  849. Cv2.Erode(imgRect1, imgRect1, null);
  850. }
  851. Cv2.FindContours(imgRect1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  852. for (int t = 0; t < contours.Length; t++)
  853. {
  854. Rect CraRect = Cv2.BoundingRect(contours[t]);
  855. double s = Cv2.ContourArea(contours[t]);//轮廓面积
  856. double c = Cv2.ArcLength(contours[t], true); //轮廓周长
  857. //设为二次球
  858. if (BallPointFs.Count > 0)
  859. {
  860. int iscr = 0;
  861. foreach (var item in BallPointFs)
  862. {
  863. OpenCvSharp.Point repoint = new OpenCvSharp.Point(item.X, item.Y);
  864. double isball = Cv2.PointPolygonTest(contours[t], repoint, false);
  865. if (isball > -1)
  866. {
  867. OpenCvSharp.Point pcenter = new OpenCvSharp.Point(CraRect.X + CraRect.Width / 2, CraRect.Y + CraRect.Height / 2);
  868. //加强圆心显示
  869. Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  870. double area = s;
  871. if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  872. {
  873. one++;
  874. oneA = oneA + area;
  875. crystalListi[0] = crystalListi[0] - Convert.ToInt32(area);
  876. }
  877. if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  878. {
  879. two++;
  880. twoA = twoA + area;
  881. crystalListi[1] = crystalListi[1] - Convert.ToInt32(area);
  882. }
  883. if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  884. {
  885. three++;
  886. threeA = threeA + area;
  887. crystalListi[2] = crystalListi[2] - Convert.ToInt32(area);
  888. }
  889. if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  890. {
  891. four++;
  892. fourA = fourA + area;
  893. crystalListi[3] = crystalListi[3] - Convert.ToInt32(area);
  894. }
  895. iscr = 1;
  896. break;
  897. }
  898. }
  899. if (iscr == 1)
  900. {
  901. continue;
  902. }
  903. }
  904. RotatedRect rectR = Cv2.MinAreaRect(contours[t]); //计算每个轮廓最小外接矩形
  905. float width = rectR.Size.Width;
  906. float height = rectR.Size.Height;
  907. //如果离圆心很近算作圆的部分
  908. bool isjoin = false;
  909. for (int p = 0; p < cs.Count(); p++)
  910. {
  911. if (delKey.Contains(p))
  912. continue;
  913. Point2f center = new Point2f(cs[p].Center.X, cs[p].Center.Y);
  914. double distanc = 0;
  915. for (int k = 0; k < contours[t].Length; k++)
  916. {
  917. Point2f pin = new Point2f(contours[t][k].X, contours[t][k].Y);
  918. distanc += pin.DistanceTo(center);
  919. }
  920. double dev = distanc / contours[t].Length;
  921. float mvg = width / height;
  922. if ((dev < cs[p].Radius + 20))
  923. {
  924. isjoin = true;
  925. break;
  926. }
  927. }
  928. if (isjoin)
  929. {
  930. continue;
  931. }
  932. #region 如果球度在范围内判定为球
  933. //List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
  934. //int rx = CraRect.X;
  935. //int ry = CraRect.Y;
  936. //int rw = CraRect.Width;
  937. //int rh = CraRect.Height;
  938. ////top
  939. //if (ry == 0)
  940. //{
  941. // int rmx = rx + rw;
  942. // int rmxh = rw / 2 + rx;
  943. // plist = contours[t].OrderByDescending(g => g.Y).ToList();
  944. // int rmy = plist[0].Y;
  945. // List<OpenCvSharp.Point> qli = new List<OpenCvSharp.Point>() {new OpenCvSharp.Point(rx,0),
  946. // new OpenCvSharp.Point(rx+ rw/4, rmy/2),
  947. // new OpenCvSharp.Point(rmx,0),
  948. // new OpenCvSharp.Point(rx+ rw*3/4, rmy/2),
  949. // new OpenCvSharp.Point(rmxh, rmy) };
  950. // Point2f newcenter1 = new Point2f();
  951. // float newR1 = 0;
  952. // Cv2.MinEnclosingCircle(qli, out newcenter1, out newR1);
  953. // int pcou = 0;
  954. // List<OpenCvSharp.Point> newl = new List<OpenCvSharp.Point>();
  955. // OpenCvSharp.Point pv = new OpenCvSharp.Point((int)newcenter1.X, (int)newcenter1.Y);
  956. // foreach (var item in plist)
  957. // {
  958. // if (item.DistanceTo(pv) > newR1)
  959. // {
  960. // pcou++;
  961. // contours[t] = contours[t].Where(val => val.X != item.X && val.Y != item.Y).ToArray();
  962. // }
  963. // else
  964. // {
  965. // newl.Add(item);
  966. // }
  967. // }
  968. // double t1 = (double)pcou;
  969. // double s1 = Cv2.ContourArea(qli);
  970. // if (s1 / s >0.9 && t1 / s < 0.1)
  971. // {
  972. // //加强圆心显示
  973. // Cv2.Circle(src, (int)pv.X, (int)pv.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  974. // continue;
  975. // }
  976. //}
  977. /***********************
  978. //如果球度在范围内判定为球
  979. //afa参考代码
  980. //double afa = 4 * Math.PI * s / (c * c); //afa计算
  981. //afa = Math.Abs(afa - 1);
  982. //if (afa < 0.2&& s>4000)
  983. //{
  984. // OpenCvSharp.Point pcenter = new OpenCvSharp.Point(CraRect.X+ CraRect.Width/2, CraRect.Y+ CraRect.Height/2);
  985. // //加强圆心显示
  986. // Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  987. // double area = s;
  988. // if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  989. // {
  990. // one++;
  991. // oneA = oneA + area;
  992. // }
  993. // if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  994. // {
  995. // two++;
  996. // twoA = twoA + area;
  997. // }
  998. // if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  999. // {
  1000. // three++;
  1001. // threeA = threeA + area;
  1002. // }
  1003. // if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  1004. // {
  1005. // four++;
  1006. // fourA = fourA + area;
  1007. // }
  1008. // continue;
  1009. //}
  1010. #endregion
  1011. #region 如果是边界半圆算作圆
  1012. //如果是边界半圆算作圆
  1013. List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
  1014. int rx = CraRect.X;
  1015. int ry = CraRect.Y;
  1016. int rw = CraRect.Width;
  1017. int rh = CraRect.Height;
  1018. //top
  1019. if (ry == 0)
  1020. {
  1021. int minx = contours[t][0].X;
  1022. int maxx = contours[t][0].X;
  1023. for (int k = 0; k < contours[t].Length; k++)
  1024. {
  1025. if (contours[t][k].Y > 0)
  1026. {
  1027. plist.Add(contours[t][k]);
  1028. if (minx > contours[t][k].X)
  1029. minx = contours[t][k].X;
  1030. if (maxx < contours[t][k].X)
  1031. maxx = contours[t][k].X;
  1032. }
  1033. }
  1034. plist.Sort((x, y) => x.X.CompareTo(y.X));
  1035. //for (int i = 0; i < maxx - minx; i++)
  1036. //{
  1037. // int curx = i + minx;
  1038. // if (plist[i].X > curx&&i>0)
  1039. // {
  1040. // int y = (plist[i - 1].Y + plist[i].Y) / 2;
  1041. // plist.Insert(i, new OpenCvSharp.Point(curx, y));
  1042. // }
  1043. //}
  1044. if (plist.Count > 10)
  1045. {
  1046. int len = plist.Count / 8;
  1047. int midx = (maxx - minx) / 2 + minx;
  1048. int a = Math.Abs(plist[len].Y - plist[7 * len].Y);
  1049. int b = Math.Abs(plist[2 * len].Y - plist[6 * len].Y);
  1050. int d = Math.Abs(plist[3 * len].Y - plist[5 * len].Y);
  1051. int l1 = plist[len].Y;
  1052. int l2 = plist[2 * len].Y;
  1053. int l3 = plist[3 * len].Y;
  1054. int l5 = plist[5 * len].Y;
  1055. int l6 = plist[6 * len].Y;
  1056. int l7 = plist[7 * len].Y;
  1057. if (l2 > l1 && l3 > l2 && l5 > l6 && l6 > l7)
  1058. {
  1059. OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X, plist[len * 4].Y + 4);
  1060. //加强圆心显示
  1061. Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1062. double area = s;
  1063. if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  1064. {
  1065. one++;
  1066. oneA = oneA + area;
  1067. }
  1068. if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  1069. {
  1070. two++;
  1071. twoA = twoA + area;
  1072. }
  1073. if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  1074. {
  1075. three++;
  1076. threeA = threeA + area;
  1077. }
  1078. if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  1079. {
  1080. four++;
  1081. fourA = fourA + area;
  1082. }
  1083. continue;
  1084. }
  1085. }
  1086. }
  1087. //bottom
  1088. if (ry + rh > src.Rows - 155)
  1089. {
  1090. int minx = contours[t][0].X;
  1091. int maxx = contours[t][0].X;
  1092. for (int k = 0; k < contours[t].Length; k++)
  1093. {
  1094. if (contours[t][k].Y < src.Rows - 155)
  1095. {
  1096. plist.Add(contours[t][k]);
  1097. if (minx > contours[t][k].X)
  1098. minx = contours[t][k].X;
  1099. if (maxx < contours[t][k].X)
  1100. maxx = contours[t][k].X;
  1101. }
  1102. }
  1103. plist.Sort((x, y) => x.X.CompareTo(y.X));
  1104. //for (int i = 0; i < maxx - minx; i++)
  1105. //{
  1106. // int curx = i + minx;
  1107. // if (plist[i].X > curx && i > 0)
  1108. // {
  1109. // int y = (plist[i - 1].Y + plist[i].Y) / 2;
  1110. // plist.Insert(i, new OpenCvSharp.Point(curx, y));
  1111. // }
  1112. //}
  1113. if (plist.Count > 10)
  1114. {
  1115. int len = plist.Count / 8;
  1116. int midx = (maxx - minx) / 2 + minx;
  1117. int a = Math.Abs(plist[len].Y - plist[7 * len].Y);
  1118. int b = Math.Abs(plist[2 * len].Y - plist[6 * len].Y);
  1119. int d = Math.Abs(plist[3 * len].Y - plist[5 * len].Y);
  1120. int l1 = plist[len].Y;
  1121. int l2 = plist[2 * len].Y;
  1122. int l3 = plist[3 * len].Y;
  1123. int l5 = plist[5 * len].Y;
  1124. int l6 = plist[6 * len].Y;
  1125. int l7 = plist[7 * len].Y;
  1126. if (l2 < l1 && l3 < l2 && l5 < l6 && l6 < l7)
  1127. {
  1128. OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X, plist[len * 4].Y + 4);
  1129. //加强圆心显示
  1130. Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1131. double area = s;
  1132. if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  1133. {
  1134. one++;
  1135. oneA = oneA + area;
  1136. }
  1137. if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  1138. {
  1139. two++;
  1140. twoA = twoA + area;
  1141. }
  1142. if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  1143. {
  1144. three++;
  1145. threeA = threeA + area;
  1146. }
  1147. if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  1148. {
  1149. four++;
  1150. fourA = fourA + area;
  1151. }
  1152. continue;
  1153. }
  1154. }
  1155. }
  1156. //left
  1157. if (rx == 0)
  1158. {
  1159. int minx = contours[t][0].Y;
  1160. int maxx = contours[t][0].Y;
  1161. for (int k = 0; k < contours[t].Length; k++)
  1162. {
  1163. if (contours[t][k].X > 0)
  1164. {
  1165. plist.Add(contours[t][k]);
  1166. if (minx > contours[t][k].Y)
  1167. minx = contours[t][k].Y;
  1168. if (maxx < contours[t][k].Y)
  1169. maxx = contours[t][k].Y;
  1170. }
  1171. }
  1172. plist.Sort((x, y) => x.Y.CompareTo(y.Y));
  1173. //for (int i = 0; i < maxx - minx; i++)
  1174. //{
  1175. // int curx = i + minx;
  1176. // if (plist[i].Y > curx && i > 0)
  1177. // {
  1178. // int y = (plist[i - 1].X + plist[i].X) / 2;
  1179. // plist.Insert(i, new OpenCvSharp.Point(y, curx));
  1180. // }
  1181. //}
  1182. if (plist.Count > 10)
  1183. {
  1184. int len = plist.Count / 8;
  1185. int midx = (maxx - minx) / 2 + minx;
  1186. int a = Math.Abs(plist[len].X - plist[7 * len].X);
  1187. int b = Math.Abs(plist[2 * len].X - plist[6 * len].X);
  1188. int d = Math.Abs(plist[3 * len].X - plist[5 * len].X);
  1189. int l1 = plist[len].X;
  1190. int l2 = plist[2 * len].X;
  1191. int l3 = plist[3 * len].X;
  1192. int l5 = plist[5 * len].X;
  1193. int l6 = plist[6 * len].X;
  1194. int l7 = plist[7 * len].X;
  1195. if (l2 > l1 && l3 > l2 && l5 > l6 && l6 > l7)
  1196. {
  1197. OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X + 4, plist[len * 4].Y);
  1198. //加强圆心显示
  1199. Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1200. double area = s;
  1201. if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  1202. {
  1203. one++;
  1204. oneA = oneA + area;
  1205. }
  1206. if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  1207. {
  1208. two++;
  1209. twoA = twoA + area;
  1210. }
  1211. if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  1212. {
  1213. three++;
  1214. threeA = threeA + area;
  1215. }
  1216. if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  1217. {
  1218. four++;
  1219. fourA = fourA + area;
  1220. }
  1221. continue;
  1222. }
  1223. }
  1224. }
  1225. //rght
  1226. if (rx + rw > src.Cols - 3)
  1227. {
  1228. int minx = contours[t][0].Y;
  1229. int maxx = contours[t][0].Y;
  1230. for (int k = 0; k < contours[t].Length; k++)
  1231. {
  1232. if (contours[t][k].X < src.Cols - 3)
  1233. {
  1234. plist.Add(contours[t][k]);
  1235. if (minx > contours[t][k].Y)
  1236. minx = contours[t][k].Y;
  1237. if (maxx < contours[t][k].Y)
  1238. maxx = contours[t][k].Y;
  1239. }
  1240. }
  1241. plist.Sort((x, y) => x.Y.CompareTo(y.Y));
  1242. //for (int i = 0; i < maxx - minx; i++)
  1243. //{
  1244. // int curx = i + minx;
  1245. // if (plist[i].Y > curx && i > 0)
  1246. // {
  1247. // int y = (plist[i - 1].X + plist[i].X) / 2;
  1248. // plist.Insert(i, new OpenCvSharp.Point(y, curx));
  1249. // }
  1250. //}
  1251. if (plist.Count > 10)
  1252. {
  1253. int len = plist.Count / 8;
  1254. int midx = (maxx - minx) / 2 + minx;
  1255. int a = Math.Abs(plist[len].X - plist[7 * len].X);
  1256. int b = Math.Abs(plist[2 * len].X - plist[6 * len].X);
  1257. int d = Math.Abs(plist[3 * len].X - plist[5 * len].X);
  1258. int l1 = plist[len].X;
  1259. int l2 = plist[2 * len].X;
  1260. int l3 = plist[3 * len].X;
  1261. int l5 = plist[5 * len].X;
  1262. int l6 = plist[6 * len].X;
  1263. int l7 = plist[7 * len].X;
  1264. if (l2 < l1 && l3 < l2 && l5 < l6 && l6 < l7)
  1265. {
  1266. OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X + 4, plist[len * 4].Y);
  1267. //加强圆心显示
  1268. Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1269. double area = s;
  1270. if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
  1271. {
  1272. one++;
  1273. oneA = oneA + area;
  1274. }
  1275. if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
  1276. {
  1277. two++;
  1278. twoA = twoA + area;
  1279. }
  1280. if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
  1281. {
  1282. three++;
  1283. threeA = threeA + area;
  1284. }
  1285. if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
  1286. {
  1287. four++;
  1288. fourA = fourA + area;
  1289. }
  1290. continue;
  1291. }
  1292. }
  1293. }
  1294. **************/
  1295. #endregion
  1296. Mat temp_empt = Mat.Zeros(src.Size(), MatType.CV_8UC1);
  1297. Cv2.DrawContours(temp_empt, contours, t, new Scalar(255), -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  1298. for (int i = 0; i < 6; i++)
  1299. {
  1300. Cv2.Dilate(temp_empt, temp_empt, null);
  1301. }
  1302. OpenCvSharp.Point[][] contours1 = new OpenCvSharp.Point[][] { };
  1303. Cv2.FindContours(temp_empt, out contours1, out HierarchyIndex[] hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  1304. Cv2.DrawContours(src, contours1, 0, new Scalar(vec4B.Item0, vec4B.Item1, vec4B.Item2, vec4B.Item3), -1, LineTypes.Link8, hierarchy1, 4, new OpenCvSharp.Point(0, 0));
  1305. }
  1306. for (int i = 0; i < cs.Length; i++)
  1307. {
  1308. if (delKey.Contains(i))
  1309. {
  1310. continue;
  1311. }
  1312. //加强圆心显示
  1313. Cv2.Circle(src, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1314. }
  1315. //
  1316. if (CrystalLunkuo.Count > 0)
  1317. {
  1318. for (int lk = 0; lk < CrystalLunkuo.Count; lk++)
  1319. {
  1320. List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
  1321. CrystalLunkuo[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
  1322. Point2f newcenter = new Point2f();
  1323. float newR = 0;
  1324. Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
  1325. Cv2.Circle(src, (int)newcenter.X, (int)newcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
  1326. //Rect lkRect = Cv2.BoundingRect(pl);
  1327. ////加强圆心显示
  1328. //Cv2.Circle(dst, (int)(lkRect.X + lkRect.Width / 2), (int)(lkRect.Y + lkRect.Height / 2), 3, colorList[0], 2, LineTypes.AntiAlias);
  1329. }
  1330. }
  1331. Cv2.Line(src, new OpenCvSharp.Point() { X = 0, Y = helfy }, new OpenCvSharp.Point() { X = src.Cols, Y = helfy }, colorList[1]);
  1332. Cv2.Line(src, new OpenCvSharp.Point() { X = helfx, Y = 0 }, new OpenCvSharp.Point() { X = helfx, Y = src.Rows - 70 }, colorList[1]);
  1333. circleList.Add(one);
  1334. circleList.Add(two);
  1335. circleList.Add(three);
  1336. circleList.Add(four);
  1337. circleAreaList.Add((int)oneA);
  1338. circleAreaList.Add((int)twoA);
  1339. circleAreaList.Add((int)threeA);
  1340. circleAreaList.Add((int)fourA);
  1341. data.Add(circleList);
  1342. data.Add(crystalListi);
  1343. data.Add(circleAreaList);
  1344. }
  1345. else if (imageType == 4)
  1346. {
  1347. if (selPointFs != -1 && retMat != null)
  1348. {
  1349. Mat used = retMat.Clone();
  1350. keyValueSel.Add(selPointFs, 1);
  1351. List<int> sel = poListHis[selPointFs];
  1352. //src = SelectBall(used, sel[0], sel[1], sel[2]);
  1353. src = SelectBallInt(used, selPointFs);
  1354. }
  1355. else
  1356. {
  1357. //src = WhirtBinarization(src);
  1358. Cv2.CvtColor(src, src, ColorConversionCodes.BGRA2BGR);
  1359. Mat dst = new Mat();
  1360. //Cv2.PyrMeanShiftFiltering(src, src, 21, 51);
  1361. Cv2.GaussianBlur(src, src, new OpenCvSharp.Size(17, 17), 0);
  1362. Cv2.MedianBlur(src, src, 15);
  1363. // Cv2.BilateralFilter(dst, src, 21, 132, 181);
  1364. src = BinarizationBall(src);
  1365. InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
  1366. // 开操作,也可省落变量前缀名
  1367. // Cv2.MorphologyEx(src, src, MorphTypes.Dilate, kernel, new OpenCvSharp.Point(-1, -1));
  1368. //双边滤波
  1369. //Cv2.MorphologyEx(src, src, MorphTypes.Close, null, null, 4, BorderTypes.Constant);
  1370. //src = WhirtBinarization(src);
  1371. //src = DrwCrackBall(src);
  1372. //retMat = src.Clone();
  1373. //poListHis.Clear();
  1374. //poList.ForEach(i => poListHis.Add(i));
  1375. }
  1376. keyValueSel.Clear();
  1377. selPointFs = -1;
  1378. }
  1379. else if (imageType == 14)
  1380. {
  1381. if (selPointFs != -1 && retMat != null)
  1382. {
  1383. Mat used = retMat.Clone();
  1384. keyValueSel.Add(selPointFs, 1);
  1385. List<int> sel = poListHis[selPointFs];
  1386. src = SelectBallInt(used, selPointFs);
  1387. }
  1388. else
  1389. {
  1390. src = DrwCrackBall(src);
  1391. retMat = src.Clone();
  1392. poListHis.Clear();
  1393. poList.ForEach(i => poListHis.Add(i));
  1394. }
  1395. keyValueSel.Clear();
  1396. selPointFs = -1;
  1397. }
  1398. else if (imageType == 5)
  1399. {
  1400. if (selPointFs != -1 && retMat != null)
  1401. {
  1402. Mat used = retMat.Clone();
  1403. keyValueSel.Add(selPointFs, 1);
  1404. src = SelectPoint(used);
  1405. }
  1406. else
  1407. {
  1408. //二值提取
  1409. src = BinarizationForM(src);
  1410. //去掉过小孔隙,计算孔隙面积
  1411. src = DebrisRemoval_New(src);
  1412. data.Add(poAreaList);
  1413. retMat = src.Clone();
  1414. }
  1415. keyValueSel.Clear();
  1416. selPointFs = -1;
  1417. }
  1418. return src;
  1419. }
  1420. /// <summary>
  1421. /// 开裂球
  1422. /// </summary>
  1423. /// <param name="src">源图像</param>
  1424. /// <param name="lists">参数集合</param>
  1425. /// <returns></returns>
  1426. public static Mat ImageBinaryExtraction(Mat src, Mat source, List<Args> lists, out List<List<int>> data, bool findContours = false)
  1427. {
  1428. //以下是参数信息---------------------
  1429. ///1个颜色区间还是2个
  1430. colorInterval = 1;
  1431. //第一个二值区间
  1432. colorOneStart = 0;
  1433. colorOneEnd = 0;
  1434. //第二个二值区间
  1435. colorTwoStart = 0;
  1436. colorTwoEnd = 0;
  1437. //第三个二值区间
  1438. colorThreeStart = 0;
  1439. colorThreeEnd = 0;
  1440. //处理细节
  1441. //删除边界对象
  1442. bool deleteBoundaryObject = false;
  1443. //孔洞填充
  1444. bool holeFilling = false;
  1445. //碎屑删除
  1446. bool debrisRemoval = false;
  1447. //碎屑删除面积起
  1448. debrisAreaStart = 0;
  1449. //碎屑删除面积止
  1450. debrisAreaEnd = 0;
  1451. //二值样式
  1452. //1实心 2边线
  1453. int binaryStyle = 0;
  1454. //相颜色
  1455. Color phaseColor = Color.Red;
  1456. //目标选择
  1457. int targetSelection = 1;
  1458. for (int i = 0; i < lists.Count; i++)
  1459. {
  1460. Args args = lists[i];
  1461. switch (args.Key)
  1462. {
  1463. case "colorInterval":
  1464. {
  1465. if (args.Value is Boolean)
  1466. colorInterval = (Boolean)args.Value ? 2 : 1;
  1467. else
  1468. colorInterval = (int)args.Value;
  1469. }
  1470. break;
  1471. case "scope1":
  1472. colorOneStart = (int)((List<double>)args.Value)[0];
  1473. colorOneEnd = (int)((List<double>)args.Value)[1];
  1474. break;
  1475. case "scope2":
  1476. colorTwoStart = (int)((List<double>)args.Value)[0];
  1477. colorTwoEnd = (int)((List<double>)args.Value)[1];
  1478. break;
  1479. case "scope3":
  1480. colorThreeStart = (int)((List<double>)args.Value)[0];
  1481. colorThreeEnd = (int)((List<double>)args.Value)[1];
  1482. break;
  1483. case "deleteBoundaryObject":
  1484. deleteBoundaryObject = (bool)args.Value;
  1485. break;
  1486. case "holeFilling":
  1487. holeFilling = (bool)args.Value;
  1488. break;
  1489. case "debrisRemoval":
  1490. debrisRemoval = (bool)args.Value;
  1491. break;
  1492. case "binaryStyle":
  1493. binaryStyle = (int)args.Value;
  1494. break;
  1495. case "phaseColor":
  1496. phaseColor = Color.FromArgb((int)args.Value);
  1497. break;
  1498. case "targetSelection":
  1499. targetSelection = (int)args.Value;
  1500. break;
  1501. case "scope4":
  1502. debrisAreaStart = (int)((List<double>)args.Value)[0];
  1503. debrisAreaEnd = (int)((List<double>)args.Value)[1];
  1504. findContours = true;
  1505. break;
  1506. case "CircleCount":
  1507. circleCount = (int)args.Value;
  1508. break;
  1509. case "maxContour":
  1510. maxContour = (OpenCvSharp.Point[])args.Value;
  1511. break;
  1512. case "CircleR":
  1513. CircleR = (int)args.Value;
  1514. break;
  1515. case "Center":
  1516. center = (OpenCvSharp.Point)args.Value;
  1517. break;
  1518. case "DelPointFs":
  1519. delPointFs = (List<PointF>)args.Value;
  1520. break;
  1521. case "imageType":
  1522. imageType = (int)args.Value;
  1523. break;
  1524. case "SelPointFs":
  1525. selPointFs = (int)args.Value;
  1526. break;
  1527. case "imageTypes":
  1528. imageType = (int)args.Value;
  1529. break;
  1530. case "CreackBallPointFs":
  1531. CreackBallPointFs = (List<PointF>)args.Value;
  1532. break;
  1533. case "CreackBallPointFsK":
  1534. CreackBallPointFsK = (List<PointF>)args.Value;
  1535. break;
  1536. case "CreackBallPointFsP":
  1537. CreackBallPointFsP = (List<PointF>)args.Value;
  1538. break;
  1539. default:
  1540. break;
  1541. }
  1542. }
  1543. if (phaseColor.A < 1)//#21321
  1544. phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
  1545. vec4B.Item0 = phaseColor.B;
  1546. vec4B.Item1 = phaseColor.G;
  1547. vec4B.Item2 = phaseColor.R;
  1548. vec4B.Item3 = phaseColor.A;
  1549. poArea = 0;
  1550. maxArea = 0;
  1551. poList.Clear();
  1552. poAreaList = new List<int>() { };
  1553. data = poList;
  1554. imageHight = src.Rows;
  1555. if (imageType == 14)
  1556. {
  1557. if (selPointFs != -1 && retMat != null)
  1558. {
  1559. Mat used = retMat.Clone();
  1560. keyValueSel.Add(selPointFs, 1);
  1561. List<int> sel = poListHis[selPointFs];
  1562. src = SelectBallInt(used, selPointFs);
  1563. }
  1564. else
  1565. {
  1566. src = DrwCrackBall_New(src, source);
  1567. retMat = src.Clone();
  1568. poListHis.Clear();
  1569. poList.ForEach(i => poListHis.Add(i));
  1570. }
  1571. keyValueSel.Clear();
  1572. selPointFs = -1;
  1573. }
  1574. return src;
  1575. }
  1576. /// <summary>
  1577. /// 二次球与单晶去底条
  1578. /// </summary>
  1579. /// <param name="source"></param>
  1580. /// <returns></returns>
  1581. private static Mat RemoveBottm(Mat source)
  1582. {
  1583. Mat srcGray;
  1584. if (source.Type() == MatType.CV_8UC1)
  1585. {
  1586. srcGray = source;
  1587. }
  1588. else
  1589. {
  1590. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  1591. }
  1592. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  1593. srcGray.ForEachAsByte(RemoveBottmForEachAsByte);
  1594. return temp.Clone();
  1595. }
  1596. /// <summary>
  1597. /// 并行循环
  1598. /// </summary>
  1599. /// <param name="value"></param>
  1600. /// <param name="position"></param>
  1601. private static void RemoveBottmForEachAsByte(byte* value, int* position)
  1602. {
  1603. int y = position[0];
  1604. int x = position[1];
  1605. byte v = *value;
  1606. if (y > imageHight - 140)
  1607. {
  1608. temp.Set<Vec4b>(y, x, vec4Bw);
  1609. }
  1610. }
  1611. /// <summary>
  1612. /// 二值提取
  1613. /// </summary>
  1614. /// <param name="source">源</param>
  1615. /// <param name="colorInterval">1个或2个颜色区间</param>
  1616. /// <param name="colorOneStart"></param>
  1617. /// <param name="colorOneEnd"></param>
  1618. /// <param name="colorTwoStart"></param>
  1619. /// <param name="colorTwoEnd"></param>
  1620. /// <param name="colorThreeStart"></param>
  1621. /// <param name="colorThreeEnd"></param>
  1622. /// <returns></returns>
  1623. private static Mat Binarization(Mat source)
  1624. {
  1625. Mat srcGray;
  1626. if (source.Type() == MatType.CV_8UC1)
  1627. {
  1628. srcGray = source;
  1629. }
  1630. else
  1631. {
  1632. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  1633. }
  1634. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  1635. try
  1636. {
  1637. srcGray.ForEachAsByte(GrayForEachAsByte);
  1638. }
  1639. catch (Exception e)
  1640. {
  1641. throw;
  1642. }
  1643. return temp.Clone();
  1644. }
  1645. /// <summary>
  1646. /// 并行循环
  1647. /// </summary>
  1648. /// <param name="value"></param>
  1649. /// <param name="position"></param>
  1650. private static void GrayForEachAsByte(byte* value, int* position)
  1651. {
  1652. int y = position[0];
  1653. int x = position[1];
  1654. byte v = *value;
  1655. if (colorInterval == 1)
  1656. {
  1657. if (v >= colorOneStart && v <= colorOneEnd)
  1658. {
  1659. temp.Set<Vec4b>(y, x, vec4B);
  1660. //手动画圆
  1661. if (ListRadiusColor.Count > 0)
  1662. {
  1663. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  1664. Color co = ListRadiusColor.First().Value;
  1665. Vec4b colorMax = new Vec4b(co.B, co.G, co.R, 255);
  1666. temp.Set<Vec4b>(y, x, colorMax);
  1667. foreach (var item in ListRadiusColor)
  1668. {
  1669. int r = item.Key;
  1670. if (d < r)
  1671. {
  1672. Vec4b vb4 = new Vec4b(item.Value.B, item.Value.G, item.Value.R, 255);
  1673. temp.Set<Vec4b>(y, x, vb4);
  1674. }
  1675. }
  1676. if (ListRadiusColor.Count > 1)
  1677. {
  1678. for (int i = 0; i < ListRadiusColor.Count - 1; i++)
  1679. {
  1680. int r = i == 0 ? 0 : ListRadiusColor.ElementAt(ListRadiusColor.Count - i).Key;
  1681. int r2 = ListRadiusColor.ElementAt(ListRadiusColor.Count - 1 - i).Key;
  1682. if (r < d && d <= r2)
  1683. {
  1684. poAreaList[i]++;
  1685. break;
  1686. }
  1687. }
  1688. }
  1689. }
  1690. else if (circleCount > 1) //同心圆数量大于一时染色
  1691. {
  1692. temp.Set<Vec4b>(y, x, vec4BList[circleCount - 1]);
  1693. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  1694. for (int i = circleCount - 1; i >= 0; i--)
  1695. {
  1696. int r = Convert.ToInt32(CircleR * (i + 1));
  1697. if (d < r)
  1698. {
  1699. temp.Set<Vec4b>(y, x, vec4BList[i]);
  1700. }
  1701. }
  1702. for (int i = 0; i < circleCount; i++)
  1703. {
  1704. int r = Convert.ToInt32(CircleR * (i));
  1705. int r2 = Convert.ToInt32(CircleR * (i + 1));
  1706. if (r < d && d <= r2)
  1707. {
  1708. poAreaList[i]++;
  1709. break;
  1710. }
  1711. }
  1712. }
  1713. }
  1714. }
  1715. else
  1716. {
  1717. if ((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd))
  1718. {
  1719. temp.Set<Vec4b>(y, x, vec4B);
  1720. }
  1721. }
  1722. }
  1723. /// <summary>
  1724. /// 开裂球分水岭二值提取
  1725. /// </summary>
  1726. /// <param name="source">源</param>
  1727. /// <param name="colorInterval">1个或2个颜色区间</param>
  1728. /// <param name="colorOneStart"></param>
  1729. /// <param name="colorOneEnd"></param>
  1730. /// <param name="colorTwoStart"></param>
  1731. /// <param name="colorTwoEnd"></param>
  1732. /// <param name="colorThreeStart"></param>
  1733. /// <param name="colorThreeEnd"></param>
  1734. /// <returns></returns>
  1735. private static Mat BinarizationBall(Mat source)
  1736. {
  1737. Mat srcGray;
  1738. if (source.Type() == MatType.CV_8UC1)
  1739. {
  1740. srcGray = source;
  1741. }
  1742. else
  1743. {
  1744. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  1745. }
  1746. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  1747. srcGray.ForEachAsByte(GrayForEachAsByteBall);
  1748. return temp.Clone();
  1749. }
  1750. /// <summary>
  1751. /// 并行循环
  1752. /// </summary>
  1753. /// <param name="value"></param>
  1754. /// <param name="position"></param>
  1755. private static void GrayForEachAsByteBall(byte* value, int* position)
  1756. {
  1757. int y = position[0];
  1758. int x = position[1];
  1759. byte v = *value;
  1760. if (colorInterval == 1)
  1761. {
  1762. if (v >= colorOneStart && v <= colorOneEnd)
  1763. {
  1764. temp.Set<Vec4b>(y, x, vec4B);
  1765. }
  1766. }
  1767. else
  1768. {
  1769. if ((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd))
  1770. {
  1771. temp.Set<Vec4b>(y, x, vec4B);
  1772. }
  1773. }
  1774. }
  1775. private static Mat WhirtBinarization(Mat source)
  1776. {
  1777. Mat srcGray;
  1778. if (source.Type() == MatType.CV_8UC1)
  1779. {
  1780. srcGray = source;
  1781. }
  1782. else
  1783. {
  1784. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  1785. }
  1786. temp = source.Clone();
  1787. srcGray.ForEachAsByte(WhirtForEachAsByte);
  1788. return temp.Clone();
  1789. }
  1790. /// <summary>
  1791. /// 并行循环
  1792. /// </summary>
  1793. /// <param name="value"></param>
  1794. /// <param name="position"></param>
  1795. private static void WhirtForEachAsByte(byte* value, int* position)
  1796. {
  1797. int y = position[0];
  1798. int x = position[1];
  1799. byte v = *value;
  1800. if (v > 240 || y > imageHight - 70)
  1801. {
  1802. temp.Set<Vec4b>(y, x, vec4Bw);
  1803. }
  1804. //if (x < 50 || y < 50 || x > imageWidth - 50 || y > imageHight - 190)
  1805. //{
  1806. // temp.Set<Vec4b>(y, x, vec4Bw);
  1807. //}
  1808. }
  1809. //二次球去边
  1810. private static Mat BallCutBottor(Mat source)
  1811. {
  1812. Mat srcGray;
  1813. if (source.Type() == MatType.CV_8UC1)
  1814. {
  1815. srcGray = source;
  1816. }
  1817. else
  1818. {
  1819. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  1820. }
  1821. temp = source.Clone();
  1822. srcGray.ForEachAsByte(BallCutBottorForEachAsByte);
  1823. return temp.Clone();
  1824. }
  1825. /// <summary>
  1826. /// 并行循环
  1827. /// </summary>
  1828. /// <param name="value"></param>
  1829. /// <param name="position"></param>
  1830. private static void BallCutBottorForEachAsByte(byte* value, int* position)
  1831. {
  1832. int y = position[0];
  1833. int x = position[1];
  1834. byte v = *value;
  1835. if (x < boundary || y < boundary || x > imageWidth - boundary || y > imageHight - boundary - 140)
  1836. {
  1837. temp.Set<Vec4b>(y, x, vec4Bw);
  1838. }
  1839. }
  1840. /// <summary>
  1841. /// 新版本删除边界
  1842. /// </summary>
  1843. /// <param name="src"></param>
  1844. /// <returns></returns>
  1845. private static Mat DeleteContours_New(Mat src)
  1846. {
  1847. Mat[] arr = src.Split();
  1848. Mat rgb = BaseTools.MergeMatFromMatArr(arr);
  1849. Mat temp_1 = arr[3].Clone();
  1850. for (int h = 0; h < temp_1.Width; h++)
  1851. {
  1852. byte vec4B_top = temp_1.At<byte>(0, h);
  1853. if (vec4B_top > 0)
  1854. {
  1855. Cv2.FloodFill(rgb, new OpenCvSharp.Point(h, 0), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1856. Cv2.FloodFill(temp_1, new OpenCvSharp.Point(h, 0), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1857. }
  1858. }
  1859. for (int h = 0; h < temp_1.Width; h++)
  1860. {
  1861. byte vec4B_bottom = temp_1.At<byte>(temp_1.Height - 1, h);
  1862. if (vec4B_bottom > 0)
  1863. {
  1864. Cv2.FloodFill(rgb, new OpenCvSharp.Point(h, temp_1.Height - 1), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1865. Cv2.FloodFill(temp_1, new OpenCvSharp.Point(h, temp_1.Height - 1), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1866. }
  1867. }
  1868. for (int y = 0; y < temp_1.Height; y++)
  1869. {
  1870. Vec4b vec4B_top = temp_1.At<Vec4b>(y, 0);
  1871. if (vec4B_top.Item3 > 0)
  1872. {
  1873. Cv2.FloodFill(rgb, new OpenCvSharp.Point(0, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1874. Cv2.FloodFill(temp_1, new OpenCvSharp.Point(0, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1875. }
  1876. }
  1877. for (int y = 0; y < temp_1.Height; y++)
  1878. {
  1879. byte vec4B_top = temp_1.At<byte>(y, temp_1.Width - 1);
  1880. if (vec4B_top > 0)
  1881. {
  1882. Cv2.FloodFill(rgb, new OpenCvSharp.Point(temp_1.Width - 1, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1883. Cv2.FloodFill(temp_1, new OpenCvSharp.Point(temp_1.Width - 1, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  1884. }
  1885. }
  1886. Mat[] mats = rgb.Split();
  1887. arr[0] = mats[0];
  1888. arr[1] = mats[1];
  1889. arr[2] = mats[2];
  1890. arr[3] = temp_1;
  1891. Cv2.Merge(arr, src);
  1892. return src;
  1893. }
  1894. /// <summary>
  1895. /// 新孔洞填充,采用形态学填充
  1896. /// </summary>
  1897. /// <param name="src"></param>
  1898. /// <returns></returns>
  1899. private static Mat HoleFilling_New(Mat src)
  1900. {
  1901. Mat[] arr2 = src.Split();
  1902. Mat matc = arr2[3];
  1903. //去掉透明层
  1904. Mat mat = src.CvtColor(ColorConversionCodes.BGRA2BGR);
  1905. //填充孔洞
  1906. mat = BaseTools.FillHole(mat, new Scalar(255 - vec4B.Item0, 255 - vec4B.Item1, 255 - vec4B.Item2));
  1907. matc = BaseTools.FillHole(matc, new Scalar(255));
  1908. //循环处理
  1909. mat.ForEachAsVec3b(RGBForEachAsByteForHoleFillingNew);
  1910. Mat[] arr1 = mat.Split();
  1911. arr2[0] = arr1[0];
  1912. arr2[1] = arr1[1];
  1913. arr2[2] = arr1[2];
  1914. arr2[3] = matc;
  1915. Cv2.Merge(arr2, src);
  1916. return src;
  1917. }
  1918. private static void RGBForEachAsByteForHoleFillingNew(Vec3b* value, int* position)
  1919. {
  1920. int y = position[0];
  1921. int x = position[1];
  1922. if (value->Item0 == 255 && value->Item1 == 255 && value->Item2 == 255)
  1923. {
  1924. value->Item0 = vec4B.Item0;
  1925. value->Item1 = vec4B.Item1;
  1926. value->Item2 = vec4B.Item2;
  1927. }
  1928. }
  1929. /// <summary>
  1930. /// 选择颗粒处理
  1931. /// </summary>
  1932. /// <param name="src"></param>
  1933. /// <returns></returns>
  1934. private static Mat SelectPoint(Mat src)
  1935. {
  1936. Mat[] arr = src.Split();
  1937. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  1938. temp_ap = arr[3].Clone();
  1939. labelMatForSel.ForEachAsInt32(CommonForEachForSel);
  1940. //合并rgb和透明度
  1941. Mat[] mats = rgb_ap.Split();
  1942. arr[0] = mats[0];
  1943. arr[1] = mats[1];
  1944. arr[2] = mats[2];
  1945. arr[3] = temp_ap;
  1946. Cv2.Merge(arr, src);
  1947. return src;
  1948. }
  1949. /// <summary>
  1950. /// 新碎屑删除,使用连通分量找寻碎屑截面孔隙
  1951. /// </summary>
  1952. /// <param name="src"></param>
  1953. /// <returns></returns>
  1954. private static Mat DebrisRemoval_New(Mat src)
  1955. {
  1956. Mat[] arr = src.Split();
  1957. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  1958. temp_ap = arr[3].Clone();
  1959. //寻找连通分量
  1960. Mat labelMat = new Mat();
  1961. Mat stats = new Mat();
  1962. Mat centroids = new Mat();
  1963. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  1964. Mat oo = temp_ap.Clone();
  1965. Cv2.Dilate(oo, oo, null);
  1966. Mat respend = new Mat();
  1967. temp_view.ConvertTo(respend, MatType.CV_8UC3);
  1968. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  1969. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  1970. Cv2.FindContours(oo, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  1971. for (int i = 0; i < contours.Length; i++)
  1972. {
  1973. double art = Cv2.ContourArea(contours[i]);
  1974. if (art < 50)
  1975. continue;
  1976. respend.DrawContours(contours, i, Scalar.RandomColor(), -1);
  1977. }
  1978. //using (new Window("s", WindowMode.Normal, respend))
  1979. //{
  1980. // Cv2.WaitKey(0);
  1981. //}
  1982. //Cv2.ImWrite("E://tt.jpg", respend);
  1983. //寻找在范围内需要删除的碎屑
  1984. keyValuePairs.Clear();
  1985. keyValueSel.Clear();
  1986. for (int h = 1; h < centroids.Height; h++)
  1987. {
  1988. int areaField1 = stats.At<int>(h, 4);
  1989. int x = stats.At<int>(h, 0);
  1990. int y = stats.At<int>(h, 1);
  1991. int width = stats.At<int>(h, 2);
  1992. int height = stats.At<int>(h, 3);
  1993. //面积小于30的孔隙删除
  1994. if (debrisAreaStart <= areaField1 && areaField1 <= 3)
  1995. {
  1996. keyValuePairs.Add(h, 1);
  1997. }
  1998. else if (areaField1 > src.Rows * src.Cols * 0.3)//面积最大的是轮廓,这里算大于整体面积的0.3
  1999. {
  2000. keyValuePairs.Add(h, 1);
  2001. maxArea = areaField1;
  2002. }
  2003. else
  2004. {
  2005. int qud = 0;
  2006. if (delPointFs != null && delPointFs.Count > 0)
  2007. {
  2008. for (int i = 0; i < delPointFs.Count; i++)
  2009. {
  2010. double px = delPointFs[i].X;
  2011. double py = delPointFs[i].Y;
  2012. if (px > x && px < (x + width) && py > y && py < (y + height))
  2013. {
  2014. keyValuePairs.Add(h, 1);
  2015. qud = 1;
  2016. break;
  2017. }
  2018. }
  2019. }
  2020. if (qud == 1)
  2021. {
  2022. continue;
  2023. }
  2024. poArea += areaField1;
  2025. List<int> po = new List<int>() { x, y, width, height, areaField1, h };
  2026. poList.Add(po);
  2027. }
  2028. }
  2029. labelMatForSel = labelMat;
  2030. labelMat.ForEachAsInt32(CommonForEachForInt32);
  2031. labelMat.ForEachAsInt32(CommonForEachForSel);
  2032. //合并rgb和透明度
  2033. Mat[] mats = rgb_ap.Split();
  2034. arr[0] = mats[0];
  2035. arr[1] = mats[1];
  2036. arr[2] = mats[2];
  2037. arr[3] = temp_ap;
  2038. Cv2.Merge(arr, src);
  2039. return src;
  2040. }
  2041. private static Mat CrystBinarization(Mat source)
  2042. {
  2043. Mat srcGray;
  2044. if (source.Type() == MatType.CV_8UC1)
  2045. {
  2046. srcGray = source;
  2047. }
  2048. else
  2049. {
  2050. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  2051. }
  2052. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  2053. srcGray.ForEachAsByte(CrystForEachAsByte);
  2054. return temp.Clone();
  2055. }
  2056. /// <summary>
  2057. /// 并行循环
  2058. /// </summary>
  2059. /// <param name="value"></param>
  2060. /// <param name="position"></param>
  2061. private static void CrystForEachAsByte(byte* value, int* position)
  2062. {
  2063. int y = position[0];
  2064. int x = position[1];
  2065. byte v = *value;
  2066. if (v >= 240)
  2067. {
  2068. temp.Set<Vec4b>(y, x, vec4B);
  2069. }
  2070. //if (AddPontins != null && AddPontins.Count > 0)
  2071. //{
  2072. // for (int i = 0; i < AddPontins.Count; i++)
  2073. // {
  2074. // if (Cv2.PointPolygonTest(AddPontins[i], new OpenCvSharp.Point(x, y), false) > -1)
  2075. // {
  2076. // temp.Set<Vec4b>(y, x, vec4B);
  2077. // }
  2078. // }
  2079. //}
  2080. }
  2081. /// <summary>
  2082. /// 单晶使用找轮廓找寻碎屑
  2083. /// </summary>
  2084. /// <param name="src"></param>
  2085. /// <returns></returns>
  2086. private static Mat DebrisRemoval_Cryst1(Mat src)
  2087. {
  2088. if (AddPontins != null && AddPontins.Count > 0)
  2089. {
  2090. Cv2.DrawContours(src, AddPontins, -1, new Scalar(255, 255, 255, 255), -1);
  2091. }
  2092. //using (new Window("s",WindowMode.Normal, src))
  2093. //{
  2094. // Cv2.WaitKey(0);
  2095. //}
  2096. src = CrystBinarization(src);
  2097. Mat[] arr = src.Split();
  2098. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  2099. temp_ap = arr[3].Clone();
  2100. OpenCvSharp.Point[][] contours;
  2101. HierarchyIndex[] hierarchy;
  2102. Cv2.FindContours(temp_ap, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  2103. //寻找在范围内需要删除的碎屑
  2104. for (int h = 1; h < contours.Length; h++)
  2105. {
  2106. Rect rect = Cv2.BoundingRect(contours[h]);
  2107. int areaField1 = Convert.ToInt32(Cv2.ContourArea(contours[h]));
  2108. int x = rect.X;
  2109. int y = rect.Y;
  2110. int width = rect.Width;
  2111. int height = rect.Height;
  2112. //边缘
  2113. if (x < 5 || x + width > src.Cols - 5 || y < 5 || y + height > src.Rows - 5)
  2114. {
  2115. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2116. continue;
  2117. }
  2118. //面积小于30的孔隙删除
  2119. else if (areaField1 < 2)
  2120. {
  2121. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2122. continue;
  2123. }
  2124. else
  2125. {
  2126. poArea += areaField1;
  2127. Mat t = new Mat(temp_ap, new Rect(x, y, width, height));
  2128. int maxxx = 0; int maxyy = 0;
  2129. int inde = h - 1;
  2130. RotatedRect rectR = Cv2.MinAreaRect(contours[h]);
  2131. if (maxxx < rectR.Size.Width)
  2132. {
  2133. maxxx = (int)rectR.Size.Width;
  2134. }
  2135. if (maxyy < rectR.Size.Height)
  2136. {
  2137. maxyy = (int)rectR.Size.Height;
  2138. }
  2139. double kgr = Convert.ToDouble(maxxx + maxyy) * 0.5 * Micron;
  2140. double hlengh = maxxx > maxyy ? maxxx : maxyy;
  2141. double wlengh = maxxx < maxyy ? maxxx : maxyy;
  2142. double area = maxxx * maxyy * AreaRatio;
  2143. if (wlengh > 0)
  2144. {
  2145. double hm = hlengh / wlengh;
  2146. //颗粒尺寸超长
  2147. if (kgr < pointsize)
  2148. {
  2149. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2150. continue;
  2151. }
  2152. else if (hm > HW)//长宽比过大
  2153. {
  2154. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2155. continue;
  2156. }
  2157. else if (areaField1 < area)
  2158. {
  2159. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2160. continue;
  2161. }
  2162. //正常颗粒
  2163. else
  2164. {
  2165. //afa参考代码
  2166. double s = areaField1;//轮廓面积
  2167. double c = contours[h].Length; //轮廓周长
  2168. double afa = Math.Sqrt(4 * Math.PI * s / (c * c)); //afa计算
  2169. int aa = Convert.ToInt32(afa * 1000);
  2170. InputArray contoursAll = InputArray.Create(contours[h]);
  2171. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2172. OutputArray hull = OutputArray.Create(outArr);
  2173. Cv2.ConvexHull(contoursAll, hull, true);
  2174. double nc = Cv2.ArcLength(outArr.ToArray(), true) / Math.PI;
  2175. double na = Math.Sqrt(areaField1 / Math.PI) * 2;
  2176. aa = Convert.ToInt32((na / nc) * 1000);
  2177. List<int> po = new List<int>() { x, y, width, height, areaField1, h, maxxx, maxyy, aa };
  2178. poList.Add(po);
  2179. }
  2180. }
  2181. else
  2182. {
  2183. temp_ap.DrawContours(contours, h, new Scalar(0), -1);
  2184. continue;
  2185. }
  2186. }
  2187. }
  2188. //合并rgb和透明度
  2189. Mat[] mats = rgb_ap.Split();
  2190. arr[0] = mats[0];
  2191. arr[1] = mats[1];
  2192. arr[2] = mats[2];
  2193. arr[3] = temp_ap;
  2194. Cv2.Merge(arr, src);
  2195. return src;
  2196. }
  2197. /// <summary>
  2198. /// 单晶使用连通分量找寻碎屑
  2199. /// </summary>
  2200. /// <param name="src"></param>
  2201. /// <returns></returns>
  2202. private static int hindex = -1;
  2203. private static Mat ground = new Mat();
  2204. private static Mat DebrisRemoval_Cryst(Mat src)
  2205. {
  2206. src = CrystBinarization(src);
  2207. keyValuePairs.Clear();
  2208. Mat[] arr = src.Split();
  2209. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  2210. temp_ap = arr[3].Clone();
  2211. //寻找连通分量
  2212. Mat labelMat = new Mat();
  2213. Mat stats = new Mat();
  2214. Mat centroids = new Mat();
  2215. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2216. if (delPointFs != null && delPointFs.Count > 0)
  2217. {
  2218. for (int i = 0; i < delPointFs.Count; i++)
  2219. {
  2220. int qx = (int)delPointFs[i].X;
  2221. int qy = (int)delPointFs[i].Y;
  2222. int label = labelMat.At<int>(qy, qx);
  2223. if (label > 0 && !keyValuePairs.ContainsKey(label))
  2224. {
  2225. keyValuePairs.Add(label, 1);
  2226. }
  2227. }
  2228. }
  2229. labelMat.ForEachAsInt32(CommonForEachDel);
  2230. //寻找连通分量
  2231. labelMat = new Mat();
  2232. stats = new Mat();
  2233. centroids = new Mat();
  2234. nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2235. //Mat oo = temp_ap.Clone();
  2236. //Mat respend = new Mat();
  2237. //temp_view.ConvertTo(respend, MatType.CV_8UC3);
  2238. //OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2239. //HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2240. //Cv2.FindContours(oo, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2241. //for (int i = 0; i < contours.Length; i++)
  2242. //{
  2243. // double art = Cv2.ContourArea(contours[i]);
  2244. // if (art < 50)
  2245. // continue;
  2246. // if (contours[i][0].Y > oo.Height - border)
  2247. // {
  2248. // respend.DrawContours(contours, i, Scalar.Black, -1);
  2249. // continue;
  2250. // }
  2251. // respend.DrawContours(contours, i, Scalar.RandomColor(), -1);
  2252. //}
  2253. //using (new Window("s", WindowMode.Normal, respend))
  2254. //{
  2255. // Cv2.WaitKey(0);
  2256. //}
  2257. //Cv2.ImWrite("E://tt.jpg", respend);
  2258. AllFields = new List<List<OpenCvSharp.Point>>();
  2259. for (int i = 0; i < centroids.Height; i++)
  2260. {
  2261. AllFields.Add(new List<OpenCvSharp.Point>());
  2262. }
  2263. labelMat.ForEachAsInt32(CommonForEachForCon);
  2264. //寻找在范围内需要删除的碎屑
  2265. keyValuePairs.Clear();
  2266. keyValueSel.Clear();
  2267. for (int i = 0; i < circleCount; i++)
  2268. {
  2269. poAreaList.Add(0);
  2270. }
  2271. ////旧的删除方式
  2272. //if (delPointFs != null && delPointFs.Count > 0)
  2273. //{
  2274. // for (int i = 0; i < delPointFs.Count; i++)
  2275. // {
  2276. // int qx = (int)delPointFs[i].X;
  2277. // int qy = (int)delPointFs[i].Y;
  2278. // int label = labelMat.At<int>(qy, qx);
  2279. // if (label > 0 && !keyValuePairs.ContainsKey(label))
  2280. // {
  2281. // keyValuePairs.Add(label, 1);
  2282. // }
  2283. // }
  2284. //}
  2285. List<RotatedRect> rectList = new List<RotatedRect>();
  2286. List<List<OpenCvSharp.Point>> rectListPoint = new List<List<OpenCvSharp.Point>>();
  2287. for (int h = 1; h < centroids.Height; h++)
  2288. {
  2289. int areaField1 = stats.At<int>(h, 4);
  2290. int x = stats.At<int>(h, 0);
  2291. int y = stats.At<int>(h, 1);
  2292. int width = stats.At<int>(h, 2);
  2293. int height = stats.At<int>(h, 3);
  2294. if (keyValuePairs.ContainsKey(h))
  2295. {
  2296. continue;
  2297. }
  2298. if (Contour != null && Contour.Count > 0)
  2299. {
  2300. OpenCvSharp.Point p1 = new OpenCvSharp.Point(x, y);
  2301. double d = Cv2.PointPolygonTest(Contour, p1, false);
  2302. if (d < 0)
  2303. {
  2304. keyValuePairs.Add(h, 1);
  2305. continue;
  2306. }
  2307. p1 = new OpenCvSharp.Point(x + width, y);
  2308. d = Cv2.PointPolygonTest(Contour, p1, false);
  2309. if (d < 0)
  2310. {
  2311. keyValuePairs.Add(h, 1);
  2312. continue;
  2313. }
  2314. p1 = new OpenCvSharp.Point(x + width, y + height);
  2315. d = Cv2.PointPolygonTest(Contour, p1, false);
  2316. if (d < 0)
  2317. {
  2318. keyValuePairs.Add(h, 1);
  2319. continue;
  2320. }
  2321. p1 = new OpenCvSharp.Point(x, y + height);
  2322. d = Cv2.PointPolygonTest(Contour, p1, false);
  2323. if (d < 0)
  2324. {
  2325. keyValuePairs.Add(h, 1);
  2326. continue;
  2327. }
  2328. }
  2329. //边缘
  2330. if (x < border || x + width > src.Cols - border || y < border || y + height > src.Rows - border - borderBottom)
  2331. {
  2332. keyValuePairs.Add(h, 1);
  2333. }
  2334. else if (areaField1 > src.Rows * src.Cols * 0.3)//面积最大的是轮廓,这里算大于整体面积的0.3
  2335. {
  2336. keyValuePairs.Add(h, 1);
  2337. maxArea = areaField1;
  2338. }
  2339. else
  2340. {
  2341. poArea += areaField1;
  2342. Mat t = new Mat(temp_ap, new Rect(x, y, width, height));
  2343. int maxxx = 0; int maxyy = 0;
  2344. int inde = h - 1;
  2345. RotatedRect rectR = Cv2.MinAreaRect(AllFields[inde]);
  2346. if (maxxx < rectR.Size.Width)
  2347. {
  2348. maxxx = (int)rectR.Size.Width;
  2349. }
  2350. if (maxyy < rectR.Size.Height)
  2351. {
  2352. maxyy = (int)rectR.Size.Height;
  2353. }
  2354. double kgr = Convert.ToDouble(maxxx + maxyy) * 0.5 * Micron;
  2355. double hlengh = maxxx > maxyy ? maxxx : maxyy;
  2356. double wlengh = maxxx < maxyy ? maxxx : maxyy;
  2357. double area = maxxx * maxyy * AreaRatio;
  2358. InputArray contoursAll = InputArray.Create(AllFields[inde]);
  2359. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2360. OutputArray hull = OutputArray.Create(outArr);
  2361. Cv2.ConvexHull(contoursAll, hull, true);
  2362. area = Cv2.ContourArea(outArr) * AreaRatio;
  2363. if (wlengh > 0)
  2364. {
  2365. double hm = hlengh / wlengh;
  2366. //颗粒尺寸超长
  2367. if (kgr < pointsize)
  2368. {
  2369. keyValuePairs.Add(h, 1);
  2370. }
  2371. else if (hm > HW)//长宽比过大
  2372. {
  2373. keyValuePairs.Add(h, 1);
  2374. }
  2375. else if (areaField1 < area)
  2376. {
  2377. keyValuePairs.Add(h, 1);
  2378. }
  2379. //正常颗粒
  2380. else
  2381. {
  2382. ////圆润度
  2383. //hindex = h;
  2384. //ground = temp_ap.Clone();
  2385. //labelMat.ForEachAsInt32(CommonForEachForArc);
  2386. //double roundness= GetRoundness2(width, height, x, y);
  2387. //double c = contours[0].Length; //轮廓周长
  2388. //double xa = Math.Sqrt(areaField1 / Math.PI) * 2;
  2389. //double xp = c / Math.PI;
  2390. //int aa = Convert.ToInt32((xa / xp) * 1000);
  2391. double nc = Cv2.ArcLength(outArr.ToArray(), true) ;
  2392. double na = Math.Sqrt(areaField1 / Math.PI) * 2;
  2393. int aa = Convert.ToInt32((na / nc) * 1000);
  2394. List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
  2395. Point2f[] point2F = rectR.Points();
  2396. foreach (var item in point2F)
  2397. {
  2398. listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
  2399. }
  2400. rectListPoint.Add(listpoint);
  2401. rectList.Add(rectR);
  2402. List<int> po = new List<int>() { x, y, width, height, areaField1, h, maxxx, maxyy, 1 , (int)nc };
  2403. poList.Add(po);
  2404. }
  2405. }
  2406. else
  2407. {
  2408. keyValuePairs.Add(h, 1);
  2409. }
  2410. }
  2411. }
  2412. labelMatForSel = labelMat;
  2413. fieldsCount = centroids.Height;
  2414. labelMat.ForEachAsInt32(CommonForEachForInt32);
  2415. labelMat.ForEachAsInt32(CommonForEachForSel);
  2416. #region 添加颗粒
  2417. Mat MatAdd = new Mat(src.Rows, src.Cols, MatType.CV_8UC1,new Scalar(0));
  2418. if (AddPontins != null && AddPontins.Count > 0)
  2419. {
  2420. for (int i = 0; i < AddPontins.Count; i++)
  2421. {
  2422. Cv2.DrawContours(MatAdd, AddPontins, i, new Scalar(255), -1);
  2423. Cv2.DrawContours(rgb_ap, AddPontins, i,new Scalar( vec4B.Item0, vec4B.Item1, vec4B.Item2), -1);
  2424. Cv2.DrawContours(temp_ap, AddPontins, i, new Scalar(255), -1);
  2425. }
  2426. // Cv2.DrawContours(src, AddPontins, -1, new Scalar(255, 255, 255, 255), -1);
  2427. }
  2428. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2429. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2430. //轮廓
  2431. Cv2.FindContours(MatAdd, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2432. labelMatForSelAdd = contours;
  2433. for (int i = 0; i < contours.Length; i++)
  2434. {
  2435. Rect rect = Cv2.BoundingRect(contours[i]);
  2436. int areaField1 =Convert.ToInt32( Cv2.ContourArea(contours[i]));
  2437. int nc = Convert.ToInt32(Cv2.ArcLength(contours[i], true));
  2438. int x = rect.X;
  2439. int y = rect.Y;
  2440. int width = rect.Width;
  2441. int height = rect.Height;
  2442. int maxxx = 0; int maxyy = 0;
  2443. RotatedRect rectR = Cv2.MinAreaRect(contours[i]);
  2444. if (maxxx < rectR.Size.Width)
  2445. {
  2446. maxxx = (int)rectR.Size.Width;
  2447. }
  2448. if (maxyy < rectR.Size.Height)
  2449. {
  2450. maxyy = (int)rectR.Size.Height;
  2451. }
  2452. List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
  2453. Point2f[] point2F = rectR.Points();
  2454. foreach (var item in point2F)
  2455. {
  2456. listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
  2457. }
  2458. rectListPoint.Add(listpoint);
  2459. rectList.Add(rectR);
  2460. List<int> po = new List<int>() { x, y, width, height, areaField1, centroids.Height+i, maxxx, maxyy, 1 , nc };
  2461. poList.Add(po);
  2462. }
  2463. //using (new Window("s", WindowMode.Normal, src))
  2464. //{
  2465. // Cv2.WaitKey(0);
  2466. //}
  2467. #endregion
  2468. //合并rgb和透明度
  2469. Mat[] mats = rgb_ap.Split();
  2470. arr[0] = mats[0];
  2471. arr[1] = mats[1];
  2472. arr[2] = mats[2];
  2473. arr[3] = temp_ap;
  2474. Cv2.Merge(arr, src);
  2475. Scalar scalar = new Scalar(255, 255, 255, 255);
  2476. if (isDis)
  2477. {
  2478. foreach (var p in rectList)
  2479. {
  2480. Point2f[] point2F = p.Points();
  2481. double width = (point2F[0].X - point2F[1].X) / 2;
  2482. double height = (point2F[0].Y - point2F[1].Y) / 2;
  2483. OpenCvSharp.Point p1 = new OpenCvSharp.Point(point2F[1].X + width, point2F[1].Y + height);
  2484. OpenCvSharp.Point p2 = new OpenCvSharp.Point(point2F[2].X + width, point2F[2].Y + height);
  2485. src.Line(p1, p2, scalar, 1);
  2486. int wid = (int)p.Size.Width;
  2487. double d1= wid* Micron;
  2488. src.PutText(Math.Round(d1, 2).ToString(), p2, HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0, 255), 1);
  2489. width = (point2F[3].X - point2F[0].X) / 2;
  2490. height = (point2F[0].Y - point2F[3].Y) / 2;
  2491. OpenCvSharp.Point p3 = new OpenCvSharp.Point(point2F[0].X + width, point2F[3].Y + height);
  2492. OpenCvSharp.Point p4 = new OpenCvSharp.Point(point2F[1].X + width, point2F[2].Y + height);
  2493. src.Line(p3, p4, scalar, 1);
  2494. int hei = (int)p.Size.Height;
  2495. double d2 = hei * Micron;
  2496. src.PutText(Math.Round(d2, 2).ToString(), p3, HersheyFonts.HersheyPlain, 1, new Scalar(0, 0, 255, 255), 1);
  2497. }
  2498. }
  2499. if (isJu)
  2500. {
  2501. src.DrawContours(rectListPoint, -1, scalar, 1);
  2502. }
  2503. return src;
  2504. }
  2505. /// <summary>
  2506. /// 单晶删除颗粒
  2507. /// </summary>
  2508. /// <param name="src"></param>
  2509. /// <returns></returns>
  2510. private static Mat DebrisRemoval_Cryst_Del(Mat src)
  2511. {
  2512. temp_ap = src.CvtColor(ColorConversionCodes.BGR2GRAY);
  2513. using (new Window("s", WindowMode.Normal, temp_ap))
  2514. {
  2515. Cv2.WaitKey(0);
  2516. }
  2517. //寻找连通分量
  2518. Mat labelMat = new Mat();
  2519. Mat stats = new Mat();
  2520. Mat centroids = new Mat();
  2521. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2522. //寻找在范围内需要删除的碎屑
  2523. keyValuePairs.Clear();
  2524. if (delPointFs != null && delPointFs.Count > 0)
  2525. {
  2526. for (int i = 0; i < delPointFs.Count; i++)
  2527. {
  2528. int qx = (int)delPointFs[i].X;
  2529. int qy = (int)delPointFs[i].Y;
  2530. int label = labelMat.At<int>(qy, qx);
  2531. if (label > 0 && !keyValuePairs.ContainsKey(label))
  2532. {
  2533. keyValuePairs.Add(label, 1);
  2534. }
  2535. }
  2536. }
  2537. labelMat.ForEachAsInt32(CommonForEachDel);
  2538. return temp_ap.Clone();
  2539. }
  2540. private static void CommonForEachDel(int* value, int* position)
  2541. {
  2542. int y = position[0];
  2543. int x = position[1];
  2544. int v = *value;
  2545. if (v > 0 && keyValuePairs.ContainsKey(v))
  2546. {
  2547. temp_ap.Set<int>(y, x, 0);
  2548. }
  2549. }
  2550. //寻找角点做角曲率
  2551. private static double GetRoundness1(int width, int height, int x, int y)
  2552. {
  2553. OpenCvSharp.Point core = new OpenCvSharp.Point();
  2554. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2555. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2556. Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2557. Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
  2558. double dist = 0;
  2559. double maxdist = 0;
  2560. for (int i = 0; i < width; i++)
  2561. {
  2562. for (int j = 0; j < height; j++)
  2563. {
  2564. OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
  2565. dist = Cv2.PointPolygonTest(contours[0], point, true);
  2566. if (dist > maxdist)
  2567. {
  2568. maxdist = dist;
  2569. core = point;
  2570. }
  2571. }
  2572. }
  2573. Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
  2574. double roundness = 0;
  2575. //寻找角点
  2576. InputArray contoursAll = InputArray.Create(contours[0]);
  2577. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2578. OutputArray hull = OutputArray.Create(outArr);
  2579. Cv2.ConvexHull(contoursAll, hull, true);
  2580. Point2f[] cornersPoint = Cv2.GoodFeaturesToTrack(ground, 100, 0.01, 30, new Mat(), 7, false, 0.04);
  2581. foreach (var item in cornersPoint)
  2582. {
  2583. Cv2.Circle(ground, Convert.ToInt16(item.X), Convert.ToInt16(item.Y), 10, Scalar.White, 2);
  2584. int index = contours[0].ToList().FindIndex(u => Math.Abs(u.X - item.X) < 3 && Math.Abs(u.Y - item.Y) < 3);
  2585. List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
  2586. list.Add(item);
  2587. int nv = 10;
  2588. if (index > nv)
  2589. {
  2590. list.Add(contours[0][index - nv]);
  2591. }
  2592. else
  2593. {
  2594. int ind = nv - index;
  2595. list.Add(contours[0][contours[0].Length - nv - 1]);
  2596. }
  2597. if (index + nv < contours[0].Length)
  2598. {
  2599. list.Add(contours[0][index + nv]);
  2600. }
  2601. else
  2602. {
  2603. list.Add(contours[0][index + nv - contours[0].Length]);
  2604. }
  2605. double dis1, dis2, dis3;
  2606. double cosA, sinA, dis;
  2607. OpenCvSharp.Point2f P1 = list[0];
  2608. OpenCvSharp.Point2f P2 = list[1];
  2609. OpenCvSharp.Point2f P3 = list[2];
  2610. dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
  2611. dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
  2612. dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
  2613. dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
  2614. cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
  2615. sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
  2616. double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
  2617. curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
  2618. roundness += curvity;
  2619. }
  2620. double ri = roundness / maxdist;
  2621. ri = ri / cornersPoint.Length;
  2622. using (new Window("ss", WindowMode.Normal, ground))
  2623. {
  2624. Cv2.WaitKey(0);
  2625. }
  2626. return ri;
  2627. }
  2628. //寻找凸包做角曲率
  2629. private static double GetRoundness2(int width, int height, int x, int y)
  2630. {
  2631. OpenCvSharp.Point core = new OpenCvSharp.Point();
  2632. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2633. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2634. Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2635. Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
  2636. double dist = 0;
  2637. double maxdist = 0;
  2638. for (int i = 0; i < width; i++)
  2639. {
  2640. for (int j = 0; j < height; j++)
  2641. {
  2642. OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
  2643. dist = Cv2.PointPolygonTest(contours[0], point, true);
  2644. if (dist > maxdist)
  2645. {
  2646. maxdist = dist;
  2647. core = point;
  2648. }
  2649. }
  2650. }
  2651. //寻找角点
  2652. InputArray contoursAll = InputArray.Create(contours[0]);
  2653. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2654. OutputArray hull = OutputArray.Create(outArr);
  2655. Cv2.ConvexHull(contoursAll, hull, true);
  2656. //内切圆
  2657. Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
  2658. double roundness = 0;
  2659. Cv2.DrawContours(open, new List<List<OpenCvSharp.Point>>() { outArr }, 0, Scalar.White, 2);
  2660. for (int i = 0; i < outArr.Count(); i++)
  2661. {
  2662. Point2f item = outArr[i];
  2663. List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
  2664. list.Add(item);
  2665. if (i == 0)
  2666. {
  2667. list.Add(outArr[outArr.Count() - 1]);
  2668. }
  2669. else
  2670. {
  2671. list.Add(outArr[i - 1]);
  2672. }
  2673. if (i == (outArr.Count() - 1))
  2674. {
  2675. list.Add(outArr[0]);
  2676. }
  2677. else
  2678. {
  2679. list.Add(outArr[i + 1]);
  2680. }
  2681. double dis1, dis2, dis3;
  2682. double cosA, sinA, dis;
  2683. OpenCvSharp.Point2f P1 = list[0];
  2684. OpenCvSharp.Point2f P2 = list[1];
  2685. OpenCvSharp.Point2f P3 = list[2];
  2686. dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
  2687. dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
  2688. dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
  2689. dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
  2690. cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
  2691. sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
  2692. double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
  2693. curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
  2694. roundness += curvity;
  2695. }
  2696. double ri = roundness / maxdist;
  2697. ri = ri / outArr.Count();
  2698. using (new Window("open", WindowMode.Normal, open))
  2699. using (new Window("ss", WindowMode.Normal, ground))
  2700. {
  2701. Cv2.WaitKey(0);
  2702. }
  2703. return ri;
  2704. }
  2705. private static readonly object locker = new object();
  2706. //获取连通域点
  2707. private static void CommonForEachForCon(int* value, int* position)
  2708. {
  2709. int y = position[0];
  2710. int x = position[1];
  2711. int v = *value;
  2712. if (v > 0)
  2713. {
  2714. try
  2715. {
  2716. lock (locker)
  2717. {
  2718. AllFields[v - 1].Add(new OpenCvSharp.Point(x, y));
  2719. }
  2720. }
  2721. catch (Exception e)
  2722. {
  2723. throw;
  2724. }
  2725. }
  2726. }
  2727. private static void CommonForEachForArc(int* value, int* position)
  2728. {
  2729. int y = position[0];
  2730. int x = position[1];
  2731. int v = *value;
  2732. if (v > 0 && hindex != v)
  2733. {
  2734. ground.Set<int>(y, x, 0);
  2735. }
  2736. }
  2737. /// <summary>
  2738. /// 单晶Canny去噪点
  2739. /// </summary>
  2740. /// <param name="src"></param>
  2741. /// <returns></returns>
  2742. private static Mat DebrisRemoval_CrystCanny(Mat src)
  2743. {
  2744. temp_ap = src;
  2745. //寻找连通分量
  2746. Mat labelMat = new Mat();
  2747. Mat stats = new Mat();
  2748. Mat centroids = new Mat();
  2749. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2750. //寻找在范围内需要删除的碎屑
  2751. keyValuePairs.Clear();
  2752. for (int h = 1; h < centroids.Height; h++)
  2753. {
  2754. int areaField1 = stats.At<int>(h, 4);
  2755. int x = stats.At<int>(h, 0);
  2756. int y = stats.At<int>(h, 1);
  2757. int width = stats.At<int>(h, 2);
  2758. int height = stats.At<int>(h, 3);
  2759. //面积小于30的孔隙删除
  2760. if (areaField1 <= 500)
  2761. {
  2762. keyValuePairs.Add(h, 1);
  2763. }
  2764. }
  2765. labelMatForSel = labelMat;
  2766. labelMat.ForEachAsInt32(CommonForEachForInt32_CrystCanny);
  2767. return temp_ap;
  2768. }
  2769. private static void CommonForEachForInt32_CrystCanny(int* value, int* position)
  2770. {
  2771. int y = position[0];
  2772. int x = position[1];
  2773. int v = *value;
  2774. if (v > 0 && keyValuePairs.ContainsKey(v))
  2775. {
  2776. temp_ap.Set<int>(y, x, 0);
  2777. }
  2778. }
  2779. #endregion
  2780. #region 有视场 二值提取
  2781. /// <summary>
  2782. /// 二值操作-二值提取-有视场
  2783. /// </summary>
  2784. /// <param name="src">视场mat</param>
  2785. /// <param name="mat">原图mat</param>
  2786. /// <param name="lists">参数列表</param>
  2787. /// <returns></returns>
  2788. public static Mat ImageBinaryExtraction(Mat source, Mat mat, List<Args> lists, bool findContours = false)
  2789. {
  2790. //以下是参数信息---------------------
  2791. ///1个颜色区间还是2个
  2792. colorInterval = 1;
  2793. //第一个二值区间
  2794. colorOneStart = 0;
  2795. colorOneEnd = 0;
  2796. //第二个二值区间
  2797. colorTwoStart = 0;
  2798. colorTwoEnd = 0;
  2799. //第三个二值区间
  2800. colorThreeStart = 0;
  2801. colorThreeEnd = 0;
  2802. //处理细节
  2803. //删除边界对象
  2804. bool deleteBoundaryObject = false;
  2805. //孔洞填充
  2806. bool holeFilling = false;
  2807. //碎屑删除
  2808. bool debrisRemoval = false;
  2809. //碎屑删除面积起
  2810. debrisAreaStart = 0;
  2811. //碎屑删除面积止
  2812. debrisAreaEnd = 0;
  2813. //二值样式
  2814. //1实心 2边线
  2815. int binaryStyle = 0;
  2816. //相颜色
  2817. Color phaseColor = Color.Red;
  2818. //目标选择
  2819. int targetSelection = 1;
  2820. for (int i = 0; i < lists.Count; i++)
  2821. {
  2822. Args args = lists[i];
  2823. switch (args.Key)
  2824. {
  2825. case "colorInterval":
  2826. {
  2827. if (args.Value is Boolean)
  2828. colorInterval = (Boolean)args.Value ? 2 : 1;
  2829. else
  2830. colorInterval = (int)args.Value;
  2831. }
  2832. break;
  2833. case "scope1":
  2834. colorOneStart = (int)((List<double>)args.Value)[0];
  2835. colorOneEnd = (int)((List<double>)args.Value)[1];
  2836. break;
  2837. case "scope2":
  2838. colorTwoStart = (int)((List<double>)args.Value)[0];
  2839. colorTwoEnd = (int)((List<double>)args.Value)[1];
  2840. break;
  2841. case "scope3":
  2842. colorThreeStart = (int)((List<double>)args.Value)[0];
  2843. colorThreeEnd = (int)((List<double>)args.Value)[1];
  2844. break;
  2845. case "deleteBoundaryObject":
  2846. deleteBoundaryObject = (bool)args.Value;
  2847. break;
  2848. case "holeFilling":
  2849. holeFilling = (bool)args.Value;
  2850. break;
  2851. case "debrisRemoval":
  2852. debrisRemoval = (bool)args.Value;
  2853. break;
  2854. case "binaryStyle":
  2855. binaryStyle = (int)args.Value;
  2856. break;
  2857. case "phaseColor":
  2858. phaseColor = Color.FromArgb((int)args.Value);
  2859. break;
  2860. case "targetSelection":
  2861. targetSelection = (int)args.Value;
  2862. break;
  2863. case "scope4":
  2864. debrisAreaStart = (int)((List<double>)args.Value)[0];
  2865. debrisAreaEnd = (int)((List<double>)args.Value)[1];
  2866. break;
  2867. default:
  2868. break;
  2869. }
  2870. }
  2871. vec4B.Item0 = phaseColor.B;
  2872. vec4B.Item1 = phaseColor.G;
  2873. vec4B.Item2 = phaseColor.R;
  2874. vec4B.Item3 = phaseColor.A;
  2875. //二值提取
  2876. Mat src = BinarizationWithView(source);
  2877. //目标选择
  2878. if (targetSelection != 2)
  2879. src = CalcContoursByTargetSelection_New(temp_view, targetSelection, source);
  2880. //碎屑删除,参考冈萨雷斯,414,9.5.3,连通分量提取
  2881. if (debrisRemoval && debrisAreaEnd > 0)
  2882. src = DebrisRemoval_NewWithView(src);
  2883. //孔洞填充,参考冈萨雷斯,413,9.5.2
  2884. if (holeFilling)
  2885. src = HoleFilling_NewWithView(src);
  2886. //实心/边线,参考冈萨雷斯,412,9.5.1,边界提取
  2887. if (binaryStyle == 2)
  2888. {
  2889. Cv2.Erode(src, temp, null);
  2890. src = src - temp;
  2891. src = BaseTools.MergeMatFromMatArr(src, vec4B);
  2892. }
  2893. return src;
  2894. }
  2895. /// <summary>
  2896. /// 二值提取
  2897. /// </summary>
  2898. /// <param name="source">视场图像</param>
  2899. /// <param name="mat">原图像</param>
  2900. /// <param name="colorInterval">1个或2个颜色区间</param>
  2901. /// <param name="colorOneStart"></param>
  2902. /// <param name="colorOneEnd"></param>
  2903. /// <param name="colorTwoStart"></param>
  2904. /// <param name="colorTwoEnd"></param>
  2905. /// <param name="colorThreeStart"></param>
  2906. /// <param name="colorThreeEnd"></param>
  2907. /// <param name="phaseColor">相颜色</param>
  2908. /// <returns></returns>
  2909. private static Mat BinarizationWithView(Mat source)
  2910. {
  2911. Mat[] arr = source.Split();
  2912. alpha = arr[3];
  2913. Mat srcGray;
  2914. if (source.Type() == MatType.CV_8UC1)
  2915. {
  2916. srcGray = source;
  2917. }
  2918. else
  2919. {
  2920. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  2921. }
  2922. temp_view = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  2923. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  2924. srcGray.ForEachAsByte(GrayForEachAsByteWithView);
  2925. return temp.Clone();
  2926. }
  2927. /// <summary>
  2928. /// 并行循环
  2929. /// </summary>
  2930. /// <param name="value"></param>
  2931. /// <param name="position"></param>
  2932. private static void GrayForEachAsByteWithView(byte* value, int* position)
  2933. {
  2934. int y = position[0];
  2935. int x = position[1];
  2936. byte v = *value;
  2937. if (colorInterval == 1)
  2938. {
  2939. if (v >= colorOneStart && v <= colorOneEnd)
  2940. {
  2941. if (alpha.At<byte>(y, x) > 0)
  2942. {
  2943. temp.Set<Vec4b>(y, x, vec4B);
  2944. temp_view.Set<Vec4b>(y, x, vec4B);
  2945. }
  2946. else
  2947. {
  2948. temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
  2949. }
  2950. }
  2951. }
  2952. else
  2953. {
  2954. if (((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd)))
  2955. {
  2956. if (alpha.At<byte>(y, x) > 0)
  2957. {
  2958. temp.Set<Vec4b>(y, x, vec4B);
  2959. temp_view.Set<Vec4b>(y, x, vec4B);
  2960. }
  2961. else
  2962. {
  2963. temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
  2964. }
  2965. }
  2966. }
  2967. }
  2968. /// <summary>
  2969. /// 新碎屑删除,使用连通分量找寻碎屑
  2970. /// </summary>
  2971. /// <param name="src"></param>
  2972. /// <returns></returns>
  2973. private static Mat DebrisRemoval_NewWithView(Mat src)
  2974. {
  2975. Mat[] arr = src.Split();
  2976. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  2977. temp_ap = arr[3].Clone();
  2978. //寻找连通分量
  2979. Mat labelMat = new Mat();
  2980. Mat stats = new Mat();
  2981. Mat centroids = new Mat();
  2982. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2983. //寻找在范围内需要删除的碎屑
  2984. keyValuePairs.Clear();
  2985. for (int h = 1; h < centroids.Height; h++)
  2986. {
  2987. int areaField1 = stats.At<int>(h, 4);
  2988. if (debrisAreaStart <= areaField1 && areaField1 <= debrisAreaEnd)
  2989. {
  2990. keyValuePairs.Add(h, 1);
  2991. }
  2992. }
  2993. labelMat.ForEachAsInt32(CommonForEachForInt32);
  2994. //合并rgb和透明度
  2995. Mat[] mats = rgb_ap.Split();
  2996. arr[0] = mats[0];
  2997. arr[1] = mats[1];
  2998. arr[2] = mats[2];
  2999. arr[3] = temp_ap;
  3000. Cv2.Merge(arr, src);
  3001. return src;
  3002. }
  3003. /// <summary>
  3004. /// 新孔洞填充,采用形态学填充
  3005. /// </summary>
  3006. /// <param name="src"></param>
  3007. /// <returns></returns>
  3008. private static Mat HoleFilling_NewWithView(Mat src)
  3009. {
  3010. Mat[] arr2 = src.Split();
  3011. Mat tempc = arr2[3];
  3012. //去掉透明层
  3013. Mat mat = src.CvtColor(ColorConversionCodes.BGRA2BGR);
  3014. //填充孔洞
  3015. mat = BaseTools.FillHole(mat, new Scalar(255 - vec4B.Item0, 255 - vec4B.Item1, 255 - vec4B.Item2));
  3016. tempc = BaseTools.FillHole(tempc, new Scalar(255));
  3017. //循环处理
  3018. mat.ForEachAsVec3b(RGBForEachAsByteForHoleFillingNewWithView);
  3019. Mat[] arr1 = mat.Split();
  3020. arr2[0] = arr1[0];
  3021. arr2[1] = arr1[1];
  3022. arr2[2] = arr1[2];
  3023. arr2[3] = tempc;
  3024. Cv2.Merge(arr2, src);
  3025. return src;
  3026. }
  3027. private static void RGBForEachAsByteForHoleFillingNewWithView(Vec3b* value, int* position)
  3028. {
  3029. int y = position[0];
  3030. int x = position[1];
  3031. if (value->Item0 == 255 && value->Item1 == 255 && value->Item2 == 255)
  3032. {
  3033. value->Item0 = vec4B.Item0;
  3034. value->Item1 = vec4B.Item1;
  3035. value->Item2 = vec4B.Item2;
  3036. }
  3037. }
  3038. /// <summary>
  3039. /// 目标选择
  3040. /// </summary>
  3041. /// <param name="src"></param>
  3042. /// <param name="mat"></param>
  3043. /// <param name="targetSelection"></param>
  3044. /// <param name="source"></param>
  3045. /// <returns></returns>
  3046. public static Mat CalcContoursByTargetSelection_New(Mat src, int targetSelection, Mat source)
  3047. {
  3048. Mat[] arr = src.Split();
  3049. alpha = arr[3].Clone();
  3050. Mat rgb = BaseTools.MergeMatFromMatArr(arr);
  3051. Mat alphatemp = arr[3].Clone();
  3052. Mat mask = Mat.Zeros(rgb.Rows + 2, rgb.Cols + 2, MatType.CV_8UC1);
  3053. //考虑循环填充,填充视场的透明层和原图的透明层,然后比较填充区域的大小
  3054. //但是循环的时候需要少循环像素,可以处理视场的透明层,减少循环量
  3055. //同时记录种子点,然后根据targetSelection判断是填充透明还是不透明
  3056. Mat rgbClone = rgb.Clone();
  3057. List<OpenCvSharp.Point> points = new List<OpenCvSharp.Point>();
  3058. for (int h = 0; h < alphatemp.Height; h++)
  3059. {
  3060. for (int w = 0; w < alphatemp.Width; w++)
  3061. {
  3062. int v = alphatemp.At<byte>(h, w);
  3063. if (v > 0)
  3064. {
  3065. int a = Cv2.FloodFill(alphatemp, new OpenCvSharp.Point(w, h), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  3066. int b = Cv2.FloodFill(rgbClone, new OpenCvSharp.Point(w, h), new Scalar(0, 0, 0), out rect, null, null, FloodFillFlags.Link8);
  3067. if (a != b)
  3068. {
  3069. points.Add(new OpenCvSharp.Point(w, h));
  3070. }
  3071. }
  3072. }
  3073. }
  3074. if (points.Count > 0)
  3075. {
  3076. foreach (OpenCvSharp.Point p in points)
  3077. {
  3078. if (targetSelection == 1)
  3079. {
  3080. Cv2.FloodFill(alpha, p, new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  3081. }
  3082. else if (targetSelection == 3)
  3083. {
  3084. Cv2.FloodFill(rgb, mask, p, new Scalar(vec4B.Item0, vec4B.Item1, vec4B.Item2), out rect, null, null, FloodFillFlags.Link8);
  3085. }
  3086. }
  3087. }
  3088. if (targetSelection == 3)
  3089. {
  3090. Mat t = new Mat(mask, new Rect(1, 1, rgb.Width, rgb.Height));
  3091. alpha = alpha + t * 255;
  3092. }
  3093. //合并rgb和透明度
  3094. Mat[] mats = rgb.Split();
  3095. arr[0] = mats[0];
  3096. arr[1] = mats[1];
  3097. arr[2] = mats[2];
  3098. arr[3] = alpha;
  3099. Cv2.Merge(arr, src);
  3100. return src;
  3101. }
  3102. #endregion
  3103. private static void CommonForEachForInt32(int* value, int* position)
  3104. {
  3105. int y = position[0];
  3106. int x = position[1];
  3107. int v = *value;
  3108. if (v > 0 && keyValuePairs.ContainsKey(v))
  3109. {
  3110. rgb_ap.Set<Vec3b>(y, x, new Vec3b(0, 0, 0));
  3111. temp_ap.Set<int>(y, x, 0);
  3112. //手动画圆
  3113. if (ListRadiusColor.Count > 0)
  3114. {
  3115. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  3116. if (ListRadiusColor.Count > 1)
  3117. {
  3118. for (int i = 0; i < ListRadiusColor.Count - 1; i++)
  3119. {
  3120. int r = i == 0 ? 0 : ListRadiusColor.ElementAt(ListRadiusColor.Count - i).Key;
  3121. int r2 = ListRadiusColor.ElementAt(ListRadiusColor.Count - 1 - i).Key;
  3122. if (r < d && d <= r2)
  3123. {
  3124. poAreaList[i]--;
  3125. break;
  3126. }
  3127. }
  3128. }
  3129. }
  3130. else if (circleCount > 1)
  3131. {
  3132. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  3133. for (int i = 0; i < circleCount; i++)
  3134. {
  3135. int r = Convert.ToInt32(CircleR * (i));
  3136. int r2 = Convert.ToInt32(CircleR * (i + 1));
  3137. if (r < d && d <= r2)
  3138. {
  3139. poAreaList[i]--;
  3140. break;
  3141. }
  3142. }
  3143. }
  3144. }
  3145. }
  3146. private static void CommonForEachForSel(int* value, int* position)
  3147. {
  3148. int y = position[0];
  3149. int x = position[1];
  3150. int v = *value;
  3151. if (v > 0 && keyValueSel.ContainsKey(v))
  3152. {
  3153. rgb_ap.Set<Vec3b>(y, x, new Vec3b(255, 255, 0));
  3154. }
  3155. }
  3156. /// <summary>
  3157. /// 开裂球识别霍夫圆
  3158. /// </summary>
  3159. /// <param name="src"></param>
  3160. public static Mat DrwCrackBall(Mat src)
  3161. {
  3162. temp = src.Clone();
  3163. Mat dst = new Mat();
  3164. //1:因为霍夫圆检测对噪声比较敏感,所以首先对图像做一个中值滤波或高斯滤波(噪声如果没有可以不做)
  3165. Mat m1 = new Mat();
  3166. Cv2.MedianBlur(temp, m1, 3); // ksize必须大于1且是奇数
  3167. //2:转为灰度图像
  3168. Mat m2 = m1.Clone();
  3169. // m1.Release();
  3170. Cv2.CvtColor(m1, m2, ColorConversionCodes.BGR2GRAY);
  3171. CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 130, 60, 25, 35, 80);
  3172. temp.CopyTo(dst);
  3173. //大圆
  3174. for (int i = 0; i < cs.Length; i++)
  3175. {
  3176. //画圆
  3177. Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias);
  3178. //加强圆心显示
  3179. Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias);
  3180. }
  3181. Mat srcBlack;
  3182. int sucessCs = 0;
  3183. int badCs = 0;
  3184. for (int i = 0; i < cs.Length; i++)
  3185. {
  3186. int left = (int)cs[i].Center.X - (int)cs[i].Radius;
  3187. int right = (int)cs[i].Center.X + (int)cs[i].Radius;
  3188. int top = (int)cs[i].Center.Y - (int)cs[i].Radius;
  3189. int bottom = (int)cs[i].Center.Y + (int)cs[i].Radius;
  3190. if (left < 10 || right - 10 > temp.Width || top < 10 || bottom - 10 > temp.Height - 140)
  3191. {
  3192. continue;
  3193. }
  3194. srcBlack = new Mat(temp.Height, temp.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3195. //画圆
  3196. Cv2.Circle(srcBlack, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, Scalar.White, 1, LineTypes.AntiAlias);
  3197. OpenCvSharp.Point[][] contours;
  3198. HierarchyIndex[] hierarchy;
  3199. Cv2.FindContours(srcBlack, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3200. Cv2.DrawContours(srcBlack, contours, -1, Scalar.White, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3201. //取所有的点
  3202. List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
  3203. int rows = srcBlack.Height, cols = srcBlack.Width;
  3204. for (int k = 0; k < rows; k++)
  3205. {
  3206. IntPtr a = srcBlack.Ptr(k);
  3207. byte* b = (byte*)a.ToPointer();
  3208. for (int j = 0; j < cols; j++)
  3209. {
  3210. if (b[j] != 0)
  3211. {
  3212. srPoints.Add(new OpenCvSharp.Point(j, k));
  3213. }
  3214. }
  3215. }
  3216. for (int j = 0; j < srPoints.Count; j++)
  3217. {
  3218. int item = temp.Get<int>(srPoints[j].Y, srPoints[j].X);
  3219. srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
  3220. }
  3221. Rect bigrect = Cv2.BoundingRect(contours[0]);
  3222. Mat rect = new Mat(srcBlack, bigrect);
  3223. //Cv2.EqualizeHist(rect, dst);
  3224. Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
  3225. //Cv2.MedianBlur(dst, dst, 1);
  3226. Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
  3227. Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3228. Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
  3229. Mat bb = new Mat(aa.Height, aa.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3230. Cv2.Circle(bb, (int)center.X, (int)center.Y, (int)cs[i].Radius - 15, Scalar.White, 1, LineTypes.AntiAlias);
  3231. OpenCvSharp.Point[][] contoursCircleLine;
  3232. HierarchyIndex[] hierarchyLine;
  3233. Cv2.FindContours(bb, out contoursCircleLine, out hierarchyLine, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3234. List<OpenCvSharp.Point> contoursCircleLineOne = new List<OpenCvSharp.Point>();
  3235. for (int m = 0; m < contoursCircleLine.Length; m++)
  3236. {
  3237. for (int n = 0; n < contoursCircleLine[m].Length; n++)
  3238. {
  3239. contoursCircleLineOne.Add(contoursCircleLine[m][n]);
  3240. }
  3241. }
  3242. //内缩
  3243. Rect bigRect = new Rect(0, 0, rect.Width, rect.Height);
  3244. for (int nX = bigRect.X; nX <= bigRect.Right; nX++)
  3245. {
  3246. for (int nY = bigRect.Y; nY <= bigRect.Bottom; nY++)
  3247. {
  3248. double localPos = Cv2.PointPolygonTest(contoursCircleLineOne, new Point2f(nX, nY), false);
  3249. if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
  3250. {
  3251. }
  3252. else
  3253. {
  3254. aa.Set<int>(nX, nY, 0);
  3255. }
  3256. }
  3257. }
  3258. OpenCvSharp.Point[][] contours1 = new OpenCvSharp.Point[][] { };
  3259. HierarchyIndex[] hierarchy1 = new HierarchyIndex[] { };
  3260. Cv2.FindContours(aa, out contours1, out hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3261. // Cv2.CvtColor(aa, aa, ColorConversionCodes.RGB2BGR);
  3262. List<OpenCvSharp.Point[]> contoursHoleList = contours1.OrderByDescending(t => t.Count()).ToList();
  3263. //if (contoursHoleList.Count == 0)
  3264. //{
  3265. // continue;
  3266. //}
  3267. double isk = 0;
  3268. float widthto = 0;
  3269. float heightto = 0;
  3270. for (int k = 0; k < contours1.Count(); k++)
  3271. {
  3272. RotatedRect rectR = Cv2.MinAreaRect(contours1[k]); //计算每个轮廓最小外接矩形
  3273. Rect rectB = Cv2.BoundingRect(contours1[k]);
  3274. float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3275. float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3276. height = height == 0 ? 1 : height;
  3277. double distance = 0;
  3278. for (int m = 0; m < contours1[k].Count(); m++)
  3279. {
  3280. Point2f centerCoutours = new Point2f(contours1[k][m].X, contours1[k][m].Y);
  3281. distance += centerCoutours.DistanceTo(center);
  3282. }
  3283. distance = distance / contours1[k].Count();
  3284. OpenCvSharp.Point[] lineDmax = new OpenCvSharp.Point[2];
  3285. RotatedRect minRect;
  3286. // double ratio = GetDMax(contours[k], out lineDmax) / GetDMin(contours[k], out minRect);
  3287. if (distance > 55)
  3288. {
  3289. //再边缘
  3290. //Cv2.DrawContours(aa, contours, k, Scalar.Yellow, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3291. }
  3292. else if (/*ratio > 2 && */Cv2.ArcLength(contours1[k], true) < 15)
  3293. {
  3294. //像素太少的去掉
  3295. // Cv2.DrawContours(aa, contours, k, Scalar.Blue, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3296. }
  3297. else
  3298. {
  3299. widthto = widthto + width;
  3300. isk = isk + Cv2.ContourArea(contours1[k]);
  3301. if (Cv2.ContourArea(contours1[k]) > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
  3302. {
  3303. break;
  3304. }
  3305. //最终想要的裂缝
  3306. //Cv2.DrawContours(aa, contours1, k, Scalar.Green, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3307. List<OpenCvSharp.Point> bigmap = new List<OpenCvSharp.Point>();
  3308. foreach (OpenCvSharp.Point item in contours1[k])
  3309. {
  3310. bigmap.Add(new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y });
  3311. }
  3312. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3313. tol.Add(bigmap);
  3314. Cv2.DrawContours(temp, tol, 0, colorList[1], 1, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3315. }
  3316. }
  3317. if (isk > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
  3318. {
  3319. continue;
  3320. }
  3321. if (isk > 0)
  3322. {
  3323. heightto = (float)isk / widthto;
  3324. heightto = heightto < 1 ? 1 : heightto;
  3325. //画圆
  3326. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[1], 2, LineTypes.AntiAlias);
  3327. //加强圆心显示
  3328. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[1], 6, LineTypes.AntiAlias);
  3329. }
  3330. else
  3331. {
  3332. //画圆
  3333. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[0], 2, LineTypes.AntiAlias);
  3334. //加强圆心显示
  3335. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[0], 6, LineTypes.AntiAlias);
  3336. }
  3337. List<int> po = new List<int>() { (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, (int)widthto, (int)heightto, isk > 0 ? 1 : 0 };
  3338. poList.Add(po);
  3339. }
  3340. return temp.Clone();
  3341. }
  3342. /// <summary>
  3343. /// 开裂球识别分水岭
  3344. /// </summary>
  3345. /// <param name="src"></param>
  3346. public static Mat DrwCrackBall_New(Mat src, Mat source)
  3347. {
  3348. temp = source.Clone();
  3349. Mat gray = new Mat();
  3350. Mat dst = new Mat();
  3351. Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
  3352. OpenCvSharp.Point[][] cs;
  3353. HierarchyIndex[] hierarchycs;
  3354. Cv2.FindContours(gray, out cs, out hierarchycs, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3355. particlePixles.Clear();
  3356. Mat srcBlack;
  3357. int sucessCs = 0;
  3358. int badCs = 0;
  3359. int index = 1;
  3360. double heig = (double)140 / (double)1920;
  3361. for (int i = 0; i < cs.Length; i++)
  3362. {
  3363. //边界颗粒去除
  3364. int coutp = 0;
  3365. for (int j = 0; j < cs[i].Length; j++)
  3366. {
  3367. int cspx = cs[i][j].X;
  3368. int cspy = cs[i][j].Y;
  3369. if (cspx == 0 || cspy == 0 || cspx > src.Cols - 5 || cspy > src.Rows - heig * src.Rows - 5)
  3370. {
  3371. coutp++;
  3372. }
  3373. }
  3374. if (coutp > 5)
  3375. {
  3376. continue;
  3377. }
  3378. //面积过小去除
  3379. if (Cv2.ContourArea(cs[i]) < 4000)
  3380. {
  3381. continue;
  3382. }
  3383. Rect bigrect = Cv2.BoundingRect(cs[i]);
  3384. if (CreackBallPointFs.Count > 0)
  3385. {
  3386. bool isnei = false;
  3387. foreach (var item in CreackBallPointFs)
  3388. {
  3389. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3390. if (dq > 0)
  3391. {
  3392. isnei = true;
  3393. break;
  3394. }
  3395. }
  3396. if (isnei)
  3397. {
  3398. continue;
  3399. }
  3400. }
  3401. //圆度过大去除
  3402. //afa参考代码
  3403. double s = Cv2.ContourArea(cs[i]);//轮廓面积
  3404. double c = Cv2.ArcLength(cs[i], true); //轮廓周长
  3405. double afa = 4 * Math.PI * s / (c * c); //afa计算
  3406. afa = Math.Abs(afa - 1);
  3407. //if (afa > 0.6)
  3408. //{
  3409. // continue;
  3410. //}
  3411. afa = afa * 1000;
  3412. if (CreackBallPointFsK.Count > 0)
  3413. {
  3414. bool isnei = false;
  3415. foreach (var item in CreackBallPointFsK)
  3416. {
  3417. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3418. if (dq > 0)
  3419. {
  3420. isnei = true;
  3421. break;
  3422. }
  3423. }
  3424. if (isnei)
  3425. {
  3426. Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3427. List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 1, (int)afa };
  3428. poList.Add(po1);
  3429. continue;
  3430. }
  3431. }
  3432. if (CreackBallPointFsP.Count > 0)
  3433. {
  3434. bool isnei = false;
  3435. foreach (var item in CreackBallPointFsP)
  3436. {
  3437. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3438. if (dq > 0)
  3439. {
  3440. isnei = true;
  3441. break;
  3442. }
  3443. }
  3444. if (isnei)
  3445. {
  3446. Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3447. List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 0, (int)afa };
  3448. poList.Add(po1);
  3449. continue;
  3450. }
  3451. }
  3452. srcBlack = new Mat(gray.Height, gray.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3453. Cv2.DrawContours(srcBlack, cs, i, Scalar.White, -1, LineTypes.Link4, hierarchycs, 2, new OpenCvSharp.Point(0, 0));
  3454. //取所有的点
  3455. List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
  3456. int rows = srcBlack.Height,
  3457. cols = srcBlack.Width;
  3458. for (int k = 0; k < rows; k++)
  3459. {
  3460. IntPtr a = srcBlack.Ptr(k);
  3461. byte* b = (byte*)a.ToPointer();
  3462. for (int j = 0; j < cols; j++)
  3463. {
  3464. if (b[j] != 0)
  3465. {
  3466. srPoints.Add(new OpenCvSharp.Point(j, k));
  3467. }
  3468. }
  3469. }
  3470. for (int j = 0; j < srPoints.Count; j++)
  3471. {
  3472. int item = source.Get<int>(srPoints[j].Y, srPoints[j].X);
  3473. srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
  3474. }
  3475. double outR = Math.Sqrt(s / Math.PI) * 0.5;
  3476. double dist = 0;
  3477. double maxdist = 0;
  3478. //中心点
  3479. OpenCvSharp.Point ballCenter = new OpenCvSharp.Point();
  3480. foreach (var item in srPoints)
  3481. {
  3482. dist = Cv2.PointPolygonTest(cs[i], item, true);
  3483. if (dist > maxdist)
  3484. {
  3485. maxdist = dist;
  3486. ballCenter = item;
  3487. }
  3488. }
  3489. List<OpenCvSharp.Point> sel = new List<OpenCvSharp.Point>();
  3490. for (int k = 0; k < cs[i].Length; k++)
  3491. {
  3492. sel.Add(cs[i][k]);
  3493. }
  3494. Mat rect = new Mat(srcBlack, bigrect);
  3495. Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
  3496. Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
  3497. for (int x = 0; x < aa.Cols; x++)
  3498. {
  3499. for (int y = 0; y < aa.Rows; y++)
  3500. {
  3501. double localPos = Cv2.PointPolygonTest(sel, new Point2f(x + bigrect.X, y + bigrect.Y), false);
  3502. if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
  3503. {
  3504. }
  3505. else
  3506. {
  3507. aa.Set<int>(y, x, 0);
  3508. }
  3509. }
  3510. }
  3511. InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
  3512. //开操作,也可省落变量前缀名
  3513. Cv2.MorphologyEx(aa, aa, MorphTypes.Dilate, kernel, new OpenCvSharp.Point(-1, -1));
  3514. OpenCvSharp.Point[][] contours;
  3515. HierarchyIndex[] hierarchy;
  3516. Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3517. List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t.Count()).ToList();
  3518. double isk = 0;
  3519. float widthto = 0;
  3520. double heightto = 0;
  3521. double arclength = 0;
  3522. Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
  3523. double area = Cv2.ContourArea(cs[i]);
  3524. double ra = aa.Cols < aa.Rows ? aa.Cols / 2 : aa.Rows / 2;
  3525. for (int k = 0; k < contoursHoleList.Count(); k++)
  3526. {
  3527. double tarea = Cv2.ContourArea(contoursHoleList[k]);
  3528. RotatedRect rectR = Cv2.MinAreaRect(contoursHoleList[k]); //计算每个轮廓最小外接矩形
  3529. Rect rectB = Cv2.BoundingRect(contoursHoleList[k]);
  3530. float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3531. float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3532. height = height == 0 ? 1 : height;
  3533. List<OpenCvSharp.Point> poingtForUse = new List<OpenCvSharp.Point>();
  3534. List<OpenCvSharp.Point> tempList = new List<OpenCvSharp.Point>();
  3535. int outCount = 0;
  3536. foreach (OpenCvSharp.Point item in contoursHoleList[k])
  3537. {
  3538. OpenCvSharp.Point point1 = new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y };
  3539. double d = Cv2.PointPolygonTest(cs[i], point1, true);
  3540. tempList.Add(point1);
  3541. if (d < 5)
  3542. {
  3543. outCount++;
  3544. }
  3545. }
  3546. if (((outCount * 100) / contoursHoleList[k].Count()) < 70)
  3547. {
  3548. tempList.ForEach(p => poingtForUse.Add(p));
  3549. }
  3550. // double ratio = GetDMax(contoursHoleList[k], out lineDmax) / GetDMin(contoursHoleList[k], out minRect);
  3551. double carea = Cv2.ContourArea(contoursHoleList[k]);
  3552. double cleng = Cv2.ArcLength(contoursHoleList[k], true); //轮廓周长
  3553. double cafa = 4 * Math.PI * s / (c * c); //afa计算
  3554. cafa = Math.Abs(cafa - 1);
  3555. if (poingtForUse.Count < 25)
  3556. {
  3557. }
  3558. else if (cleng < 30)
  3559. {
  3560. }
  3561. else
  3562. {
  3563. arclength = arclength + Cv2.ArcLength(contoursHoleList[k], true);
  3564. widthto = widthto + width;
  3565. isk = isk + Cv2.ContourArea(contoursHoleList[k]);
  3566. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3567. tol.Add(poingtForUse);
  3568. Cv2.DrawContours(temp, tol, 0, colorList[1], -1, LineTypes.Link8, null, 2, new OpenCvSharp.Point(0, 0));
  3569. //for (int p = 0; p < poingtForUse.Count(); p++)
  3570. //{
  3571. // temp.Set<Vec4b>(poingtForUse[p].Y, poingtForUse[p].X, vec4BList[1]);
  3572. //}
  3573. }
  3574. }
  3575. if (isk > 0)
  3576. {
  3577. heightto = isk / arclength;
  3578. heightto = heightto < 1 ? 1 : heightto;
  3579. Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3580. }
  3581. else
  3582. {
  3583. Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3584. }
  3585. particlePixles.Add(index++, sel);
  3586. List<int> po = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, (int)widthto, (int)heightto, isk > 0 ? 1 : 0, (int)afa };
  3587. poList.Add(po);
  3588. }
  3589. return temp.Clone();
  3590. }
  3591. /// <summary>
  3592. /// 开裂球选择
  3593. /// </summary>
  3594. /// <param name="src"></param>
  3595. /// <returns></returns>
  3596. private static Mat SelectBall(Mat src, int x, int y, int r)
  3597. {
  3598. temp = src.Clone();
  3599. //画圆
  3600. // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
  3601. //加强圆心显示
  3602. Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
  3603. return temp;
  3604. }
  3605. /// <summary>
  3606. /// 开裂球选择
  3607. /// </summary>
  3608. /// <param name="src"></param>
  3609. /// <returns></returns>
  3610. private static Mat SelectBallInt(Mat src, int index)
  3611. {
  3612. temp = src.Clone();
  3613. //画圆
  3614. // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
  3615. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3616. tol.Add(particlePixles[index]);
  3617. Cv2.DrawContours(temp, tol, 0, colorList[4], 4, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3618. RotatedRect rectR = Cv2.MinAreaRect(particlePixles[index]);
  3619. double are = Cv2.ContourArea(particlePixles[index]);
  3620. //加强圆心显示
  3621. // Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
  3622. return temp;
  3623. }
  3624. private static void GetHalfCircles(Mat color)
  3625. {
  3626. Mat canny = new Mat();
  3627. Mat gray = new Mat();
  3628. Cv2.CvtColor(color, gray, ColorConversionCodes.BGRA2GRAY);
  3629. Cv2.Canny(gray, canny, 200, 20);
  3630. CircleSegment[] circles = Cv2.HoughCircles(gray, HoughMethods.Gradient, 1, 80, 70, 24, 33, 52);
  3631. for (int i = 0; i < circles.Length; i++)
  3632. {
  3633. //加强圆心显示
  3634. Cv2.Circle(color, (int)circles[i].Center.X, (int)circles[i].Center.Y, 3, new Scalar(0, 255, 255), -1, LineTypes.AntiAlias);
  3635. //画圆
  3636. Cv2.Circle(color, (int)circles[i].Center.X, (int)circles[i].Center.Y, (int)circles[i].Radius, new Scalar(0, 0, 255), 1, LineTypes.AntiAlias);
  3637. }
  3638. Mat dt = new Mat();
  3639. Cv2.BitwiseNot(canny, canny);
  3640. Cv2.DistanceTransform(canny, dt, DistanceTypes.L2, DistanceMaskSize.Mask3);
  3641. float minInlierDist = 2.0f;
  3642. for (int i = 0; i < circles.Length; i++)
  3643. {
  3644. int counter = 0;
  3645. int inlier = 0;
  3646. Point2f center = circles[i].Center;
  3647. float radius = circles[i].Radius;
  3648. float maxInlierDist = radius / 25.0f;
  3649. if (maxInlierDist < minInlierDist) maxInlierDist = minInlierDist;
  3650. for (float t = 0; t < 2 * Math.PI; t += 0.1f)
  3651. {
  3652. counter++;
  3653. float cX = radius * (float)Math.Cos(t) + circles[i].Center.X;
  3654. float cY = radius * (float)Math.Sin(t) + circles[i].Center.Y;
  3655. if (cX < 0)
  3656. {
  3657. cX = 0;
  3658. }
  3659. if (cY < 0)
  3660. {
  3661. cY = 0;
  3662. }
  3663. if (dt.At<float>((int)cY, (int)cX) < maxInlierDist)
  3664. {
  3665. inlier++;
  3666. Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(0, 255, 0));
  3667. }
  3668. else
  3669. {
  3670. Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(255, 0, 0));
  3671. }
  3672. }
  3673. }
  3674. using (new Window("color", WindowMode.Normal, color))
  3675. {
  3676. Cv2.WaitKey(0);
  3677. }
  3678. }
  3679. /// <summary>
  3680. /// 二值提取隔膜
  3681. /// </summary>
  3682. /// <param name="source">源</param>
  3683. /// <param name="colorInterval">1个或2个颜色区间</param>
  3684. /// <param name="colorOneStart"></param>
  3685. /// <param name="colorOneEnd"></param>
  3686. /// <param name="colorTwoStart"></param>
  3687. /// <param name="colorTwoEnd"></param>
  3688. /// <param name="colorThreeStart"></param>
  3689. /// <param name="colorThreeEnd"></param>
  3690. /// <returns></returns>
  3691. private static Mat BinarizationForM(Mat source)
  3692. {
  3693. Mat srcGray;
  3694. if (source.Type() == MatType.CV_8UC1)
  3695. {
  3696. srcGray = source;
  3697. }
  3698. else
  3699. {
  3700. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  3701. }
  3702. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  3703. try
  3704. {
  3705. srcGray.ForEachAsByte(GrayForEachAsByteForM);
  3706. }
  3707. catch (Exception)
  3708. {
  3709. throw;
  3710. }
  3711. return temp.Clone();
  3712. }
  3713. /// <summary>
  3714. /// 并行循环
  3715. /// </summary>
  3716. /// <param name="value"></param>
  3717. /// <param name="position"></param>
  3718. private static void GrayForEachAsByteForM(byte* value, int* position)
  3719. {
  3720. int y = position[0];
  3721. int x = position[1];
  3722. byte v = *value;
  3723. if (v >= colorOneStart && v <= colorOneEnd && y < imageHight - 70)
  3724. {
  3725. temp.Set<Vec4b>(y, x, vec4B);
  3726. }
  3727. }
  3728. }
  3729. }