Battery.cs 165 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250
  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. // InputArray contoursAll = InputArray.Create(AllFields[h - 1]);
  2392. // List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2393. // OutputArray hull = OutputArray.Create(outArr);
  2394. // Cv2.ConvexHull(contoursAll, hull, true);
  2395. // double nc = Cv2.ArcLength(outArr.ToArray(), true) / Math.PI;
  2396. // double na = Math.Sqrt(areaField1 / Math.PI) * 2;
  2397. //int aa = Convert.ToInt32((na / nc) * 1000);
  2398. List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
  2399. Point2f[] point2F = rectR.Points();
  2400. foreach (var item in point2F)
  2401. {
  2402. listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
  2403. }
  2404. rectListPoint.Add(listpoint);
  2405. rectList.Add(rectR);
  2406. List<int> po = new List<int>() { x, y, width, height, areaField1, h, maxxx, maxyy, 1 };
  2407. poList.Add(po);
  2408. }
  2409. }
  2410. else
  2411. {
  2412. keyValuePairs.Add(h, 1);
  2413. }
  2414. }
  2415. }
  2416. labelMatForSel = labelMat;
  2417. fieldsCount = centroids.Height;
  2418. labelMat.ForEachAsInt32(CommonForEachForInt32);
  2419. labelMat.ForEachAsInt32(CommonForEachForSel);
  2420. #region 添加颗粒
  2421. Mat MatAdd = new Mat(src.Size(), MatType.CV_8UC1);
  2422. if (AddPontins != null && AddPontins.Count > 0)
  2423. {
  2424. for (int i = 0; i < AddPontins.Count; i++)
  2425. {
  2426. Cv2.DrawContours(MatAdd, AddPontins, i, new Scalar(255), -1);
  2427. Cv2.DrawContours(rgb_ap, AddPontins, i,new Scalar( vec4B.Item0, vec4B.Item1, vec4B.Item2), -1);
  2428. Cv2.DrawContours(temp_ap, AddPontins, i, new Scalar(255), -1);
  2429. }
  2430. // Cv2.DrawContours(src, AddPontins, -1, new Scalar(255, 255, 255, 255), -1);
  2431. }
  2432. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2433. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2434. //轮廓
  2435. Cv2.FindContours(MatAdd, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2436. labelMatForSelAdd = contours;
  2437. for (int i = 0; i < contours.Length; i++)
  2438. {
  2439. Rect rect = Cv2.BoundingRect(contours[i]);
  2440. int areaField1 =Convert.ToInt32( Cv2.ContourArea(contours[i]));
  2441. int x = rect.X;
  2442. int y = rect.Y;
  2443. int width = rect.Width;
  2444. int height = rect.Height;
  2445. int maxxx = 0; int maxyy = 0;
  2446. RotatedRect rectR = Cv2.MinAreaRect(contours[i]);
  2447. if (maxxx < rectR.Size.Width)
  2448. {
  2449. maxxx = (int)rectR.Size.Width;
  2450. }
  2451. if (maxyy < rectR.Size.Height)
  2452. {
  2453. maxyy = (int)rectR.Size.Height;
  2454. }
  2455. List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
  2456. Point2f[] point2F = rectR.Points();
  2457. foreach (var item in point2F)
  2458. {
  2459. listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
  2460. }
  2461. rectListPoint.Add(listpoint);
  2462. rectList.Add(rectR);
  2463. List<int> po = new List<int>() { x, y, width, height, areaField1, centroids.Height+i, maxxx, maxyy, 1 };
  2464. poList.Add(po);
  2465. }
  2466. //using (new Window("s", WindowMode.Normal, src))
  2467. //{
  2468. // Cv2.WaitKey(0);
  2469. //}
  2470. #endregion
  2471. //合并rgb和透明度
  2472. Mat[] mats = rgb_ap.Split();
  2473. arr[0] = mats[0];
  2474. arr[1] = mats[1];
  2475. arr[2] = mats[2];
  2476. arr[3] = temp_ap;
  2477. Cv2.Merge(arr, src);
  2478. Scalar scalar = new Scalar(255, 255, 255, 255);
  2479. if (isDis)
  2480. {
  2481. foreach (var p in rectList)
  2482. {
  2483. Point2f[] point2F = p.Points();
  2484. double width = (point2F[0].X - point2F[1].X) / 2;
  2485. double height = (point2F[0].Y - point2F[1].Y) / 2;
  2486. OpenCvSharp.Point p1 = new OpenCvSharp.Point(point2F[1].X + width, point2F[1].Y + height);
  2487. OpenCvSharp.Point p2 = new OpenCvSharp.Point(point2F[2].X + width, point2F[2].Y + height);
  2488. src.Line(p1, p2, scalar, 1);
  2489. int wid = (int)p.Size.Width;
  2490. double d1= wid* Micron;
  2491. src.PutText(Math.Round(d1, 2).ToString(), p2, HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0, 255), 1);
  2492. width = (point2F[3].X - point2F[0].X) / 2;
  2493. height = (point2F[0].Y - point2F[3].Y) / 2;
  2494. OpenCvSharp.Point p3 = new OpenCvSharp.Point(point2F[0].X + width, point2F[3].Y + height);
  2495. OpenCvSharp.Point p4 = new OpenCvSharp.Point(point2F[1].X + width, point2F[2].Y + height);
  2496. src.Line(p3, p4, scalar, 1);
  2497. int hei = (int)p.Size.Height;
  2498. double d2 = hei * Micron;
  2499. src.PutText(Math.Round(d2, 2).ToString(), p3, HersheyFonts.HersheyPlain, 1, new Scalar(0, 0, 255, 255), 1);
  2500. }
  2501. }
  2502. if (isJu)
  2503. {
  2504. src.DrawContours(rectListPoint, -1, scalar, 1);
  2505. }
  2506. return src;
  2507. }
  2508. /// <summary>
  2509. /// 单晶删除颗粒
  2510. /// </summary>
  2511. /// <param name="src"></param>
  2512. /// <returns></returns>
  2513. private static Mat DebrisRemoval_Cryst_Del(Mat src)
  2514. {
  2515. temp_ap = src.CvtColor(ColorConversionCodes.BGR2GRAY);
  2516. using (new Window("s", WindowMode.Normal, temp_ap))
  2517. {
  2518. Cv2.WaitKey(0);
  2519. }
  2520. //寻找连通分量
  2521. Mat labelMat = new Mat();
  2522. Mat stats = new Mat();
  2523. Mat centroids = new Mat();
  2524. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2525. //寻找在范围内需要删除的碎屑
  2526. keyValuePairs.Clear();
  2527. if (delPointFs != null && delPointFs.Count > 0)
  2528. {
  2529. for (int i = 0; i < delPointFs.Count; i++)
  2530. {
  2531. int qx = (int)delPointFs[i].X;
  2532. int qy = (int)delPointFs[i].Y;
  2533. int label = labelMat.At<int>(qy, qx);
  2534. if (label > 0 && !keyValuePairs.ContainsKey(label))
  2535. {
  2536. keyValuePairs.Add(label, 1);
  2537. }
  2538. }
  2539. }
  2540. labelMat.ForEachAsInt32(CommonForEachDel);
  2541. return temp_ap.Clone();
  2542. }
  2543. private static void CommonForEachDel(int* value, int* position)
  2544. {
  2545. int y = position[0];
  2546. int x = position[1];
  2547. int v = *value;
  2548. if (v > 0 && keyValuePairs.ContainsKey(v))
  2549. {
  2550. temp_ap.Set<int>(y, x, 0);
  2551. }
  2552. }
  2553. //寻找角点做角曲率
  2554. private static double GetRoundness1(int width, int height, int x, int y)
  2555. {
  2556. OpenCvSharp.Point core = new OpenCvSharp.Point();
  2557. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2558. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2559. Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2560. Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
  2561. double dist = 0;
  2562. double maxdist = 0;
  2563. for (int i = 0; i < width; i++)
  2564. {
  2565. for (int j = 0; j < height; j++)
  2566. {
  2567. OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
  2568. dist = Cv2.PointPolygonTest(contours[0], point, true);
  2569. if (dist > maxdist)
  2570. {
  2571. maxdist = dist;
  2572. core = point;
  2573. }
  2574. }
  2575. }
  2576. Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
  2577. double roundness = 0;
  2578. //寻找角点
  2579. InputArray contoursAll = InputArray.Create(contours[0]);
  2580. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2581. OutputArray hull = OutputArray.Create(outArr);
  2582. Cv2.ConvexHull(contoursAll, hull, true);
  2583. Point2f[] cornersPoint = Cv2.GoodFeaturesToTrack(ground, 100, 0.01, 30, new Mat(), 7, false, 0.04);
  2584. foreach (var item in cornersPoint)
  2585. {
  2586. Cv2.Circle(ground, Convert.ToInt16(item.X), Convert.ToInt16(item.Y), 10, Scalar.White, 2);
  2587. int index = contours[0].ToList().FindIndex(u => Math.Abs(u.X - item.X) < 3 && Math.Abs(u.Y - item.Y) < 3);
  2588. List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
  2589. list.Add(item);
  2590. int nv = 10;
  2591. if (index > nv)
  2592. {
  2593. list.Add(contours[0][index - nv]);
  2594. }
  2595. else
  2596. {
  2597. int ind = nv - index;
  2598. list.Add(contours[0][contours[0].Length - nv - 1]);
  2599. }
  2600. if (index + nv < contours[0].Length)
  2601. {
  2602. list.Add(contours[0][index + nv]);
  2603. }
  2604. else
  2605. {
  2606. list.Add(contours[0][index + nv - contours[0].Length]);
  2607. }
  2608. double dis1, dis2, dis3;
  2609. double cosA, sinA, dis;
  2610. OpenCvSharp.Point2f P1 = list[0];
  2611. OpenCvSharp.Point2f P2 = list[1];
  2612. OpenCvSharp.Point2f P3 = list[2];
  2613. dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
  2614. dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
  2615. dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
  2616. dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
  2617. cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
  2618. sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
  2619. double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
  2620. curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
  2621. roundness += curvity;
  2622. }
  2623. double ri = roundness / maxdist;
  2624. ri = ri / cornersPoint.Length;
  2625. using (new Window("ss", WindowMode.Normal, ground))
  2626. {
  2627. Cv2.WaitKey(0);
  2628. }
  2629. return ri;
  2630. }
  2631. //寻找凸包做角曲率
  2632. private static double GetRoundness2(int width, int height, int x, int y)
  2633. {
  2634. OpenCvSharp.Point core = new OpenCvSharp.Point();
  2635. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  2636. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  2637. Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  2638. Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
  2639. double dist = 0;
  2640. double maxdist = 0;
  2641. for (int i = 0; i < width; i++)
  2642. {
  2643. for (int j = 0; j < height; j++)
  2644. {
  2645. OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
  2646. dist = Cv2.PointPolygonTest(contours[0], point, true);
  2647. if (dist > maxdist)
  2648. {
  2649. maxdist = dist;
  2650. core = point;
  2651. }
  2652. }
  2653. }
  2654. //寻找角点
  2655. InputArray contoursAll = InputArray.Create(contours[0]);
  2656. List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
  2657. OutputArray hull = OutputArray.Create(outArr);
  2658. Cv2.ConvexHull(contoursAll, hull, true);
  2659. //内切圆
  2660. Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
  2661. double roundness = 0;
  2662. Cv2.DrawContours(open, new List<List<OpenCvSharp.Point>>() { outArr }, 0, Scalar.White, 2);
  2663. for (int i = 0; i < outArr.Count(); i++)
  2664. {
  2665. Point2f item = outArr[i];
  2666. List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
  2667. list.Add(item);
  2668. if (i == 0)
  2669. {
  2670. list.Add(outArr[outArr.Count() - 1]);
  2671. }
  2672. else
  2673. {
  2674. list.Add(outArr[i - 1]);
  2675. }
  2676. if (i == (outArr.Count() - 1))
  2677. {
  2678. list.Add(outArr[0]);
  2679. }
  2680. else
  2681. {
  2682. list.Add(outArr[i + 1]);
  2683. }
  2684. double dis1, dis2, dis3;
  2685. double cosA, sinA, dis;
  2686. OpenCvSharp.Point2f P1 = list[0];
  2687. OpenCvSharp.Point2f P2 = list[1];
  2688. OpenCvSharp.Point2f P3 = list[2];
  2689. dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
  2690. dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
  2691. dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
  2692. dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
  2693. cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
  2694. sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
  2695. double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
  2696. curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
  2697. roundness += curvity;
  2698. }
  2699. double ri = roundness / maxdist;
  2700. ri = ri / outArr.Count();
  2701. using (new Window("open", WindowMode.Normal, open))
  2702. using (new Window("ss", WindowMode.Normal, ground))
  2703. {
  2704. Cv2.WaitKey(0);
  2705. }
  2706. return ri;
  2707. }
  2708. private static readonly object locker = new object();
  2709. //获取连通域点
  2710. private static void CommonForEachForCon(int* value, int* position)
  2711. {
  2712. int y = position[0];
  2713. int x = position[1];
  2714. int v = *value;
  2715. if (v > 0)
  2716. {
  2717. try
  2718. {
  2719. lock (locker)
  2720. {
  2721. AllFields[v - 1].Add(new OpenCvSharp.Point(x, y));
  2722. }
  2723. }
  2724. catch (Exception e)
  2725. {
  2726. throw;
  2727. }
  2728. }
  2729. }
  2730. private static void CommonForEachForArc(int* value, int* position)
  2731. {
  2732. int y = position[0];
  2733. int x = position[1];
  2734. int v = *value;
  2735. if (v > 0 && hindex != v)
  2736. {
  2737. ground.Set<int>(y, x, 0);
  2738. }
  2739. }
  2740. /// <summary>
  2741. /// 单晶Canny去噪点
  2742. /// </summary>
  2743. /// <param name="src"></param>
  2744. /// <returns></returns>
  2745. private static Mat DebrisRemoval_CrystCanny(Mat src)
  2746. {
  2747. temp_ap = src;
  2748. //寻找连通分量
  2749. Mat labelMat = new Mat();
  2750. Mat stats = new Mat();
  2751. Mat centroids = new Mat();
  2752. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2753. //寻找在范围内需要删除的碎屑
  2754. keyValuePairs.Clear();
  2755. for (int h = 1; h < centroids.Height; h++)
  2756. {
  2757. int areaField1 = stats.At<int>(h, 4);
  2758. int x = stats.At<int>(h, 0);
  2759. int y = stats.At<int>(h, 1);
  2760. int width = stats.At<int>(h, 2);
  2761. int height = stats.At<int>(h, 3);
  2762. //面积小于30的孔隙删除
  2763. if (areaField1 <= 500)
  2764. {
  2765. keyValuePairs.Add(h, 1);
  2766. }
  2767. }
  2768. labelMatForSel = labelMat;
  2769. labelMat.ForEachAsInt32(CommonForEachForInt32_CrystCanny);
  2770. return temp_ap;
  2771. }
  2772. private static void CommonForEachForInt32_CrystCanny(int* value, int* position)
  2773. {
  2774. int y = position[0];
  2775. int x = position[1];
  2776. int v = *value;
  2777. if (v > 0 && keyValuePairs.ContainsKey(v))
  2778. {
  2779. temp_ap.Set<int>(y, x, 0);
  2780. }
  2781. }
  2782. #endregion
  2783. #region 有视场 二值提取
  2784. /// <summary>
  2785. /// 二值操作-二值提取-有视场
  2786. /// </summary>
  2787. /// <param name="src">视场mat</param>
  2788. /// <param name="mat">原图mat</param>
  2789. /// <param name="lists">参数列表</param>
  2790. /// <returns></returns>
  2791. public static Mat ImageBinaryExtraction(Mat source, Mat mat, List<Args> lists, bool findContours = false)
  2792. {
  2793. //以下是参数信息---------------------
  2794. ///1个颜色区间还是2个
  2795. colorInterval = 1;
  2796. //第一个二值区间
  2797. colorOneStart = 0;
  2798. colorOneEnd = 0;
  2799. //第二个二值区间
  2800. colorTwoStart = 0;
  2801. colorTwoEnd = 0;
  2802. //第三个二值区间
  2803. colorThreeStart = 0;
  2804. colorThreeEnd = 0;
  2805. //处理细节
  2806. //删除边界对象
  2807. bool deleteBoundaryObject = false;
  2808. //孔洞填充
  2809. bool holeFilling = false;
  2810. //碎屑删除
  2811. bool debrisRemoval = false;
  2812. //碎屑删除面积起
  2813. debrisAreaStart = 0;
  2814. //碎屑删除面积止
  2815. debrisAreaEnd = 0;
  2816. //二值样式
  2817. //1实心 2边线
  2818. int binaryStyle = 0;
  2819. //相颜色
  2820. Color phaseColor = Color.Red;
  2821. //目标选择
  2822. int targetSelection = 1;
  2823. for (int i = 0; i < lists.Count; i++)
  2824. {
  2825. Args args = lists[i];
  2826. switch (args.Key)
  2827. {
  2828. case "colorInterval":
  2829. {
  2830. if (args.Value is Boolean)
  2831. colorInterval = (Boolean)args.Value ? 2 : 1;
  2832. else
  2833. colorInterval = (int)args.Value;
  2834. }
  2835. break;
  2836. case "scope1":
  2837. colorOneStart = (int)((List<double>)args.Value)[0];
  2838. colorOneEnd = (int)((List<double>)args.Value)[1];
  2839. break;
  2840. case "scope2":
  2841. colorTwoStart = (int)((List<double>)args.Value)[0];
  2842. colorTwoEnd = (int)((List<double>)args.Value)[1];
  2843. break;
  2844. case "scope3":
  2845. colorThreeStart = (int)((List<double>)args.Value)[0];
  2846. colorThreeEnd = (int)((List<double>)args.Value)[1];
  2847. break;
  2848. case "deleteBoundaryObject":
  2849. deleteBoundaryObject = (bool)args.Value;
  2850. break;
  2851. case "holeFilling":
  2852. holeFilling = (bool)args.Value;
  2853. break;
  2854. case "debrisRemoval":
  2855. debrisRemoval = (bool)args.Value;
  2856. break;
  2857. case "binaryStyle":
  2858. binaryStyle = (int)args.Value;
  2859. break;
  2860. case "phaseColor":
  2861. phaseColor = Color.FromArgb((int)args.Value);
  2862. break;
  2863. case "targetSelection":
  2864. targetSelection = (int)args.Value;
  2865. break;
  2866. case "scope4":
  2867. debrisAreaStart = (int)((List<double>)args.Value)[0];
  2868. debrisAreaEnd = (int)((List<double>)args.Value)[1];
  2869. break;
  2870. default:
  2871. break;
  2872. }
  2873. }
  2874. vec4B.Item0 = phaseColor.B;
  2875. vec4B.Item1 = phaseColor.G;
  2876. vec4B.Item2 = phaseColor.R;
  2877. vec4B.Item3 = phaseColor.A;
  2878. //二值提取
  2879. Mat src = BinarizationWithView(source);
  2880. //目标选择
  2881. if (targetSelection != 2)
  2882. src = CalcContoursByTargetSelection_New(temp_view, targetSelection, source);
  2883. //碎屑删除,参考冈萨雷斯,414,9.5.3,连通分量提取
  2884. if (debrisRemoval && debrisAreaEnd > 0)
  2885. src = DebrisRemoval_NewWithView(src);
  2886. //孔洞填充,参考冈萨雷斯,413,9.5.2
  2887. if (holeFilling)
  2888. src = HoleFilling_NewWithView(src);
  2889. //实心/边线,参考冈萨雷斯,412,9.5.1,边界提取
  2890. if (binaryStyle == 2)
  2891. {
  2892. Cv2.Erode(src, temp, null);
  2893. src = src - temp;
  2894. src = BaseTools.MergeMatFromMatArr(src, vec4B);
  2895. }
  2896. return src;
  2897. }
  2898. /// <summary>
  2899. /// 二值提取
  2900. /// </summary>
  2901. /// <param name="source">视场图像</param>
  2902. /// <param name="mat">原图像</param>
  2903. /// <param name="colorInterval">1个或2个颜色区间</param>
  2904. /// <param name="colorOneStart"></param>
  2905. /// <param name="colorOneEnd"></param>
  2906. /// <param name="colorTwoStart"></param>
  2907. /// <param name="colorTwoEnd"></param>
  2908. /// <param name="colorThreeStart"></param>
  2909. /// <param name="colorThreeEnd"></param>
  2910. /// <param name="phaseColor">相颜色</param>
  2911. /// <returns></returns>
  2912. private static Mat BinarizationWithView(Mat source)
  2913. {
  2914. Mat[] arr = source.Split();
  2915. alpha = arr[3];
  2916. Mat srcGray;
  2917. if (source.Type() == MatType.CV_8UC1)
  2918. {
  2919. srcGray = source;
  2920. }
  2921. else
  2922. {
  2923. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  2924. }
  2925. temp_view = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  2926. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  2927. srcGray.ForEachAsByte(GrayForEachAsByteWithView);
  2928. return temp.Clone();
  2929. }
  2930. /// <summary>
  2931. /// 并行循环
  2932. /// </summary>
  2933. /// <param name="value"></param>
  2934. /// <param name="position"></param>
  2935. private static void GrayForEachAsByteWithView(byte* value, int* position)
  2936. {
  2937. int y = position[0];
  2938. int x = position[1];
  2939. byte v = *value;
  2940. if (colorInterval == 1)
  2941. {
  2942. if (v >= colorOneStart && v <= colorOneEnd)
  2943. {
  2944. if (alpha.At<byte>(y, x) > 0)
  2945. {
  2946. temp.Set<Vec4b>(y, x, vec4B);
  2947. temp_view.Set<Vec4b>(y, x, vec4B);
  2948. }
  2949. else
  2950. {
  2951. temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
  2952. }
  2953. }
  2954. }
  2955. else
  2956. {
  2957. if (((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd)))
  2958. {
  2959. if (alpha.At<byte>(y, x) > 0)
  2960. {
  2961. temp.Set<Vec4b>(y, x, vec4B);
  2962. temp_view.Set<Vec4b>(y, x, vec4B);
  2963. }
  2964. else
  2965. {
  2966. temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
  2967. }
  2968. }
  2969. }
  2970. }
  2971. /// <summary>
  2972. /// 新碎屑删除,使用连通分量找寻碎屑
  2973. /// </summary>
  2974. /// <param name="src"></param>
  2975. /// <returns></returns>
  2976. private static Mat DebrisRemoval_NewWithView(Mat src)
  2977. {
  2978. Mat[] arr = src.Split();
  2979. rgb_ap = BaseTools.MergeMatFromMatArr(arr);
  2980. temp_ap = arr[3].Clone();
  2981. //寻找连通分量
  2982. Mat labelMat = new Mat();
  2983. Mat stats = new Mat();
  2984. Mat centroids = new Mat();
  2985. int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  2986. //寻找在范围内需要删除的碎屑
  2987. keyValuePairs.Clear();
  2988. for (int h = 1; h < centroids.Height; h++)
  2989. {
  2990. int areaField1 = stats.At<int>(h, 4);
  2991. if (debrisAreaStart <= areaField1 && areaField1 <= debrisAreaEnd)
  2992. {
  2993. keyValuePairs.Add(h, 1);
  2994. }
  2995. }
  2996. labelMat.ForEachAsInt32(CommonForEachForInt32);
  2997. //合并rgb和透明度
  2998. Mat[] mats = rgb_ap.Split();
  2999. arr[0] = mats[0];
  3000. arr[1] = mats[1];
  3001. arr[2] = mats[2];
  3002. arr[3] = temp_ap;
  3003. Cv2.Merge(arr, src);
  3004. return src;
  3005. }
  3006. /// <summary>
  3007. /// 新孔洞填充,采用形态学填充
  3008. /// </summary>
  3009. /// <param name="src"></param>
  3010. /// <returns></returns>
  3011. private static Mat HoleFilling_NewWithView(Mat src)
  3012. {
  3013. Mat[] arr2 = src.Split();
  3014. Mat tempc = arr2[3];
  3015. //去掉透明层
  3016. Mat mat = src.CvtColor(ColorConversionCodes.BGRA2BGR);
  3017. //填充孔洞
  3018. mat = BaseTools.FillHole(mat, new Scalar(255 - vec4B.Item0, 255 - vec4B.Item1, 255 - vec4B.Item2));
  3019. tempc = BaseTools.FillHole(tempc, new Scalar(255));
  3020. //循环处理
  3021. mat.ForEachAsVec3b(RGBForEachAsByteForHoleFillingNewWithView);
  3022. Mat[] arr1 = mat.Split();
  3023. arr2[0] = arr1[0];
  3024. arr2[1] = arr1[1];
  3025. arr2[2] = arr1[2];
  3026. arr2[3] = tempc;
  3027. Cv2.Merge(arr2, src);
  3028. return src;
  3029. }
  3030. private static void RGBForEachAsByteForHoleFillingNewWithView(Vec3b* value, int* position)
  3031. {
  3032. int y = position[0];
  3033. int x = position[1];
  3034. if (value->Item0 == 255 && value->Item1 == 255 && value->Item2 == 255)
  3035. {
  3036. value->Item0 = vec4B.Item0;
  3037. value->Item1 = vec4B.Item1;
  3038. value->Item2 = vec4B.Item2;
  3039. }
  3040. }
  3041. /// <summary>
  3042. /// 目标选择
  3043. /// </summary>
  3044. /// <param name="src"></param>
  3045. /// <param name="mat"></param>
  3046. /// <param name="targetSelection"></param>
  3047. /// <param name="source"></param>
  3048. /// <returns></returns>
  3049. public static Mat CalcContoursByTargetSelection_New(Mat src, int targetSelection, Mat source)
  3050. {
  3051. Mat[] arr = src.Split();
  3052. alpha = arr[3].Clone();
  3053. Mat rgb = BaseTools.MergeMatFromMatArr(arr);
  3054. Mat alphatemp = arr[3].Clone();
  3055. Mat mask = Mat.Zeros(rgb.Rows + 2, rgb.Cols + 2, MatType.CV_8UC1);
  3056. //考虑循环填充,填充视场的透明层和原图的透明层,然后比较填充区域的大小
  3057. //但是循环的时候需要少循环像素,可以处理视场的透明层,减少循环量
  3058. //同时记录种子点,然后根据targetSelection判断是填充透明还是不透明
  3059. Mat rgbClone = rgb.Clone();
  3060. List<OpenCvSharp.Point> points = new List<OpenCvSharp.Point>();
  3061. for (int h = 0; h < alphatemp.Height; h++)
  3062. {
  3063. for (int w = 0; w < alphatemp.Width; w++)
  3064. {
  3065. int v = alphatemp.At<byte>(h, w);
  3066. if (v > 0)
  3067. {
  3068. int a = Cv2.FloodFill(alphatemp, new OpenCvSharp.Point(w, h), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  3069. int b = Cv2.FloodFill(rgbClone, new OpenCvSharp.Point(w, h), new Scalar(0, 0, 0), out rect, null, null, FloodFillFlags.Link8);
  3070. if (a != b)
  3071. {
  3072. points.Add(new OpenCvSharp.Point(w, h));
  3073. }
  3074. }
  3075. }
  3076. }
  3077. if (points.Count > 0)
  3078. {
  3079. foreach (OpenCvSharp.Point p in points)
  3080. {
  3081. if (targetSelection == 1)
  3082. {
  3083. Cv2.FloodFill(alpha, p, new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
  3084. }
  3085. else if (targetSelection == 3)
  3086. {
  3087. Cv2.FloodFill(rgb, mask, p, new Scalar(vec4B.Item0, vec4B.Item1, vec4B.Item2), out rect, null, null, FloodFillFlags.Link8);
  3088. }
  3089. }
  3090. }
  3091. if (targetSelection == 3)
  3092. {
  3093. Mat t = new Mat(mask, new Rect(1, 1, rgb.Width, rgb.Height));
  3094. alpha = alpha + t * 255;
  3095. }
  3096. //合并rgb和透明度
  3097. Mat[] mats = rgb.Split();
  3098. arr[0] = mats[0];
  3099. arr[1] = mats[1];
  3100. arr[2] = mats[2];
  3101. arr[3] = alpha;
  3102. Cv2.Merge(arr, src);
  3103. return src;
  3104. }
  3105. #endregion
  3106. private static void CommonForEachForInt32(int* value, int* position)
  3107. {
  3108. int y = position[0];
  3109. int x = position[1];
  3110. int v = *value;
  3111. if (v > 0 && keyValuePairs.ContainsKey(v))
  3112. {
  3113. rgb_ap.Set<Vec3b>(y, x, new Vec3b(0, 0, 0));
  3114. temp_ap.Set<int>(y, x, 0);
  3115. //手动画圆
  3116. if (ListRadiusColor.Count > 0)
  3117. {
  3118. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  3119. if (ListRadiusColor.Count > 1)
  3120. {
  3121. for (int i = 0; i < ListRadiusColor.Count - 1; i++)
  3122. {
  3123. int r = i == 0 ? 0 : ListRadiusColor.ElementAt(ListRadiusColor.Count - i).Key;
  3124. int r2 = ListRadiusColor.ElementAt(ListRadiusColor.Count - 1 - i).Key;
  3125. if (r < d && d <= r2)
  3126. {
  3127. poAreaList[i]--;
  3128. break;
  3129. }
  3130. }
  3131. }
  3132. }
  3133. else if (circleCount > 1)
  3134. {
  3135. int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
  3136. for (int i = 0; i < circleCount; i++)
  3137. {
  3138. int r = Convert.ToInt32(CircleR * (i));
  3139. int r2 = Convert.ToInt32(CircleR * (i + 1));
  3140. if (r < d && d <= r2)
  3141. {
  3142. poAreaList[i]--;
  3143. break;
  3144. }
  3145. }
  3146. }
  3147. }
  3148. }
  3149. private static void CommonForEachForSel(int* value, int* position)
  3150. {
  3151. int y = position[0];
  3152. int x = position[1];
  3153. int v = *value;
  3154. if (v > 0 && keyValueSel.ContainsKey(v))
  3155. {
  3156. rgb_ap.Set<Vec3b>(y, x, new Vec3b(255, 255, 0));
  3157. }
  3158. }
  3159. /// <summary>
  3160. /// 开裂球识别霍夫圆
  3161. /// </summary>
  3162. /// <param name="src"></param>
  3163. public static Mat DrwCrackBall(Mat src)
  3164. {
  3165. temp = src.Clone();
  3166. Mat dst = new Mat();
  3167. //1:因为霍夫圆检测对噪声比较敏感,所以首先对图像做一个中值滤波或高斯滤波(噪声如果没有可以不做)
  3168. Mat m1 = new Mat();
  3169. Cv2.MedianBlur(temp, m1, 3); // ksize必须大于1且是奇数
  3170. //2:转为灰度图像
  3171. Mat m2 = m1.Clone();
  3172. // m1.Release();
  3173. Cv2.CvtColor(m1, m2, ColorConversionCodes.BGR2GRAY);
  3174. CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 130, 60, 25, 35, 80);
  3175. temp.CopyTo(dst);
  3176. //大圆
  3177. for (int i = 0; i < cs.Length; i++)
  3178. {
  3179. //画圆
  3180. 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);
  3181. //加强圆心显示
  3182. Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias);
  3183. }
  3184. Mat srcBlack;
  3185. int sucessCs = 0;
  3186. int badCs = 0;
  3187. for (int i = 0; i < cs.Length; i++)
  3188. {
  3189. int left = (int)cs[i].Center.X - (int)cs[i].Radius;
  3190. int right = (int)cs[i].Center.X + (int)cs[i].Radius;
  3191. int top = (int)cs[i].Center.Y - (int)cs[i].Radius;
  3192. int bottom = (int)cs[i].Center.Y + (int)cs[i].Radius;
  3193. if (left < 10 || right - 10 > temp.Width || top < 10 || bottom - 10 > temp.Height - 140)
  3194. {
  3195. continue;
  3196. }
  3197. srcBlack = new Mat(temp.Height, temp.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3198. //画圆
  3199. Cv2.Circle(srcBlack, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, Scalar.White, 1, LineTypes.AntiAlias);
  3200. OpenCvSharp.Point[][] contours;
  3201. HierarchyIndex[] hierarchy;
  3202. Cv2.FindContours(srcBlack, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3203. Cv2.DrawContours(srcBlack, contours, -1, Scalar.White, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3204. //取所有的点
  3205. List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
  3206. int rows = srcBlack.Height, cols = srcBlack.Width;
  3207. for (int k = 0; k < rows; k++)
  3208. {
  3209. IntPtr a = srcBlack.Ptr(k);
  3210. byte* b = (byte*)a.ToPointer();
  3211. for (int j = 0; j < cols; j++)
  3212. {
  3213. if (b[j] != 0)
  3214. {
  3215. srPoints.Add(new OpenCvSharp.Point(j, k));
  3216. }
  3217. }
  3218. }
  3219. for (int j = 0; j < srPoints.Count; j++)
  3220. {
  3221. int item = temp.Get<int>(srPoints[j].Y, srPoints[j].X);
  3222. srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
  3223. }
  3224. Rect bigrect = Cv2.BoundingRect(contours[0]);
  3225. Mat rect = new Mat(srcBlack, bigrect);
  3226. //Cv2.EqualizeHist(rect, dst);
  3227. Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
  3228. //Cv2.MedianBlur(dst, dst, 1);
  3229. Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
  3230. Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3231. Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
  3232. Mat bb = new Mat(aa.Height, aa.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3233. Cv2.Circle(bb, (int)center.X, (int)center.Y, (int)cs[i].Radius - 15, Scalar.White, 1, LineTypes.AntiAlias);
  3234. OpenCvSharp.Point[][] contoursCircleLine;
  3235. HierarchyIndex[] hierarchyLine;
  3236. Cv2.FindContours(bb, out contoursCircleLine, out hierarchyLine, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3237. List<OpenCvSharp.Point> contoursCircleLineOne = new List<OpenCvSharp.Point>();
  3238. for (int m = 0; m < contoursCircleLine.Length; m++)
  3239. {
  3240. for (int n = 0; n < contoursCircleLine[m].Length; n++)
  3241. {
  3242. contoursCircleLineOne.Add(contoursCircleLine[m][n]);
  3243. }
  3244. }
  3245. //内缩
  3246. Rect bigRect = new Rect(0, 0, rect.Width, rect.Height);
  3247. for (int nX = bigRect.X; nX <= bigRect.Right; nX++)
  3248. {
  3249. for (int nY = bigRect.Y; nY <= bigRect.Bottom; nY++)
  3250. {
  3251. double localPos = Cv2.PointPolygonTest(contoursCircleLineOne, new Point2f(nX, nY), false);
  3252. if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
  3253. {
  3254. }
  3255. else
  3256. {
  3257. aa.Set<int>(nX, nY, 0);
  3258. }
  3259. }
  3260. }
  3261. OpenCvSharp.Point[][] contours1 = new OpenCvSharp.Point[][] { };
  3262. HierarchyIndex[] hierarchy1 = new HierarchyIndex[] { };
  3263. Cv2.FindContours(aa, out contours1, out hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3264. // Cv2.CvtColor(aa, aa, ColorConversionCodes.RGB2BGR);
  3265. List<OpenCvSharp.Point[]> contoursHoleList = contours1.OrderByDescending(t => t.Count()).ToList();
  3266. //if (contoursHoleList.Count == 0)
  3267. //{
  3268. // continue;
  3269. //}
  3270. double isk = 0;
  3271. float widthto = 0;
  3272. float heightto = 0;
  3273. for (int k = 0; k < contours1.Count(); k++)
  3274. {
  3275. RotatedRect rectR = Cv2.MinAreaRect(contours1[k]); //计算每个轮廓最小外接矩形
  3276. Rect rectB = Cv2.BoundingRect(contours1[k]);
  3277. float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3278. float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3279. height = height == 0 ? 1 : height;
  3280. double distance = 0;
  3281. for (int m = 0; m < contours1[k].Count(); m++)
  3282. {
  3283. Point2f centerCoutours = new Point2f(contours1[k][m].X, contours1[k][m].Y);
  3284. distance += centerCoutours.DistanceTo(center);
  3285. }
  3286. distance = distance / contours1[k].Count();
  3287. OpenCvSharp.Point[] lineDmax = new OpenCvSharp.Point[2];
  3288. RotatedRect minRect;
  3289. // double ratio = GetDMax(contours[k], out lineDmax) / GetDMin(contours[k], out minRect);
  3290. if (distance > 55)
  3291. {
  3292. //再边缘
  3293. //Cv2.DrawContours(aa, contours, k, Scalar.Yellow, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3294. }
  3295. else if (/*ratio > 2 && */Cv2.ArcLength(contours1[k], true) < 15)
  3296. {
  3297. //像素太少的去掉
  3298. // Cv2.DrawContours(aa, contours, k, Scalar.Blue, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3299. }
  3300. else
  3301. {
  3302. widthto = widthto + width;
  3303. isk = isk + Cv2.ContourArea(contours1[k]);
  3304. if (Cv2.ContourArea(contours1[k]) > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
  3305. {
  3306. break;
  3307. }
  3308. //最终想要的裂缝
  3309. //Cv2.DrawContours(aa, contours1, k, Scalar.Green, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
  3310. List<OpenCvSharp.Point> bigmap = new List<OpenCvSharp.Point>();
  3311. foreach (OpenCvSharp.Point item in contours1[k])
  3312. {
  3313. bigmap.Add(new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y });
  3314. }
  3315. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3316. tol.Add(bigmap);
  3317. Cv2.DrawContours(temp, tol, 0, colorList[1], 1, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3318. }
  3319. }
  3320. if (isk > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
  3321. {
  3322. continue;
  3323. }
  3324. if (isk > 0)
  3325. {
  3326. heightto = (float)isk / widthto;
  3327. heightto = heightto < 1 ? 1 : heightto;
  3328. //画圆
  3329. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[1], 2, LineTypes.AntiAlias);
  3330. //加强圆心显示
  3331. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[1], 6, LineTypes.AntiAlias);
  3332. }
  3333. else
  3334. {
  3335. //画圆
  3336. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[0], 2, LineTypes.AntiAlias);
  3337. //加强圆心显示
  3338. Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[0], 6, LineTypes.AntiAlias);
  3339. }
  3340. 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 };
  3341. poList.Add(po);
  3342. }
  3343. return temp.Clone();
  3344. }
  3345. /// <summary>
  3346. /// 开裂球识别分水岭
  3347. /// </summary>
  3348. /// <param name="src"></param>
  3349. public static Mat DrwCrackBall_New(Mat src, Mat source)
  3350. {
  3351. temp = source.Clone();
  3352. Mat gray = new Mat();
  3353. Mat dst = new Mat();
  3354. Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
  3355. OpenCvSharp.Point[][] cs;
  3356. HierarchyIndex[] hierarchycs;
  3357. Cv2.FindContours(gray, out cs, out hierarchycs, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3358. particlePixles.Clear();
  3359. Mat srcBlack;
  3360. int sucessCs = 0;
  3361. int badCs = 0;
  3362. int index = 1;
  3363. double heig = (double)140 / (double)1920;
  3364. for (int i = 0; i < cs.Length; i++)
  3365. {
  3366. //边界颗粒去除
  3367. int coutp = 0;
  3368. for (int j = 0; j < cs[i].Length; j++)
  3369. {
  3370. int cspx = cs[i][j].X;
  3371. int cspy = cs[i][j].Y;
  3372. if (cspx == 0 || cspy == 0 || cspx > src.Cols - 5 || cspy > src.Rows - heig * src.Rows - 5)
  3373. {
  3374. coutp++;
  3375. }
  3376. }
  3377. if (coutp > 5)
  3378. {
  3379. continue;
  3380. }
  3381. //面积过小去除
  3382. if (Cv2.ContourArea(cs[i]) < 4000)
  3383. {
  3384. continue;
  3385. }
  3386. Rect bigrect = Cv2.BoundingRect(cs[i]);
  3387. if (CreackBallPointFs.Count > 0)
  3388. {
  3389. bool isnei = false;
  3390. foreach (var item in CreackBallPointFs)
  3391. {
  3392. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3393. if (dq > 0)
  3394. {
  3395. isnei = true;
  3396. break;
  3397. }
  3398. }
  3399. if (isnei)
  3400. {
  3401. continue;
  3402. }
  3403. }
  3404. //圆度过大去除
  3405. //afa参考代码
  3406. double s = Cv2.ContourArea(cs[i]);//轮廓面积
  3407. double c = Cv2.ArcLength(cs[i], true); //轮廓周长
  3408. double afa = 4 * Math.PI * s / (c * c); //afa计算
  3409. afa = Math.Abs(afa - 1);
  3410. //if (afa > 0.6)
  3411. //{
  3412. // continue;
  3413. //}
  3414. afa = afa * 1000;
  3415. if (CreackBallPointFsK.Count > 0)
  3416. {
  3417. bool isnei = false;
  3418. foreach (var item in CreackBallPointFsK)
  3419. {
  3420. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3421. if (dq > 0)
  3422. {
  3423. isnei = true;
  3424. break;
  3425. }
  3426. }
  3427. if (isnei)
  3428. {
  3429. Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3430. List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 1, (int)afa };
  3431. poList.Add(po1);
  3432. continue;
  3433. }
  3434. }
  3435. if (CreackBallPointFsP.Count > 0)
  3436. {
  3437. bool isnei = false;
  3438. foreach (var item in CreackBallPointFsP)
  3439. {
  3440. double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
  3441. if (dq > 0)
  3442. {
  3443. isnei = true;
  3444. break;
  3445. }
  3446. }
  3447. if (isnei)
  3448. {
  3449. Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3450. List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 0, (int)afa };
  3451. poList.Add(po1);
  3452. continue;
  3453. }
  3454. }
  3455. srcBlack = new Mat(gray.Height, gray.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
  3456. Cv2.DrawContours(srcBlack, cs, i, Scalar.White, -1, LineTypes.Link4, hierarchycs, 2, new OpenCvSharp.Point(0, 0));
  3457. //取所有的点
  3458. List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
  3459. int rows = srcBlack.Height,
  3460. cols = srcBlack.Width;
  3461. for (int k = 0; k < rows; k++)
  3462. {
  3463. IntPtr a = srcBlack.Ptr(k);
  3464. byte* b = (byte*)a.ToPointer();
  3465. for (int j = 0; j < cols; j++)
  3466. {
  3467. if (b[j] != 0)
  3468. {
  3469. srPoints.Add(new OpenCvSharp.Point(j, k));
  3470. }
  3471. }
  3472. }
  3473. for (int j = 0; j < srPoints.Count; j++)
  3474. {
  3475. int item = source.Get<int>(srPoints[j].Y, srPoints[j].X);
  3476. srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
  3477. }
  3478. double outR = Math.Sqrt(s / Math.PI) * 0.5;
  3479. double dist = 0;
  3480. double maxdist = 0;
  3481. //中心点
  3482. OpenCvSharp.Point ballCenter = new OpenCvSharp.Point();
  3483. foreach (var item in srPoints)
  3484. {
  3485. dist = Cv2.PointPolygonTest(cs[i], item, true);
  3486. if (dist > maxdist)
  3487. {
  3488. maxdist = dist;
  3489. ballCenter = item;
  3490. }
  3491. }
  3492. List<OpenCvSharp.Point> sel = new List<OpenCvSharp.Point>();
  3493. for (int k = 0; k < cs[i].Length; k++)
  3494. {
  3495. sel.Add(cs[i][k]);
  3496. }
  3497. Mat rect = new Mat(srcBlack, bigrect);
  3498. Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
  3499. Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
  3500. for (int x = 0; x < aa.Cols; x++)
  3501. {
  3502. for (int y = 0; y < aa.Rows; y++)
  3503. {
  3504. double localPos = Cv2.PointPolygonTest(sel, new Point2f(x + bigrect.X, y + bigrect.Y), false);
  3505. if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
  3506. {
  3507. }
  3508. else
  3509. {
  3510. aa.Set<int>(y, x, 0);
  3511. }
  3512. }
  3513. }
  3514. InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
  3515. //开操作,也可省落变量前缀名
  3516. Cv2.MorphologyEx(aa, aa, MorphTypes.Dilate, kernel, new OpenCvSharp.Point(-1, -1));
  3517. OpenCvSharp.Point[][] contours;
  3518. HierarchyIndex[] hierarchy;
  3519. Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
  3520. List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t.Count()).ToList();
  3521. double isk = 0;
  3522. float widthto = 0;
  3523. double heightto = 0;
  3524. double arclength = 0;
  3525. Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
  3526. double area = Cv2.ContourArea(cs[i]);
  3527. double ra = aa.Cols < aa.Rows ? aa.Cols / 2 : aa.Rows / 2;
  3528. for (int k = 0; k < contoursHoleList.Count(); k++)
  3529. {
  3530. double tarea = Cv2.ContourArea(contoursHoleList[k]);
  3531. RotatedRect rectR = Cv2.MinAreaRect(contoursHoleList[k]); //计算每个轮廓最小外接矩形
  3532. Rect rectB = Cv2.BoundingRect(contoursHoleList[k]);
  3533. float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3534. float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
  3535. height = height == 0 ? 1 : height;
  3536. List<OpenCvSharp.Point> poingtForUse = new List<OpenCvSharp.Point>();
  3537. List<OpenCvSharp.Point> tempList = new List<OpenCvSharp.Point>();
  3538. int outCount = 0;
  3539. foreach (OpenCvSharp.Point item in contoursHoleList[k])
  3540. {
  3541. OpenCvSharp.Point point1 = new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y };
  3542. double d = Cv2.PointPolygonTest(cs[i], point1, true);
  3543. tempList.Add(point1);
  3544. if (d < 5)
  3545. {
  3546. outCount++;
  3547. }
  3548. }
  3549. if (((outCount * 100) / contoursHoleList[k].Count()) < 70)
  3550. {
  3551. tempList.ForEach(p => poingtForUse.Add(p));
  3552. }
  3553. // double ratio = GetDMax(contoursHoleList[k], out lineDmax) / GetDMin(contoursHoleList[k], out minRect);
  3554. double carea = Cv2.ContourArea(contoursHoleList[k]);
  3555. double cleng = Cv2.ArcLength(contoursHoleList[k], true); //轮廓周长
  3556. double cafa = 4 * Math.PI * s / (c * c); //afa计算
  3557. cafa = Math.Abs(cafa - 1);
  3558. if (poingtForUse.Count < 25)
  3559. {
  3560. }
  3561. else if (cleng < 30)
  3562. {
  3563. }
  3564. else
  3565. {
  3566. arclength = arclength + Cv2.ArcLength(contoursHoleList[k], true);
  3567. widthto = widthto + width;
  3568. isk = isk + Cv2.ContourArea(contoursHoleList[k]);
  3569. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3570. tol.Add(poingtForUse);
  3571. Cv2.DrawContours(temp, tol, 0, colorList[1], -1, LineTypes.Link8, null, 2, new OpenCvSharp.Point(0, 0));
  3572. //for (int p = 0; p < poingtForUse.Count(); p++)
  3573. //{
  3574. // temp.Set<Vec4b>(poingtForUse[p].Y, poingtForUse[p].X, vec4BList[1]);
  3575. //}
  3576. }
  3577. }
  3578. if (isk > 0)
  3579. {
  3580. heightto = isk / arclength;
  3581. heightto = heightto < 1 ? 1 : heightto;
  3582. Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3583. }
  3584. else
  3585. {
  3586. Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3587. }
  3588. particlePixles.Add(index++, sel);
  3589. 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 };
  3590. poList.Add(po);
  3591. }
  3592. return temp.Clone();
  3593. }
  3594. /// <summary>
  3595. /// 开裂球选择
  3596. /// </summary>
  3597. /// <param name="src"></param>
  3598. /// <returns></returns>
  3599. private static Mat SelectBall(Mat src, int x, int y, int r)
  3600. {
  3601. temp = src.Clone();
  3602. //画圆
  3603. // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
  3604. //加强圆心显示
  3605. Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
  3606. return temp;
  3607. }
  3608. /// <summary>
  3609. /// 开裂球选择
  3610. /// </summary>
  3611. /// <param name="src"></param>
  3612. /// <returns></returns>
  3613. private static Mat SelectBallInt(Mat src, int index)
  3614. {
  3615. temp = src.Clone();
  3616. //画圆
  3617. // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
  3618. List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
  3619. tol.Add(particlePixles[index]);
  3620. Cv2.DrawContours(temp, tol, 0, colorList[4], 4, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
  3621. RotatedRect rectR = Cv2.MinAreaRect(particlePixles[index]);
  3622. double are = Cv2.ContourArea(particlePixles[index]);
  3623. //加强圆心显示
  3624. // Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
  3625. return temp;
  3626. }
  3627. private static void GetHalfCircles(Mat color)
  3628. {
  3629. Mat canny = new Mat();
  3630. Mat gray = new Mat();
  3631. Cv2.CvtColor(color, gray, ColorConversionCodes.BGRA2GRAY);
  3632. Cv2.Canny(gray, canny, 200, 20);
  3633. CircleSegment[] circles = Cv2.HoughCircles(gray, HoughMethods.Gradient, 1, 80, 70, 24, 33, 52);
  3634. for (int i = 0; i < circles.Length; i++)
  3635. {
  3636. //加强圆心显示
  3637. Cv2.Circle(color, (int)circles[i].Center.X, (int)circles[i].Center.Y, 3, new Scalar(0, 255, 255), -1, LineTypes.AntiAlias);
  3638. //画圆
  3639. 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);
  3640. }
  3641. Mat dt = new Mat();
  3642. Cv2.BitwiseNot(canny, canny);
  3643. Cv2.DistanceTransform(canny, dt, DistanceTypes.L2, DistanceMaskSize.Mask3);
  3644. float minInlierDist = 2.0f;
  3645. for (int i = 0; i < circles.Length; i++)
  3646. {
  3647. int counter = 0;
  3648. int inlier = 0;
  3649. Point2f center = circles[i].Center;
  3650. float radius = circles[i].Radius;
  3651. float maxInlierDist = radius / 25.0f;
  3652. if (maxInlierDist < minInlierDist) maxInlierDist = minInlierDist;
  3653. for (float t = 0; t < 2 * Math.PI; t += 0.1f)
  3654. {
  3655. counter++;
  3656. float cX = radius * (float)Math.Cos(t) + circles[i].Center.X;
  3657. float cY = radius * (float)Math.Sin(t) + circles[i].Center.Y;
  3658. if (cX < 0)
  3659. {
  3660. cX = 0;
  3661. }
  3662. if (cY < 0)
  3663. {
  3664. cY = 0;
  3665. }
  3666. if (dt.At<float>((int)cY, (int)cX) < maxInlierDist)
  3667. {
  3668. inlier++;
  3669. Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(0, 255, 0));
  3670. }
  3671. else
  3672. {
  3673. Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(255, 0, 0));
  3674. }
  3675. }
  3676. }
  3677. using (new Window("color", WindowMode.Normal, color))
  3678. {
  3679. Cv2.WaitKey(0);
  3680. }
  3681. }
  3682. /// <summary>
  3683. /// 二值提取隔膜
  3684. /// </summary>
  3685. /// <param name="source">源</param>
  3686. /// <param name="colorInterval">1个或2个颜色区间</param>
  3687. /// <param name="colorOneStart"></param>
  3688. /// <param name="colorOneEnd"></param>
  3689. /// <param name="colorTwoStart"></param>
  3690. /// <param name="colorTwoEnd"></param>
  3691. /// <param name="colorThreeStart"></param>
  3692. /// <param name="colorThreeEnd"></param>
  3693. /// <returns></returns>
  3694. private static Mat BinarizationForM(Mat source)
  3695. {
  3696. Mat srcGray;
  3697. if (source.Type() == MatType.CV_8UC1)
  3698. {
  3699. srcGray = source;
  3700. }
  3701. else
  3702. {
  3703. srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
  3704. }
  3705. temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
  3706. try
  3707. {
  3708. srcGray.ForEachAsByte(GrayForEachAsByteForM);
  3709. }
  3710. catch (Exception)
  3711. {
  3712. throw;
  3713. }
  3714. return temp.Clone();
  3715. }
  3716. /// <summary>
  3717. /// 并行循环
  3718. /// </summary>
  3719. /// <param name="value"></param>
  3720. /// <param name="position"></param>
  3721. private static void GrayForEachAsByteForM(byte* value, int* position)
  3722. {
  3723. int y = position[0];
  3724. int x = position[1];
  3725. byte v = *value;
  3726. if (v >= colorOneStart && v <= colorOneEnd && y < imageHight - 70)
  3727. {
  3728. temp.Set<Vec4b>(y, x, vec4B);
  3729. }
  3730. }
  3731. }
  3732. }