123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245 |
- using OpenCvSharp;
- using PaintDotNet.Adjust.BaseImage;
- using PaintDotNet.Base;
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Linq;
- namespace PaintDotNet.Adjust
- {
- public unsafe class Battery
- {
- /// <summary>
- /// 全局中间变量
- /// 不带视场的时候就是原图/二值图
- /// 带视场的时候就是原图/二值图
- /// </summary>
- public static Mat temp, temp_view;
- /// <summary>
- /// 用来存储透明图
- /// </summary>
- public static Mat alpha;
- /// <summary>
- /// 1个颜色区间还是2个
- /// </summary>
- public static int colorInterval;
- /// <summary>
- /// 1个颜色区间时的起始值
- /// </summary>
- public static int colorOneStart;
- /// <summary>
- /// 1个颜色区间时的结止值
- /// </summary>
- public static int colorOneEnd;
- /// <summary>
- /// 2个颜色区间时的第1个区间的起始值
- /// </summary>
- public static int colorTwoStart = 0;
- /// <summary>
- /// 2个颜色区间时的第1个区间的结止值
- /// </summary>
- public static int colorTwoEnd = 0;
- /// <summary>
- /// 2个颜色区间时的第2个区间的起始值
- /// </summary>
- public static int colorThreeStart = 0;
- /// <summary>
- /// 2个颜色区间时的第2个区间的起始值
- /// </summary>
- public static int colorThreeEnd = 0;
- //碎屑删除面积起
- public static int debrisAreaStart = 0;
- //图片类型,1同心圆孔隙2单晶3二次球与单晶
- public static int imageType = 1;
- //碎屑删除面积止
- public static int debrisAreaEnd = 0;
- /// <summary>
- /// 默认相颜色
- /// </summary>
- public static Vec4b vec4B = new Vec4b(255, 0, 0, 255);
- /// <summary>
- /// 默认相颜色
- /// </summary>
- public static Vec4b vec4Bw = new Vec4b(0, 0, 0, 0);
- /// <summary>
- /// 新增的参数,用于FloodFill方法
- /// </summary>
- public static Rect rect;
- /// <summary>
- /// 各个连通域的代表点
- /// </summary>
- public static List<OpenCvSharp.Point> points;
- /// <summary>
- /// 用来记录需要删除的连通区域的编号
- /// </summary>
- public static Dictionary<int, int> keyValuePairs = new Dictionary<int, int>();
- /// <summary>
- /// 用来记录选择的连通区域的编号
- /// </summary>
- public static Dictionary<int, int> keyValueSel = new Dictionary<int, int>();
- public static Mat rgb_ap;
- public static Mat temp_ap;
- //碎屑删除面积止
- public static int poArea = 0;
- //孔隙同心圆面积
- public static List<int> poAreaList = new List<int>() { };
- //孔隙信息,孔隙的x,y,width,height,area,id
- public static List<List<int>> poList = new List<List<int>> { };
- //开裂球历史记录
- public static List<List<int>> poListHis = new List<List<int>> { };
- //同心圆数
- public static int circleCount = 0;
- //最大轮廓
- public static OpenCvSharp.Point[] maxContour = new OpenCvSharp.Point[] { };
- //同心圆半径
- public static int CircleR = 0;
- //同心圆半径
- public static OpenCvSharp.Point center = new OpenCvSharp.Point();
- //删除孔隙
- public static List<PointF> delPointFs = new List<PointF>();
- //选择孔隙
- public static int selPointFs = -1;
- //记录联通区域
- public static Mat labelMatForSel = new Mat();
- //记录新增联通区域
- public static OpenCvSharp.Point[][] labelMatForSelAdd;
- //记录联通区域数量
- public static int fieldsCount = 0;
- //处理后的mat
- public static Mat retMat = new Mat();
- //同心圆颜色列表
- 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) };
- 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) };
- //所有点
- public static Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- //轮廓面积
- public static int maxArea = 0;
- //图像高度
- public static int imageHight = 0;
- //图像高度
- public static int imageWidth = 0;
- //二次球点
- public static List<PointF> BallPointFs = new List<PointF>();
- //二次球单晶点
- public static List<PointF> CrystalPointFs = new List<PointF>();
- //二次球轮廓
- public static List<List<PointF>> CrystalLunkuo = new List<List<PointF>>();
- //二次球模糊系数
- public static int BlurSiaze = 15;
- //二次球阈值
- public static int param2 = 24;
- //二次球最小半径
- public static int minRadius = 33;
- //二次球最大半径
- public static int maxRadius = 52;
- //去边界
- public static int boundary = 0;
- //去底边
- public static double borderBottom = 0;
- //忽略开裂球
- public static List<PointF> CreackBallPointFs = new List<PointF>();
- //设为开裂球
- public static List<PointF> CreackBallPointFsK = new List<PointF>();
- //设为普通球
- public static List<PointF> CreackBallPointFsP = new List<PointF>();
- //小颗粒
- public static double pointsize = 0.1;
- //标尺
- public static double Micron = 0.01;
- //边缘
- public static int border = 1;
- //长宽比
- public static double HW = 1;
- //面积率
- public static double AreaRatio = 1;
- //添加单晶
- public static List<List<OpenCvSharp.Point>> AddPontins = new List<List<OpenCvSharp.Point>>();
- //连通域集合
- static List<List<OpenCvSharp.Point>> AllFields = new List<List<OpenCvSharp.Point>>();
- //二次球测量区域
- public static List<OpenCvSharp.Point> Contour = new List<OpenCvSharp.Point>();
- //手动画同心圆半径和颜色
- public static Dictionary<int, Color> ListRadiusColor = new Dictionary<int, Color>();
- //是否画测距
- public static bool isDis = false;
- //是否画矩形
- public static bool isJu = false;
- #region 无视场 二值提取
- /// <summary>
- /// 二值操作-二值提取-无视场
- /// </summary>
- /// <param name="src">源图像</param>
- /// <param name="lists">参数集合</param>
- /// <returns></returns>
- public static Mat ImageBinaryExtraction(Mat src, List<Args> lists, bool findContours = false)
- {
- //以下是参数信息---------------------
- ///1个颜色区间还是2个
- colorInterval = 1;
- //第一个二值区间
- colorOneStart = 0;
- colorOneEnd = 0;
- //第二个二值区间
- colorTwoStart = 0;
- colorTwoEnd = 0;
- //第三个二值区间
- colorThreeStart = 0;
- colorThreeEnd = 0;
- //处理细节
- //删除边界对象
- bool deleteBoundaryObject = false;
- //孔洞填充
- bool holeFilling = false;
- //碎屑删除
- bool debrisRemoval = false;
- //碎屑删除面积起
- debrisAreaStart = 0;
- //碎屑删除面积止
- debrisAreaEnd = 0;
- //二值样式
- //1实心 2边线
- int binaryStyle = 0;
- //相颜色
- Color phaseColor = Color.Red;
- //目标选择
- int targetSelection = 1;
- for (int i = 0; i < lists.Count; i++)
- {
- Args args = lists[i];
- switch (args.Key)
- {
- case "colorInterval":
- {
- if (args.Value is Boolean)
- colorInterval = (Boolean)args.Value ? 2 : 1;
- else
- colorInterval = (int)args.Value;
- }
- break;
- case "scope1":
- colorOneStart = (int)((List<double>)args.Value)[0];
- colorOneEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope2":
- colorTwoStart = (int)((List<double>)args.Value)[0];
- colorTwoEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope3":
- colorThreeStart = (int)((List<double>)args.Value)[0];
- colorThreeEnd = (int)((List<double>)args.Value)[1];
- break;
- case "deleteBoundaryObject":
- deleteBoundaryObject = (bool)args.Value;
- break;
- case "holeFilling":
- holeFilling = (bool)args.Value;
- break;
- case "debrisRemoval":
- debrisRemoval = (bool)args.Value;
- break;
- case "binaryStyle":
- binaryStyle = (int)args.Value;
- break;
- case "phaseColor":
- phaseColor = Color.FromArgb((int)args.Value);
- break;
- case "targetSelection":
- targetSelection = (int)args.Value;
- break;
- case "scope4":
- debrisAreaStart = (int)((List<double>)args.Value)[0];
- debrisAreaEnd = (int)((List<double>)args.Value)[1];
- findContours = true;
- break;
- case "imageType":
- imageType = (int)args.Value;
- break;
- default:
- break;
- }
- }
- if (phaseColor.A < 1)//#21321
- phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
- vec4B.Item0 = phaseColor.B;
- vec4B.Item1 = phaseColor.G;
- vec4B.Item2 = phaseColor.R;
- vec4B.Item3 = phaseColor.A;
- //中值滤波
- //Cv2.MedianBlur(src, src, 3);
- //二值提取
- src = Binarization(src);
- //碎屑删除,参考冈萨雷斯,414,9.5.3,连通分量提取
- // if (debrisRemoval && debrisAreaEnd > 0)
- src = DebrisRemoval_New(src);
- //实心/边线,参考冈萨雷斯,412,9.5.1,边界提取
- Cv2.Erode(src, temp, null);
- src = src - temp;
- src = BaseTools.MergeMatFromMatArr(src, vec4B);
- return src;
- }
- /// <summary>
- /// 前驱截面
- /// </summary>
- /// <param name="src">源图像</param>
- /// <param name="lists">参数集合</param>
- /// <returns></returns>
- public static Mat ImageBinaryExtraction(Mat src, List<Args> lists, out List<List<int>> data, bool findContours = false)
- {
- //以下是参数信息---------------------
- ///1个颜色区间还是2个
- colorInterval = 1;
- //第一个二值区间
- colorOneStart = 0;
- colorOneEnd = 0;
- //第二个二值区间
- colorTwoStart = 0;
- colorTwoEnd = 0;
- //第三个二值区间
- colorThreeStart = 0;
- colorThreeEnd = 0;
- boundary = 0;
- //处理细节
- //删除边界对象
- bool deleteBoundaryObject = false;
- //孔洞填充
- bool holeFilling = false;
- //碎屑删除
- bool debrisRemoval = false;
- //碎屑删除面积起
- debrisAreaStart = 0;
- //碎屑删除面积止
- debrisAreaEnd = 0;
- //二值样式
- //1实心 2边线
- int binaryStyle = 0;
- //相颜色
- Color phaseColor = Color.Red;
- //目标选择
- int targetSelection = 1;
- for (int i = 0; i < lists.Count; i++)
- {
- Args args = lists[i];
- switch (args.Key)
- {
- case "colorInterval":
- {
- if (args.Value is Boolean)
- colorInterval = (Boolean)args.Value ? 2 : 1;
- else
- colorInterval = (int)args.Value;
- }
- break;
- case "scope1":
- colorOneStart = (int)((List<double>)args.Value)[0];
- colorOneEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope2":
- colorTwoStart = (int)((List<double>)args.Value)[0];
- colorTwoEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope3":
- colorThreeStart = (int)((List<double>)args.Value)[0];
- colorThreeEnd = (int)((List<double>)args.Value)[1];
- break;
- case "deleteBoundaryObject":
- deleteBoundaryObject = (bool)args.Value;
- break;
- case "holeFilling":
- holeFilling = (bool)args.Value;
- break;
- case "debrisRemoval":
- debrisRemoval = (bool)args.Value;
- break;
- case "binaryStyle":
- binaryStyle = (int)args.Value;
- break;
- case "phaseColor":
- phaseColor = Color.FromArgb((int)args.Value);
- break;
- case "targetSelection":
- targetSelection = (int)args.Value;
- break;
- case "scope4":
- debrisAreaStart = (int)((List<double>)args.Value)[0];
- debrisAreaEnd = (int)((List<double>)args.Value)[1];
- findContours = true;
- break;
- case "CircleCount":
- circleCount = (int)args.Value;
- break;
- case "maxContour":
- maxContour = (OpenCvSharp.Point[])args.Value;
- break;
- case "CircleR":
- CircleR = (int)args.Value;
- break;
- case "Center":
- center = (OpenCvSharp.Point)args.Value;
- break;
- case "DelPointFs":
- delPointFs = (List<PointF>)args.Value;
- break;
- case "imageType":
- imageType = (int)args.Value;
- break;
- case "SelPointFs":
- selPointFs = (int)args.Value;
- break;
- case "imageTypes":
- imageType = (int)args.Value;
- break;
- case "BlurSiaze":
- BlurSiaze = (int)args.Value;
- break;
- case "param2":
- param2 = (int)args.Value;
- break;
- case "minRadius":
- minRadius = (int)args.Value;
- break;
- case "maxRadius":
- maxRadius = (int)args.Value;
- break;
- case "boundary":
- boundary = (int)args.Value;
- break;
- case "BallPointFs":
- BallPointFs = (List<PointF>)args.Value;
- break;
- case "CrystalPointFs":
- CrystalPointFs = (List<PointF>)args.Value;
- break;
- case "CrystalLunkuo":
- CrystalLunkuo = (List<List<PointF>>)args.Value;
- break;
- case "AddPontins":
- AddPontins = (List<List<OpenCvSharp.Point>>)args.Value;
- break;
- case "pointsize":
- pointsize = (double)args.Value;
- break;
- case "Micron":
- Micron = (double)args.Value;
- break;
- case "border":
- border = (int)args.Value;
- break;
- case "HW":
- HW = (double)args.Value;
- break;
- case "AreaRatio":
- AreaRatio = (double)args.Value;
- break;
- case "Contour":
- Contour = (List<OpenCvSharp.Point>)args.Value;
- break;
- case "ListRadiusColor":
- ListRadiusColor = (Dictionary<int, Color>)args.Value;
- break;
- case "isDis":
- isDis = (bool)args.Value;
- break;
- case "isJu":
- isJu = (bool)args.Value;
- break;
- case "borderBottom":
- borderBottom = (int)args.Value;
- break;
- default:
- break;
- }
- }
- if (phaseColor.A < 1)//#21321
- phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
- temp_view = src.Clone();
- vec4B.Item0 = phaseColor.B;
- vec4B.Item1 = phaseColor.G;
- vec4B.Item2 = phaseColor.R;
- vec4B.Item3 = phaseColor.A;
- poArea = 0;
- maxArea = 0;
- poList.Clear();
- poAreaList = new List<int>() { };
- data = poList;
- imageHight = src.Rows;
- imageWidth = src.Cols;
- if (imageType == 1)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- src = SelectPoint(used);
- }
- else
- {
-
- if (ListRadiusColor.Count > 0)
- {
- for (int i = 0; i < ListRadiusColor.Count; i++)
- {
- poAreaList.Add(0);
- }
- ListRadiusColor = ListRadiusColor.OrderByDescending(c => c.Key).ToDictionary(pair => pair.Key, pair => pair.Value);
- }
- else if (circleCount > 0)
- {
- for (int i = 0; i < circleCount; i++)
- {
- poAreaList.Add(0);
- }
- }
- //二值提取
- src = Binarization(src);
- //using (new Window("InputImage", WindowMode.Normal, src))
- //{
- // Cv2.WaitKey(0);
- //}
- //去掉过小孔隙,计算孔隙面积
- src = DebrisRemoval_New(src);
- //using (new Window("InputImage1", WindowMode.Normal, src))
- //{
- // Cv2.WaitKey(0);
- //}
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { maxContour };
- Cv2.DrawContours(src, contours, 0, new Scalar(255, 144, 30, 255), 2);
- if (circleCount > 1)
- {
- for (int i = 0; i < circleCount; i++)
- {
- Cv2.Circle(src, center, Convert.ToInt32(CircleR * (i + 1)), colorList[i], 2);
- }
- }
- poAreaList.Add(poArea);
- poAreaList.Add(maxArea);
- data.Insert(0, poAreaList);
- retMat = src.Clone();
- ListRadiusColor.Clear();
- }
- keyValueSel.Clear();
- selPointFs = -1;
- }
- else if (imageType == 2)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- src = SelectPoint(used);
- keyValueSel.Clear();
- selPointFs = -1;
- }
- else
- {
- src = WhirtBinarization(src);
- Mat srcGray = src.CvtColor(ColorConversionCodes.BGRA2BGR);
- Mat dst = new Mat();
- //双边滤波
- Cv2.BilateralFilter(srcGray, dst, 21, 132, 181);
- Mat canny = new Mat();
- Mat gray = new Mat(); Mat andmet = new Mat();
- Cv2.GaussianBlur(dst, canny, new OpenCvSharp.Size(3, 3), 40);
- Cv2.CvtColor(canny, gray, ColorConversionCodes.BGR2GRAY);
- andmet = gray.Clone();
- Cv2.Canny(gray, gray, 100, 100);
- Cv2.Dilate(gray, gray, null);
- Cv2.Dilate(gray, gray, null);
- Cv2.Erode(gray, gray, null);
- Cv2.GaussianBlur(gray, gray, new OpenCvSharp.Size(3, 3), 10);
- gray = DebrisRemoval_CrystCanny(gray);
- Mat notmet = gray.Clone();
- Cv2.BitwiseNot(notmet, notmet);
- Cv2.Threshold(andmet, andmet, colorOneStart, colorOneEnd, ThresholdTypes.Binary);
- for (int i = 0; i < 4; i++)
- {
- Cv2.Dilate(andmet, andmet, null);
- }
- for (int i = 0; i < 4; i++)
- {
- Cv2.Erode(andmet, andmet, null);
- }
- Cv2.BitwiseAnd(notmet, andmet, andmet);
- Cv2.MedianBlur(andmet, andmet, 9);
- //二值提取
- src = Binarization(andmet);
- }
- }
- else if (imageType == 12)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- if (selPointFs >= fieldsCount)
- {
- Cv2.DrawContours(used, labelMatForSelAdd, selPointFs- fieldsCount, new Scalar(255, 255, vec4B.Item2, vec4B.Item3), -1);
- src= used.Clone();
- }
- else
- {
- keyValueSel.Add(selPointFs, 1);
- src = SelectPoint(used);
- keyValueSel.Clear();
- }
- selPointFs = -1;
- }
- else
- {
-
-
- src = DebrisRemoval_Cryst(src);
-
- retMat = src.Clone();
- }
- }
- else if (imageType == 3)
- {
- src = WhirtBinarization(src);
- List<int> circleList = new List<int>();
- List<int> circleAreaList = new List<int>();
- Mat dst = new Mat();
- Mat m1 = new Mat();
- Cv2.MedianBlur(src, m1, BlurSiaze); // ksize必须大于1且是奇数
- //2:转为灰度图像
- Mat hb = new Mat(src.Rows, src.Cols, MatType.CV_8UC1);
- Mat m2 = m1.Clone();
- Cv2.CvtColor(m1, m2, ColorConversionCodes.BGR2GRAY);
- //3:霍夫圆检测:使用霍夫变换查找灰度图像中的圆。
- /*
- * 参数:
- * 1:输入参数: 8位、单通道、灰度输入图像
- * 2:实现方法:目前,唯一的实现方法是HoughCirclesMethod.Gradient
- * 3: dp :累加器分辨率与图像分辨率的反比。默认=1
- * 4:minDist: 检测到的圆的中心之间的最小距离。(最短距离-可以分辨是两个圆的,否则认为是同心圆- src_gray.rows/8)
- * 5:param1: 第一个方法特定的参数。[默认值是100] canny边缘检测阈值低
- * 6:param2: 第二个方法特定于参数。[默认值是100] 中心点累加器阈值 – 候选圆心
- * 7:minRadius: 最小半径
- * 8:maxRadius: 最大半径
- *
- */
- CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 80, 70, param2, minRadius, maxRadius);
- src.CopyTo(dst);
- int one = 0;
- int two = 0;
- int three = 0;
- int four = 0;
- double oneA = 0;
- double twoA = 0;
- double threeA = 0;
- double fourA = 0;
- int helfx = src.Cols / 2;
- int helfy = (src.Rows - 70) / 2;
- List<int> delKey = new List<int>();
- List<List<PointF>> trmpList = new List<List<PointF>>();
- CrystalLunkuo.ForEach(s => trmpList.Add(s));
- //大圆
- for (int i = 0; i < cs.Length; i++)
- {
- if (CrystalPointFs.Count > 0)
- {
- int isCrystal = 0;
- foreach (var item in CrystalPointFs)
- {
- Point2f pin = new Point2f(item.X, item.Y);
- double distanc = pin.DistanceTo(cs[i].Center);
- if (distanc < cs[i].Radius)
- {
- isCrystal = 1;
- break;
- }
- }
- if (isCrystal == 1)
- {
- delKey.Add(i);
- continue;
- }
- }
- //手画圆轮廓
- if (trmpList.Count > 0)
- {
- int del = -1;
- for (int lk = 0; lk < trmpList.Count; lk++)
- {
- List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
- trmpList[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
- Point2f newcenter = new Point2f();
- float newR = 0;
- Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
- if (newcenter.DistanceTo(cs[i].Center) < cs[i].Radius)
- {
- cs[i].Center = newcenter;
- cs[i].Radius = newR;
- del = lk;
- break;
- }
- }
- if (del >= 0)
- {
- trmpList.RemoveAt(del);
- }
- }
- double area = Math.PI * cs[i].Radius * cs[i].Radius;
- if ((int)cs[i].Center.X < helfx && (int)cs[i].Center.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- }
- if ((int)cs[i].Center.X < helfx && (int)cs[i].Center.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- }
- if ((int)cs[i].Center.X > helfx && (int)cs[i].Center.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- }
- if ((int)cs[i].Center.X > helfx && (int)cs[i].Center.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- }
- //画圆
- 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);
- //加强圆心显示
- Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 0), 2, LineTypes.AntiAlias);
- //画圆
- Cv2.Circle(hb, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, new Scalar(255), -1, LineTypes.AntiAlias);
- }
- //手画圆轮廓
- if (trmpList.Count > 0)
- {
- for (int lk = 0; lk < trmpList.Count; lk++)
- {
- List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
- trmpList[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
- Point2f newcenter = new Point2f();
- float newR = 0;
- Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
- Cv2.Circle(dst, (int)newcenter.X, (int)newcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- //加强圆心显示
- Cv2.Circle(dst, (int)newcenter.X, (int)newcenter.Y, (int)newR, new Scalar(0, 0, 0), -1, LineTypes.AntiAlias);
- //画圆
- Cv2.Circle(hb, (int)newcenter.X, (int)newcenter.Y, (int)newR, new Scalar(255), -1, LineTypes.AntiAlias);
- double CircleArea = Math.PI * newR * newR;
- if ((int)newcenter.X < helfx && newcenter.Y < helfy)
- {
- one++;
- oneA = oneA + CircleArea;
- }
- if ((int)newcenter.X < helfx && (int)newcenter.Y > helfy)
- {
- two++;
- twoA = twoA + CircleArea;
- }
- if ((int)newcenter.X > helfx && (int)newcenter.Y < helfy)
- {
- three++;
- threeA = threeA + CircleArea;
- }
- if ((int)newcenter.X > helfx && (int)newcenter.Y > helfy)
- {
- four++;
- fourA = fourA + CircleArea;
- }
- }
- }
- Mat oldDst = dst.Clone();
- if (boundary > 0)
- {
- //去边界
- dst = BallCutBottor(dst);
- //左上
- Rect rectL1 = new Rect(0, 0, helfx, helfy);
- Mat MatL1 = new Mat(hb, rectL1);
- int areaAllL1 = MatL1.CountNonZero();
- Rect rectL1Cut = new Rect(boundary, boundary, helfx - boundary, helfy - boundary);
- Mat MatL1Cut = new Mat(hb, rectL1Cut);
- int areaCut = MatL1Cut.CountNonZero();
- int oneCut = areaAllL1 - areaCut;
- oneA = oneA - oneCut;
- //左下
- Rect rectL2 = new Rect(0, helfy, helfx, helfy);
- Mat MatL2 = new Mat(hb, rectL2);
- int areaAllL2 = MatL2.CountNonZero();
- Rect rectL2Cut = new Rect(boundary, helfy, helfx - boundary, helfy - boundary);
- Mat MatL2Cut = new Mat(hb, rectL2Cut);
- int areaCutL2 = MatL2Cut.CountNonZero();
- int oneCutL2 = areaAllL2 - areaCutL2;
- twoA = twoA - oneCutL2;
- //右上
- Rect rectR1 = new Rect(helfx, 0, helfx, helfy);
- Mat MatR1 = new Mat(hb, rectR1);
- int areaAllR1 = MatR1.CountNonZero();
- Rect rectR1Cut = new Rect(helfx, boundary, helfx - boundary, helfy - boundary);
- Mat MatR1Cut = new Mat(hb, rectR1Cut);
- int areaCutR1 = MatR1Cut.CountNonZero();
- int oneCutR1 = areaAllR1 - areaCutR1;
- threeA = threeA - oneCutR1;
- //右下
- Rect rectR2 = new Rect(helfx, helfy, helfx, helfy);
- Mat MatR2 = new Mat(hb, rectR2);
- int areaAllR2 = MatR2.CountNonZero();
- Rect rectR2Cut = new Rect(helfx, helfy, helfx - boundary, helfy - boundary);
- Mat MatR2Cut = new Mat(hb, rectR2Cut);
- int areaCutR2 = MatR2Cut.CountNonZero();
- int oneCutR2 = areaAllR2 - areaCutR2;
- fourA = fourA - oneCutR2;
- Rect cut = new Rect(boundary, boundary, src.Cols - boundary * 2, src.Rows - 70 - boundary * 2);
- Cv2.Rectangle(src, cut, colorList[1]);
- //using (new Window("MatR2Cut", WindowMode.Normal, MatR2Cut))
- //{
- // Cv2.WaitKey(0);
- //}
- }
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchy;
- Cv2.GaussianBlur(dst, dst, new OpenCvSharp.Size(25, 25), 0, 0, BorderTypes.Default);
- dst = Binarization(dst);
- List<double> crystalList = new List<double>() { 0, 0, 0, 0 };
- List<int> crystalListi = new List<int>() { 0, 0, 0, 0 };
- int xx = 0;
- for (int i = 0; i < 2; i++)
- {
- for (int j = 0; j < 2; j++)
- {
- //定义截取矩形
- Rect m_select = new Rect(i * helfx, j * helfy, helfx, helfy);
- //进行裁剪
- Mat imgRect = new Mat(dst, m_select);
- Cv2.CvtColor(imgRect, imgRect, ColorConversionCodes.BGR2GRAY);
- Cv2.FindContours(imgRect, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- for (int t = 0; t < contours.Length; t++)
- {
- RotatedRect rectR = Cv2.MinAreaRect(contours[t]); //计算每个轮廓最小外接矩形
- float width = rectR.Size.Width;
- float height = rectR.Size.Height;
- bool isjoin = false;
- for (int p = 0; p < cs.Count(); p++)
- {
- if (delKey.Contains(p))
- continue;
- Point2f center = new Point2f(cs[p].Center.X, cs[p].Center.Y);
- double distanc = 0;
- for (int k = 0; k < contours[t].Length; k++)
- {
- Point2f pin = new Point2f(contours[t][k].X, contours[t][k].Y);
- distanc += pin.DistanceTo(center);
- }
- double dev = distanc / contours[t].Length;
- float mvg = width / height;
- if (dev < cs[p].Radius + 20)
- {
- isjoin = true;
- break;
- }
- }
- if (isjoin)
- {
- continue;
- }
- double area = Cv2.ContourArea(contours[t]);
- crystalList[xx] = crystalList[xx] + area;
- }
- crystalListi[xx] = Convert.ToInt32(crystalList[xx]);
- xx++;
- }
- }
- Rect m_select1 = new Rect(0, 0, dst.Cols, dst.Rows - 70);
- //进行裁剪
- Mat imgRect1 = new Mat(dst, m_select1);
- Cv2.CvtColor(imgRect1, imgRect1, ColorConversionCodes.BGR2GRAY);
- for (int i = 0; i < 6; i++)
- {
- Cv2.Erode(imgRect1, imgRect1, null);
- }
- Cv2.FindContours(imgRect1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- for (int t = 0; t < contours.Length; t++)
- {
- Rect CraRect = Cv2.BoundingRect(contours[t]);
- double s = Cv2.ContourArea(contours[t]);//轮廓面积
- double c = Cv2.ArcLength(contours[t], true); //轮廓周长
- //设为二次球
- if (BallPointFs.Count > 0)
- {
- int iscr = 0;
- foreach (var item in BallPointFs)
- {
- OpenCvSharp.Point repoint = new OpenCvSharp.Point(item.X, item.Y);
- double isball = Cv2.PointPolygonTest(contours[t], repoint, false);
- if (isball > -1)
- {
- OpenCvSharp.Point pcenter = new OpenCvSharp.Point(CraRect.X + CraRect.Width / 2, CraRect.Y + CraRect.Height / 2);
- //加强圆心显示
- Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- double area = s;
- if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- crystalListi[0] = crystalListi[0] - Convert.ToInt32(area);
- }
- if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- crystalListi[1] = crystalListi[1] - Convert.ToInt32(area);
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- crystalListi[2] = crystalListi[2] - Convert.ToInt32(area);
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- crystalListi[3] = crystalListi[3] - Convert.ToInt32(area);
- }
- iscr = 1;
- break;
- }
- }
- if (iscr == 1)
- {
- continue;
- }
- }
- RotatedRect rectR = Cv2.MinAreaRect(contours[t]); //计算每个轮廓最小外接矩形
- float width = rectR.Size.Width;
- float height = rectR.Size.Height;
- //如果离圆心很近算作圆的部分
- bool isjoin = false;
- for (int p = 0; p < cs.Count(); p++)
- {
- if (delKey.Contains(p))
- continue;
- Point2f center = new Point2f(cs[p].Center.X, cs[p].Center.Y);
- double distanc = 0;
- for (int k = 0; k < contours[t].Length; k++)
- {
- Point2f pin = new Point2f(contours[t][k].X, contours[t][k].Y);
- distanc += pin.DistanceTo(center);
- }
- double dev = distanc / contours[t].Length;
- float mvg = width / height;
- if ((dev < cs[p].Radius + 20))
- {
- isjoin = true;
- break;
- }
- }
- if (isjoin)
- {
- continue;
- }
- #region 如果球度在范围内判定为球
- //List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
- //int rx = CraRect.X;
- //int ry = CraRect.Y;
- //int rw = CraRect.Width;
- //int rh = CraRect.Height;
- ////top
- //if (ry == 0)
- //{
- // int rmx = rx + rw;
- // int rmxh = rw / 2 + rx;
- // plist = contours[t].OrderByDescending(g => g.Y).ToList();
- // int rmy = plist[0].Y;
- // List<OpenCvSharp.Point> qli = new List<OpenCvSharp.Point>() {new OpenCvSharp.Point(rx,0),
- // new OpenCvSharp.Point(rx+ rw/4, rmy/2),
- // new OpenCvSharp.Point(rmx,0),
- // new OpenCvSharp.Point(rx+ rw*3/4, rmy/2),
- // new OpenCvSharp.Point(rmxh, rmy) };
- // Point2f newcenter1 = new Point2f();
- // float newR1 = 0;
- // Cv2.MinEnclosingCircle(qli, out newcenter1, out newR1);
- // int pcou = 0;
- // List<OpenCvSharp.Point> newl = new List<OpenCvSharp.Point>();
- // OpenCvSharp.Point pv = new OpenCvSharp.Point((int)newcenter1.X, (int)newcenter1.Y);
- // foreach (var item in plist)
- // {
- // if (item.DistanceTo(pv) > newR1)
- // {
- // pcou++;
- // contours[t] = contours[t].Where(val => val.X != item.X && val.Y != item.Y).ToArray();
- // }
- // else
- // {
- // newl.Add(item);
- // }
- // }
- // double t1 = (double)pcou;
- // double s1 = Cv2.ContourArea(qli);
- // if (s1 / s >0.9 && t1 / s < 0.1)
- // {
- // //加强圆心显示
- // Cv2.Circle(src, (int)pv.X, (int)pv.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- // continue;
- // }
- //}
- /***********************
- //如果球度在范围内判定为球
- //afa参考代码
- //double afa = 4 * Math.PI * s / (c * c); //afa计算
- //afa = Math.Abs(afa - 1);
- //if (afa < 0.2&& s>4000)
- //{
- // OpenCvSharp.Point pcenter = new OpenCvSharp.Point(CraRect.X+ CraRect.Width/2, CraRect.Y+ CraRect.Height/2);
- // //加强圆心显示
- // Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- // double area = s;
- // if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- // {
- // one++;
- // oneA = oneA + area;
- // }
- // if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- // {
- // two++;
- // twoA = twoA + area;
- // }
- // if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- // {
- // three++;
- // threeA = threeA + area;
- // }
- // if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- // {
- // four++;
- // fourA = fourA + area;
- // }
- // continue;
- //}
- #endregion
- #region 如果是边界半圆算作圆
- //如果是边界半圆算作圆
- List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
- int rx = CraRect.X;
- int ry = CraRect.Y;
- int rw = CraRect.Width;
- int rh = CraRect.Height;
- //top
- if (ry == 0)
- {
- int minx = contours[t][0].X;
- int maxx = contours[t][0].X;
- for (int k = 0; k < contours[t].Length; k++)
- {
- if (contours[t][k].Y > 0)
- {
- plist.Add(contours[t][k]);
- if (minx > contours[t][k].X)
- minx = contours[t][k].X;
- if (maxx < contours[t][k].X)
- maxx = contours[t][k].X;
- }
- }
- plist.Sort((x, y) => x.X.CompareTo(y.X));
- //for (int i = 0; i < maxx - minx; i++)
- //{
- // int curx = i + minx;
- // if (plist[i].X > curx&&i>0)
- // {
- // int y = (plist[i - 1].Y + plist[i].Y) / 2;
- // plist.Insert(i, new OpenCvSharp.Point(curx, y));
- // }
- //}
- if (plist.Count > 10)
- {
- int len = plist.Count / 8;
- int midx = (maxx - minx) / 2 + minx;
- int a = Math.Abs(plist[len].Y - plist[7 * len].Y);
- int b = Math.Abs(plist[2 * len].Y - plist[6 * len].Y);
- int d = Math.Abs(plist[3 * len].Y - plist[5 * len].Y);
- int l1 = plist[len].Y;
- int l2 = plist[2 * len].Y;
- int l3 = plist[3 * len].Y;
- int l5 = plist[5 * len].Y;
- int l6 = plist[6 * len].Y;
- int l7 = plist[7 * len].Y;
- if (l2 > l1 && l3 > l2 && l5 > l6 && l6 > l7)
- {
- OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X, plist[len * 4].Y + 4);
- //加强圆心显示
- Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- double area = s;
- if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- }
- if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- }
- continue;
- }
- }
- }
- //bottom
- if (ry + rh > src.Rows - 155)
- {
- int minx = contours[t][0].X;
- int maxx = contours[t][0].X;
- for (int k = 0; k < contours[t].Length; k++)
- {
- if (contours[t][k].Y < src.Rows - 155)
- {
- plist.Add(contours[t][k]);
- if (minx > contours[t][k].X)
- minx = contours[t][k].X;
- if (maxx < contours[t][k].X)
- maxx = contours[t][k].X;
- }
- }
- plist.Sort((x, y) => x.X.CompareTo(y.X));
- //for (int i = 0; i < maxx - minx; i++)
- //{
- // int curx = i + minx;
- // if (plist[i].X > curx && i > 0)
- // {
- // int y = (plist[i - 1].Y + plist[i].Y) / 2;
- // plist.Insert(i, new OpenCvSharp.Point(curx, y));
- // }
- //}
- if (plist.Count > 10)
- {
- int len = plist.Count / 8;
- int midx = (maxx - minx) / 2 + minx;
- int a = Math.Abs(plist[len].Y - plist[7 * len].Y);
- int b = Math.Abs(plist[2 * len].Y - plist[6 * len].Y);
- int d = Math.Abs(plist[3 * len].Y - plist[5 * len].Y);
- int l1 = plist[len].Y;
- int l2 = plist[2 * len].Y;
- int l3 = plist[3 * len].Y;
- int l5 = plist[5 * len].Y;
- int l6 = plist[6 * len].Y;
- int l7 = plist[7 * len].Y;
- if (l2 < l1 && l3 < l2 && l5 < l6 && l6 < l7)
- {
- OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X, plist[len * 4].Y + 4);
- //加强圆心显示
- Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- double area = s;
- if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- }
- if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- }
- continue;
- }
- }
- }
- //left
- if (rx == 0)
- {
- int minx = contours[t][0].Y;
- int maxx = contours[t][0].Y;
- for (int k = 0; k < contours[t].Length; k++)
- {
- if (contours[t][k].X > 0)
- {
- plist.Add(contours[t][k]);
- if (minx > contours[t][k].Y)
- minx = contours[t][k].Y;
- if (maxx < contours[t][k].Y)
- maxx = contours[t][k].Y;
- }
- }
- plist.Sort((x, y) => x.Y.CompareTo(y.Y));
- //for (int i = 0; i < maxx - minx; i++)
- //{
- // int curx = i + minx;
- // if (plist[i].Y > curx && i > 0)
- // {
- // int y = (plist[i - 1].X + plist[i].X) / 2;
- // plist.Insert(i, new OpenCvSharp.Point(y, curx));
- // }
- //}
- if (plist.Count > 10)
- {
- int len = plist.Count / 8;
- int midx = (maxx - minx) / 2 + minx;
- int a = Math.Abs(plist[len].X - plist[7 * len].X);
- int b = Math.Abs(plist[2 * len].X - plist[6 * len].X);
- int d = Math.Abs(plist[3 * len].X - plist[5 * len].X);
- int l1 = plist[len].X;
- int l2 = plist[2 * len].X;
- int l3 = plist[3 * len].X;
- int l5 = plist[5 * len].X;
- int l6 = plist[6 * len].X;
- int l7 = plist[7 * len].X;
- if (l2 > l1 && l3 > l2 && l5 > l6 && l6 > l7)
- {
- OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X + 4, plist[len * 4].Y);
- //加强圆心显示
- Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- double area = s;
- if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- }
- if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- }
- continue;
- }
- }
- }
- //rght
- if (rx + rw > src.Cols - 3)
- {
- int minx = contours[t][0].Y;
- int maxx = contours[t][0].Y;
- for (int k = 0; k < contours[t].Length; k++)
- {
- if (contours[t][k].X < src.Cols - 3)
- {
- plist.Add(contours[t][k]);
- if (minx > contours[t][k].Y)
- minx = contours[t][k].Y;
- if (maxx < contours[t][k].Y)
- maxx = contours[t][k].Y;
- }
- }
- plist.Sort((x, y) => x.Y.CompareTo(y.Y));
- //for (int i = 0; i < maxx - minx; i++)
- //{
- // int curx = i + minx;
- // if (plist[i].Y > curx && i > 0)
- // {
- // int y = (plist[i - 1].X + plist[i].X) / 2;
- // plist.Insert(i, new OpenCvSharp.Point(y, curx));
- // }
- //}
- if (plist.Count > 10)
- {
- int len = plist.Count / 8;
- int midx = (maxx - minx) / 2 + minx;
- int a = Math.Abs(plist[len].X - plist[7 * len].X);
- int b = Math.Abs(plist[2 * len].X - plist[6 * len].X);
- int d = Math.Abs(plist[3 * len].X - plist[5 * len].X);
- int l1 = plist[len].X;
- int l2 = plist[2 * len].X;
- int l3 = plist[3 * len].X;
- int l5 = plist[5 * len].X;
- int l6 = plist[6 * len].X;
- int l7 = plist[7 * len].X;
- if (l2 < l1 && l3 < l2 && l5 < l6 && l6 < l7)
- {
- OpenCvSharp.Point pcenter = new OpenCvSharp.Point(plist[len * 4].X + 4, plist[len * 4].Y);
- //加强圆心显示
- Cv2.Circle(src, (int)pcenter.X, (int)pcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- double area = s;
- if ((int)pcenter.X < helfx && (int)pcenter.Y < helfy)
- {
- one++;
- oneA = oneA + area;
- }
- if ((int)pcenter.X < helfx && (int)pcenter.Y > helfy)
- {
- two++;
- twoA = twoA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y < helfy)
- {
- three++;
- threeA = threeA + area;
- }
- if ((int)pcenter.X > helfx && (int)pcenter.Y > helfy)
- {
- four++;
- fourA = fourA + area;
- }
- continue;
- }
- }
- }
- **************/
- #endregion
- Mat temp_empt = Mat.Zeros(src.Size(), MatType.CV_8UC1);
- Cv2.DrawContours(temp_empt, contours, t, new Scalar(255), -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- for (int i = 0; i < 6; i++)
- {
- Cv2.Dilate(temp_empt, temp_empt, null);
- }
- OpenCvSharp.Point[][] contours1 = new OpenCvSharp.Point[][] { };
- Cv2.FindContours(temp_empt, out contours1, out HierarchyIndex[] hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- 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));
- }
- for (int i = 0; i < cs.Length; i++)
- {
- if (delKey.Contains(i))
- {
- continue;
- }
- //加强圆心显示
- Cv2.Circle(src, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- }
- //
- if (CrystalLunkuo.Count > 0)
- {
- for (int lk = 0; lk < CrystalLunkuo.Count; lk++)
- {
- List<OpenCvSharp.Point> pl = new List<OpenCvSharp.Point>();
- CrystalLunkuo[lk].ForEach(pp => pl.Add(new OpenCvSharp.Point(pp.X, pp.Y)));
- Point2f newcenter = new Point2f();
- float newR = 0;
- Cv2.MinEnclosingCircle(pl, out newcenter, out newR);
- Cv2.Circle(src, (int)newcenter.X, (int)newcenter.Y, 3, colorList[0], 2, LineTypes.AntiAlias);
- //Rect lkRect = Cv2.BoundingRect(pl);
- ////加强圆心显示
- //Cv2.Circle(dst, (int)(lkRect.X + lkRect.Width / 2), (int)(lkRect.Y + lkRect.Height / 2), 3, colorList[0], 2, LineTypes.AntiAlias);
- }
- }
- Cv2.Line(src, new OpenCvSharp.Point() { X = 0, Y = helfy }, new OpenCvSharp.Point() { X = src.Cols, Y = helfy }, colorList[1]);
- Cv2.Line(src, new OpenCvSharp.Point() { X = helfx, Y = 0 }, new OpenCvSharp.Point() { X = helfx, Y = src.Rows - 70 }, colorList[1]);
- circleList.Add(one);
- circleList.Add(two);
- circleList.Add(three);
- circleList.Add(four);
- circleAreaList.Add((int)oneA);
- circleAreaList.Add((int)twoA);
- circleAreaList.Add((int)threeA);
- circleAreaList.Add((int)fourA);
- data.Add(circleList);
- data.Add(crystalListi);
- data.Add(circleAreaList);
- }
- else if (imageType == 4)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- List<int> sel = poListHis[selPointFs];
- //src = SelectBall(used, sel[0], sel[1], sel[2]);
- src = SelectBallInt(used, selPointFs);
- }
- else
- {
- //src = WhirtBinarization(src);
- Cv2.CvtColor(src, src, ColorConversionCodes.BGRA2BGR);
- Mat dst = new Mat();
- //Cv2.PyrMeanShiftFiltering(src, src, 21, 51);
- Cv2.GaussianBlur(src, src, new OpenCvSharp.Size(17, 17), 0);
- Cv2.MedianBlur(src, src, 15);
- // Cv2.BilateralFilter(dst, src, 21, 132, 181);
- src = BinarizationBall(src);
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
- // 开操作,也可省落变量前缀名
- // Cv2.MorphologyEx(src, src, MorphTypes.Dilate, kernel, new OpenCvSharp.Point(-1, -1));
- //双边滤波
- //Cv2.MorphologyEx(src, src, MorphTypes.Close, null, null, 4, BorderTypes.Constant);
- //src = WhirtBinarization(src);
- //src = DrwCrackBall(src);
- //retMat = src.Clone();
- //poListHis.Clear();
- //poList.ForEach(i => poListHis.Add(i));
- }
- keyValueSel.Clear();
- selPointFs = -1;
- }
- else if (imageType == 14)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- List<int> sel = poListHis[selPointFs];
- src = SelectBallInt(used, selPointFs);
- }
- else
- {
- src = DrwCrackBall(src);
- retMat = src.Clone();
- poListHis.Clear();
- poList.ForEach(i => poListHis.Add(i));
- }
- keyValueSel.Clear();
- selPointFs = -1;
- }
- else if (imageType == 5)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- src = SelectPoint(used);
- }
- else
- {
- //二值提取
- src = BinarizationForM(src);
- //去掉过小孔隙,计算孔隙面积
- src = DebrisRemoval_New(src);
- data.Add(poAreaList);
- retMat = src.Clone();
- }
- keyValueSel.Clear();
- selPointFs = -1;
- }
- return src;
- }
- /// <summary>
- /// 开裂球
- /// </summary>
- /// <param name="src">源图像</param>
- /// <param name="lists">参数集合</param>
- /// <returns></returns>
- public static Mat ImageBinaryExtraction(Mat src, Mat source, List<Args> lists, out List<List<int>> data, bool findContours = false)
- {
- //以下是参数信息---------------------
- ///1个颜色区间还是2个
- colorInterval = 1;
- //第一个二值区间
- colorOneStart = 0;
- colorOneEnd = 0;
- //第二个二值区间
- colorTwoStart = 0;
- colorTwoEnd = 0;
- //第三个二值区间
- colorThreeStart = 0;
- colorThreeEnd = 0;
- //处理细节
- //删除边界对象
- bool deleteBoundaryObject = false;
- //孔洞填充
- bool holeFilling = false;
- //碎屑删除
- bool debrisRemoval = false;
- //碎屑删除面积起
- debrisAreaStart = 0;
- //碎屑删除面积止
- debrisAreaEnd = 0;
- //二值样式
- //1实心 2边线
- int binaryStyle = 0;
- //相颜色
- Color phaseColor = Color.Red;
- //目标选择
- int targetSelection = 1;
- for (int i = 0; i < lists.Count; i++)
- {
- Args args = lists[i];
- switch (args.Key)
- {
- case "colorInterval":
- {
- if (args.Value is Boolean)
- colorInterval = (Boolean)args.Value ? 2 : 1;
- else
- colorInterval = (int)args.Value;
- }
- break;
- case "scope1":
- colorOneStart = (int)((List<double>)args.Value)[0];
- colorOneEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope2":
- colorTwoStart = (int)((List<double>)args.Value)[0];
- colorTwoEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope3":
- colorThreeStart = (int)((List<double>)args.Value)[0];
- colorThreeEnd = (int)((List<double>)args.Value)[1];
- break;
- case "deleteBoundaryObject":
- deleteBoundaryObject = (bool)args.Value;
- break;
- case "holeFilling":
- holeFilling = (bool)args.Value;
- break;
- case "debrisRemoval":
- debrisRemoval = (bool)args.Value;
- break;
- case "binaryStyle":
- binaryStyle = (int)args.Value;
- break;
- case "phaseColor":
- phaseColor = Color.FromArgb((int)args.Value);
- break;
- case "targetSelection":
- targetSelection = (int)args.Value;
- break;
- case "scope4":
- debrisAreaStart = (int)((List<double>)args.Value)[0];
- debrisAreaEnd = (int)((List<double>)args.Value)[1];
- findContours = true;
- break;
- case "CircleCount":
- circleCount = (int)args.Value;
- break;
- case "maxContour":
- maxContour = (OpenCvSharp.Point[])args.Value;
- break;
- case "CircleR":
- CircleR = (int)args.Value;
- break;
- case "Center":
- center = (OpenCvSharp.Point)args.Value;
- break;
- case "DelPointFs":
- delPointFs = (List<PointF>)args.Value;
- break;
- case "imageType":
- imageType = (int)args.Value;
- break;
- case "SelPointFs":
- selPointFs = (int)args.Value;
- break;
- case "imageTypes":
- imageType = (int)args.Value;
- break;
- case "CreackBallPointFs":
- CreackBallPointFs = (List<PointF>)args.Value;
- break;
- case "CreackBallPointFsK":
- CreackBallPointFsK = (List<PointF>)args.Value;
- break;
- case "CreackBallPointFsP":
- CreackBallPointFsP = (List<PointF>)args.Value;
- break;
- default:
- break;
- }
- }
- if (phaseColor.A < 1)//#21321
- phaseColor = Color.FromArgb(1, phaseColor.R, phaseColor.G, phaseColor.B);
- vec4B.Item0 = phaseColor.B;
- vec4B.Item1 = phaseColor.G;
- vec4B.Item2 = phaseColor.R;
- vec4B.Item3 = phaseColor.A;
- poArea = 0;
- maxArea = 0;
- poList.Clear();
- poAreaList = new List<int>() { };
- data = poList;
- imageHight = src.Rows;
- if (imageType == 14)
- {
- if (selPointFs != -1 && retMat != null)
- {
- Mat used = retMat.Clone();
- keyValueSel.Add(selPointFs, 1);
- List<int> sel = poListHis[selPointFs];
- src = SelectBallInt(used, selPointFs);
- }
- else
- {
- src = DrwCrackBall_New(src, source);
- retMat = src.Clone();
- poListHis.Clear();
- poList.ForEach(i => poListHis.Add(i));
- }
- keyValueSel.Clear();
- selPointFs = -1;
- }
- return src;
- }
- /// <summary>
- /// 二次球与单晶去底条
- /// </summary>
- /// <param name="source"></param>
- /// <returns></returns>
- private static Mat RemoveBottm(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- srcGray.ForEachAsByte(RemoveBottmForEachAsByte);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void RemoveBottmForEachAsByte(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (y > imageHight - 140)
- {
- temp.Set<Vec4b>(y, x, vec4Bw);
- }
- }
- /// <summary>
- /// 二值提取
- /// </summary>
- /// <param name="source">源</param>
- /// <param name="colorInterval">1个或2个颜色区间</param>
- /// <param name="colorOneStart"></param>
- /// <param name="colorOneEnd"></param>
- /// <param name="colorTwoStart"></param>
- /// <param name="colorTwoEnd"></param>
- /// <param name="colorThreeStart"></param>
- /// <param name="colorThreeEnd"></param>
- /// <returns></returns>
- private static Mat Binarization(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- try
- {
- srcGray.ForEachAsByte(GrayForEachAsByte);
- }
- catch (Exception e)
- {
- throw;
- }
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void GrayForEachAsByte(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (colorInterval == 1)
- {
- if (v >= colorOneStart && v <= colorOneEnd)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- //手动画圆
- if (ListRadiusColor.Count > 0)
- {
- int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
-
- Color co = ListRadiusColor.First().Value;
- Vec4b colorMax = new Vec4b(co.B, co.G, co.R, 255);
- temp.Set<Vec4b>(y, x, colorMax);
- foreach (var item in ListRadiusColor)
- {
- int r = item.Key;
- if (d < r)
- {
- Vec4b vb4 = new Vec4b(item.Value.B, item.Value.G, item.Value.R, 255);
- temp.Set<Vec4b>(y, x, vb4);
-
- }
- }
- if (ListRadiusColor.Count > 1)
- {
- for (int i = 0; i < ListRadiusColor.Count - 1; i++)
- {
- int r = i == 0 ? 0 : ListRadiusColor.ElementAt(ListRadiusColor.Count - i).Key;
- int r2 = ListRadiusColor.ElementAt(ListRadiusColor.Count - 1 - i).Key;
- if (r < d && d <= r2)
- {
- poAreaList[i]++;
- break;
- }
- }
- }
-
-
- }
- else if (circleCount > 1) //同心圆数量大于一时染色
- {
- temp.Set<Vec4b>(y, x, vec4BList[circleCount - 1]);
- int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
- for (int i = circleCount - 1; i >= 0; i--)
- {
- int r = Convert.ToInt32(CircleR * (i + 1));
- if (d < r)
- {
- temp.Set<Vec4b>(y, x, vec4BList[i]);
- }
- }
- for (int i = 0; i < circleCount; i++)
- {
- int r = Convert.ToInt32(CircleR * (i));
- int r2 = Convert.ToInt32(CircleR * (i + 1));
- if (r < d && d <= r2)
- {
- poAreaList[i]++;
- break;
- }
- }
- }
- }
- }
- else
- {
- if ((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd))
- {
- temp.Set<Vec4b>(y, x, vec4B);
- }
- }
- }
- /// <summary>
- /// 开裂球分水岭二值提取
- /// </summary>
- /// <param name="source">源</param>
- /// <param name="colorInterval">1个或2个颜色区间</param>
- /// <param name="colorOneStart"></param>
- /// <param name="colorOneEnd"></param>
- /// <param name="colorTwoStart"></param>
- /// <param name="colorTwoEnd"></param>
- /// <param name="colorThreeStart"></param>
- /// <param name="colorThreeEnd"></param>
- /// <returns></returns>
- private static Mat BinarizationBall(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- srcGray.ForEachAsByte(GrayForEachAsByteBall);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void GrayForEachAsByteBall(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (colorInterval == 1)
- {
- if (v >= colorOneStart && v <= colorOneEnd)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- }
- }
- else
- {
- if ((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd))
- {
- temp.Set<Vec4b>(y, x, vec4B);
- }
- }
- }
- private static Mat WhirtBinarization(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = source.Clone();
- srcGray.ForEachAsByte(WhirtForEachAsByte);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void WhirtForEachAsByte(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (v > 240 || y > imageHight - 70)
- {
- temp.Set<Vec4b>(y, x, vec4Bw);
- }
- //if (x < 50 || y < 50 || x > imageWidth - 50 || y > imageHight - 190)
- //{
- // temp.Set<Vec4b>(y, x, vec4Bw);
- //}
- }
- //二次球去边
- private static Mat BallCutBottor(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = source.Clone();
- srcGray.ForEachAsByte(BallCutBottorForEachAsByte);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void BallCutBottorForEachAsByte(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (x < boundary || y < boundary || x > imageWidth - boundary || y > imageHight - boundary - 140)
- {
- temp.Set<Vec4b>(y, x, vec4Bw);
- }
- }
- /// <summary>
- /// 新版本删除边界
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DeleteContours_New(Mat src)
- {
- Mat[] arr = src.Split();
- Mat rgb = BaseTools.MergeMatFromMatArr(arr);
- Mat temp_1 = arr[3].Clone();
- for (int h = 0; h < temp_1.Width; h++)
- {
- byte vec4B_top = temp_1.At<byte>(0, h);
- if (vec4B_top > 0)
- {
- Cv2.FloodFill(rgb, new OpenCvSharp.Point(h, 0), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- Cv2.FloodFill(temp_1, new OpenCvSharp.Point(h, 0), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- }
- }
- for (int h = 0; h < temp_1.Width; h++)
- {
- byte vec4B_bottom = temp_1.At<byte>(temp_1.Height - 1, h);
- if (vec4B_bottom > 0)
- {
- Cv2.FloodFill(rgb, new OpenCvSharp.Point(h, temp_1.Height - 1), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- Cv2.FloodFill(temp_1, new OpenCvSharp.Point(h, temp_1.Height - 1), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- }
- }
- for (int y = 0; y < temp_1.Height; y++)
- {
- Vec4b vec4B_top = temp_1.At<Vec4b>(y, 0);
- if (vec4B_top.Item3 > 0)
- {
- Cv2.FloodFill(rgb, new OpenCvSharp.Point(0, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- Cv2.FloodFill(temp_1, new OpenCvSharp.Point(0, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- }
- }
- for (int y = 0; y < temp_1.Height; y++)
- {
- byte vec4B_top = temp_1.At<byte>(y, temp_1.Width - 1);
- if (vec4B_top > 0)
- {
- Cv2.FloodFill(rgb, new OpenCvSharp.Point(temp_1.Width - 1, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- Cv2.FloodFill(temp_1, new OpenCvSharp.Point(temp_1.Width - 1, y), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- }
- }
- Mat[] mats = rgb.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_1;
- Cv2.Merge(arr, src);
- return src;
- }
- /// <summary>
- /// 新孔洞填充,采用形态学填充
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat HoleFilling_New(Mat src)
- {
- Mat[] arr2 = src.Split();
- Mat matc = arr2[3];
- //去掉透明层
- Mat mat = src.CvtColor(ColorConversionCodes.BGRA2BGR);
- //填充孔洞
- mat = BaseTools.FillHole(mat, new Scalar(255 - vec4B.Item0, 255 - vec4B.Item1, 255 - vec4B.Item2));
- matc = BaseTools.FillHole(matc, new Scalar(255));
- //循环处理
- mat.ForEachAsVec3b(RGBForEachAsByteForHoleFillingNew);
- Mat[] arr1 = mat.Split();
- arr2[0] = arr1[0];
- arr2[1] = arr1[1];
- arr2[2] = arr1[2];
- arr2[3] = matc;
- Cv2.Merge(arr2, src);
- return src;
- }
- private static void RGBForEachAsByteForHoleFillingNew(Vec3b* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- if (value->Item0 == 255 && value->Item1 == 255 && value->Item2 == 255)
- {
- value->Item0 = vec4B.Item0;
- value->Item1 = vec4B.Item1;
- value->Item2 = vec4B.Item2;
- }
- }
- /// <summary>
- /// 选择颗粒处理
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat SelectPoint(Mat src)
- {
- Mat[] arr = src.Split();
- rgb_ap = BaseTools.MergeMatFromMatArr(arr);
- temp_ap = arr[3].Clone();
- labelMatForSel.ForEachAsInt32(CommonForEachForSel);
- //合并rgb和透明度
- Mat[] mats = rgb_ap.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_ap;
- Cv2.Merge(arr, src);
- return src;
- }
- /// <summary>
- /// 新碎屑删除,使用连通分量找寻碎屑截面孔隙
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DebrisRemoval_New(Mat src)
- {
- Mat[] arr = src.Split();
- rgb_ap = BaseTools.MergeMatFromMatArr(arr);
- temp_ap = arr[3].Clone();
- //寻找连通分量
- Mat labelMat = new Mat();
- Mat stats = new Mat();
- Mat centroids = new Mat();
- int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
- Mat oo = temp_ap.Clone();
- Cv2.Dilate(oo, oo, null);
- Mat respend = new Mat();
- temp_view.ConvertTo(respend, MatType.CV_8UC3);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(oo, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- for (int i = 0; i < contours.Length; i++)
- {
- double art = Cv2.ContourArea(contours[i]);
- if (art < 50)
- continue;
- respend.DrawContours(contours, i, Scalar.RandomColor(), -1);
- }
- //using (new Window("s", WindowMode.Normal, respend))
- //{
- // Cv2.WaitKey(0);
- //}
- //Cv2.ImWrite("E://tt.jpg", respend);
- //寻找在范围内需要删除的碎屑
- keyValuePairs.Clear();
- keyValueSel.Clear();
- for (int h = 1; h < centroids.Height; h++)
- {
- int areaField1 = stats.At<int>(h, 4);
- int x = stats.At<int>(h, 0);
- int y = stats.At<int>(h, 1);
- int width = stats.At<int>(h, 2);
- int height = stats.At<int>(h, 3);
- //面积小于30的孔隙删除
- if (debrisAreaStart <= areaField1 && areaField1 <= 3)
- {
- keyValuePairs.Add(h, 1);
- }
- else if (areaField1 > src.Rows * src.Cols * 0.3)//面积最大的是轮廓,这里算大于整体面积的0.3
- {
- keyValuePairs.Add(h, 1);
- maxArea = areaField1;
- }
- else
- {
- int qud = 0;
- if (delPointFs != null && delPointFs.Count > 0)
- {
- for (int i = 0; i < delPointFs.Count; i++)
- {
- double px = delPointFs[i].X;
- double py = delPointFs[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- keyValuePairs.Add(h, 1);
- qud = 1;
- break;
- }
- }
- }
- if (qud == 1)
- {
- continue;
- }
- poArea += areaField1;
- List<int> po = new List<int>() { x, y, width, height, areaField1, h };
- poList.Add(po);
- }
- }
- labelMatForSel = labelMat;
- labelMat.ForEachAsInt32(CommonForEachForInt32);
- labelMat.ForEachAsInt32(CommonForEachForSel);
- //合并rgb和透明度
- Mat[] mats = rgb_ap.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_ap;
- Cv2.Merge(arr, src);
- return src;
- }
- private static Mat CrystBinarization(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- srcGray.ForEachAsByte(CrystForEachAsByte);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void CrystForEachAsByte(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (v >= 240)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- }
- //if (AddPontins != null && AddPontins.Count > 0)
- //{
- // for (int i = 0; i < AddPontins.Count; i++)
- // {
- // if (Cv2.PointPolygonTest(AddPontins[i], new OpenCvSharp.Point(x, y), false) > -1)
- // {
- // temp.Set<Vec4b>(y, x, vec4B);
- // }
- // }
- //}
- }
- /// <summary>
- /// 单晶使用找轮廓找寻碎屑
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DebrisRemoval_Cryst1(Mat src)
- {
- if (AddPontins != null && AddPontins.Count > 0)
- {
- Cv2.DrawContours(src, AddPontins, -1, new Scalar(255, 255, 255, 255), -1);
- }
- //using (new Window("s",WindowMode.Normal, src))
- //{
- // Cv2.WaitKey(0);
- //}
- src = CrystBinarization(src);
- Mat[] arr = src.Split();
- rgb_ap = BaseTools.MergeMatFromMatArr(arr);
- temp_ap = arr[3].Clone();
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(temp_ap, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- //寻找在范围内需要删除的碎屑
- for (int h = 1; h < contours.Length; h++)
- {
- Rect rect = Cv2.BoundingRect(contours[h]);
- int areaField1 = Convert.ToInt32(Cv2.ContourArea(contours[h]));
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- //边缘
- if (x < 5 || x + width > src.Cols - 5 || y < 5 || y + height > src.Rows - 5)
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- //面积小于30的孔隙删除
- else if (areaField1 < 2)
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- else
- {
- poArea += areaField1;
- Mat t = new Mat(temp_ap, new Rect(x, y, width, height));
- int maxxx = 0; int maxyy = 0;
- int inde = h - 1;
- RotatedRect rectR = Cv2.MinAreaRect(contours[h]);
- if (maxxx < rectR.Size.Width)
- {
- maxxx = (int)rectR.Size.Width;
- }
- if (maxyy < rectR.Size.Height)
- {
- maxyy = (int)rectR.Size.Height;
- }
- double kgr = Convert.ToDouble(maxxx + maxyy) * 0.5 * Micron;
- double hlengh = maxxx > maxyy ? maxxx : maxyy;
- double wlengh = maxxx < maxyy ? maxxx : maxyy;
- double area = maxxx * maxyy * AreaRatio;
- if (wlengh > 0)
- {
- double hm = hlengh / wlengh;
- //颗粒尺寸超长
- if (kgr < pointsize)
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- else if (hm > HW)//长宽比过大
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- else if (areaField1 < area)
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- //正常颗粒
- else
- {
- //afa参考代码
- double s = areaField1;//轮廓面积
- double c = contours[h].Length; //轮廓周长
- double afa = Math.Sqrt(4 * Math.PI * s / (c * c)); //afa计算
- int aa = Convert.ToInt32(afa * 1000);
- InputArray contoursAll = InputArray.Create(contours[h]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- double nc = Cv2.ArcLength(outArr.ToArray(), true) / Math.PI;
- double na = Math.Sqrt(areaField1 / Math.PI) * 2;
- aa = Convert.ToInt32((na / nc) * 1000);
- List<int> po = new List<int>() { x, y, width, height, areaField1, h, maxxx, maxyy, aa };
- poList.Add(po);
- }
- }
- else
- {
- temp_ap.DrawContours(contours, h, new Scalar(0), -1);
- continue;
- }
- }
- }
- //合并rgb和透明度
- Mat[] mats = rgb_ap.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_ap;
- Cv2.Merge(arr, src);
- return src;
- }
- /// <summary>
- /// 单晶使用连通分量找寻碎屑
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static int hindex = -1;
- private static Mat ground = new Mat();
- private static Mat DebrisRemoval_Cryst(Mat src)
- {
- src = CrystBinarization(src);
- keyValuePairs.Clear();
- Mat[] arr = src.Split();
- rgb_ap = BaseTools.MergeMatFromMatArr(arr);
- temp_ap = arr[3].Clone();
- //寻找连通分量
- Mat labelMat = new Mat();
- Mat stats = new Mat();
- Mat centroids = new Mat();
- int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
- if (delPointFs != null && delPointFs.Count > 0)
- {
- for (int i = 0; i < delPointFs.Count; i++)
- {
- int qx = (int)delPointFs[i].X;
- int qy = (int)delPointFs[i].Y;
- int label = labelMat.At<int>(qy, qx);
- if (label > 0 && !keyValuePairs.ContainsKey(label))
- {
- keyValuePairs.Add(label, 1);
- }
- }
- }
- labelMat.ForEachAsInt32(CommonForEachDel);
- //寻找连通分量
- labelMat = new Mat();
- stats = new Mat();
- centroids = new Mat();
- nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
-
- //Mat oo = temp_ap.Clone();
- //Mat respend = new Mat();
- //temp_view.ConvertTo(respend, MatType.CV_8UC3);
- //OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- //HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //Cv2.FindContours(oo, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- //for (int i = 0; i < contours.Length; i++)
- //{
- // double art = Cv2.ContourArea(contours[i]);
- // if (art < 50)
- // continue;
- // if (contours[i][0].Y > oo.Height - border)
- // {
- // respend.DrawContours(contours, i, Scalar.Black, -1);
- // continue;
- // }
- // respend.DrawContours(contours, i, Scalar.RandomColor(), -1);
- //}
- //using (new Window("s", WindowMode.Normal, respend))
- //{
- // Cv2.WaitKey(0);
- //}
- //Cv2.ImWrite("E://tt.jpg", respend);
- AllFields = new List<List<OpenCvSharp.Point>>();
- for (int i = 0; i < centroids.Height; i++)
- {
- AllFields.Add(new List<OpenCvSharp.Point>());
- }
- labelMat.ForEachAsInt32(CommonForEachForCon);
- //寻找在范围内需要删除的碎屑
- keyValuePairs.Clear();
- keyValueSel.Clear();
- for (int i = 0; i < circleCount; i++)
- {
- poAreaList.Add(0);
- }
- ////旧的删除方式
- //if (delPointFs != null && delPointFs.Count > 0)
- //{
- // for (int i = 0; i < delPointFs.Count; i++)
- // {
- // int qx = (int)delPointFs[i].X;
- // int qy = (int)delPointFs[i].Y;
- // int label = labelMat.At<int>(qy, qx);
- // if (label > 0 && !keyValuePairs.ContainsKey(label))
- // {
- // keyValuePairs.Add(label, 1);
- // }
- // }
- //}
- List<RotatedRect> rectList = new List<RotatedRect>();
- List<List<OpenCvSharp.Point>> rectListPoint = new List<List<OpenCvSharp.Point>>();
- for (int h = 1; h < centroids.Height; h++)
- {
- int areaField1 = stats.At<int>(h, 4);
- int x = stats.At<int>(h, 0);
- int y = stats.At<int>(h, 1);
- int width = stats.At<int>(h, 2);
- int height = stats.At<int>(h, 3);
- if (keyValuePairs.ContainsKey(h))
- {
- continue;
- }
- if (Contour != null && Contour.Count > 0)
- {
- OpenCvSharp.Point p1 = new OpenCvSharp.Point(x, y);
- double d = Cv2.PointPolygonTest(Contour, p1, false);
- if (d < 0)
- {
- keyValuePairs.Add(h, 1);
- continue;
- }
- p1 = new OpenCvSharp.Point(x + width, y);
- d = Cv2.PointPolygonTest(Contour, p1, false);
- if (d < 0)
- {
- keyValuePairs.Add(h, 1);
- continue;
- }
- p1 = new OpenCvSharp.Point(x + width, y + height);
- d = Cv2.PointPolygonTest(Contour, p1, false);
- if (d < 0)
- {
- keyValuePairs.Add(h, 1);
- continue;
- }
- p1 = new OpenCvSharp.Point(x, y + height);
- d = Cv2.PointPolygonTest(Contour, p1, false);
- if (d < 0)
- {
- keyValuePairs.Add(h, 1);
- continue;
- }
- }
- //边缘
- if (x < border || x + width > src.Cols - border || y < border || y + height > src.Rows - border - borderBottom)
- {
- keyValuePairs.Add(h, 1);
- }
- else if (areaField1 > src.Rows * src.Cols * 0.3)//面积最大的是轮廓,这里算大于整体面积的0.3
- {
- keyValuePairs.Add(h, 1);
- maxArea = areaField1;
- }
- else
- {
- poArea += areaField1;
- Mat t = new Mat(temp_ap, new Rect(x, y, width, height));
- int maxxx = 0; int maxyy = 0;
- int inde = h - 1;
- RotatedRect rectR = Cv2.MinAreaRect(AllFields[inde]);
- if (maxxx < rectR.Size.Width)
- {
- maxxx = (int)rectR.Size.Width;
- }
- if (maxyy < rectR.Size.Height)
- {
- maxyy = (int)rectR.Size.Height;
- }
- double kgr = Convert.ToDouble(maxxx + maxyy) * 0.5 * Micron;
- double hlengh = maxxx > maxyy ? maxxx : maxyy;
- double wlengh = maxxx < maxyy ? maxxx : maxyy;
- double area = maxxx * maxyy * AreaRatio;
- InputArray contoursAll = InputArray.Create(AllFields[inde]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- area = Cv2.ContourArea(outArr) * AreaRatio;
- if (wlengh > 0)
- {
- double hm = hlengh / wlengh;
- //颗粒尺寸超长
- if (kgr < pointsize)
- {
- keyValuePairs.Add(h, 1);
- }
- else if (hm > HW)//长宽比过大
- {
- keyValuePairs.Add(h, 1);
- }
- else if (areaField1 < area)
- {
- keyValuePairs.Add(h, 1);
- }
- //正常颗粒
- else
- {
- ////圆润度
- //hindex = h;
- //ground = temp_ap.Clone();
- //labelMat.ForEachAsInt32(CommonForEachForArc);
- //double roundness= GetRoundness2(width, height, x, y);
- //double c = contours[0].Length; //轮廓周长
- //double xa = Math.Sqrt(areaField1 / Math.PI) * 2;
- //double xp = c / Math.PI;
- //int aa = Convert.ToInt32((xa / xp) * 1000);
- double nc = Cv2.ArcLength(outArr.ToArray(), true) ;
- double na = Math.Sqrt(areaField1 / Math.PI) * 2;
- int aa = Convert.ToInt32((na / nc) * 1000);
- List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
- Point2f[] point2F = rectR.Points();
- foreach (var item in point2F)
- {
- listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
- }
- rectListPoint.Add(listpoint);
- rectList.Add(rectR);
- List<int> po = new List<int>() { x, y, width, height, areaField1, h, maxxx, maxyy, 1 , (int)nc };
- poList.Add(po);
- }
- }
- else
- {
- keyValuePairs.Add(h, 1);
- }
- }
- }
- labelMatForSel = labelMat;
- fieldsCount = centroids.Height;
- labelMat.ForEachAsInt32(CommonForEachForInt32);
- labelMat.ForEachAsInt32(CommonForEachForSel);
- #region 添加颗粒
- Mat MatAdd = new Mat(src.Rows, src.Cols, MatType.CV_8UC1,new Scalar(0));
- if (AddPontins != null && AddPontins.Count > 0)
- {
- for (int i = 0; i < AddPontins.Count; i++)
- {
- Cv2.DrawContours(MatAdd, AddPontins, i, new Scalar(255), -1);
- Cv2.DrawContours(rgb_ap, AddPontins, i,new Scalar( vec4B.Item0, vec4B.Item1, vec4B.Item2), -1);
- Cv2.DrawContours(temp_ap, AddPontins, i, new Scalar(255), -1);
- }
- // Cv2.DrawContours(src, AddPontins, -1, new Scalar(255, 255, 255, 255), -1);
- }
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //轮廓
- Cv2.FindContours(MatAdd, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- labelMatForSelAdd = contours;
- for (int i = 0; i < contours.Length; i++)
- {
- Rect rect = Cv2.BoundingRect(contours[i]);
- int areaField1 =Convert.ToInt32( Cv2.ContourArea(contours[i]));
- int nc = Convert.ToInt32(Cv2.ArcLength(contours[i], true));
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- int maxxx = 0; int maxyy = 0;
- RotatedRect rectR = Cv2.MinAreaRect(contours[i]);
- if (maxxx < rectR.Size.Width)
- {
- maxxx = (int)rectR.Size.Width;
- }
- if (maxyy < rectR.Size.Height)
- {
- maxyy = (int)rectR.Size.Height;
- }
- List<OpenCvSharp.Point> listpoint = new List<OpenCvSharp.Point>();
- Point2f[] point2F = rectR.Points();
- foreach (var item in point2F)
- {
- listpoint.Add(new OpenCvSharp.Point(Convert.ToInt32(item.X), Convert.ToInt32(item.Y)));
- }
- rectListPoint.Add(listpoint);
- rectList.Add(rectR);
- List<int> po = new List<int>() { x, y, width, height, areaField1, centroids.Height+i, maxxx, maxyy, 1 , nc };
- poList.Add(po);
- }
- //using (new Window("s", WindowMode.Normal, src))
- //{
- // Cv2.WaitKey(0);
- //}
- #endregion
- //合并rgb和透明度
- Mat[] mats = rgb_ap.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_ap;
- Cv2.Merge(arr, src);
- Scalar scalar = new Scalar(255, 255, 255, 255);
- if (isDis)
- {
- foreach (var p in rectList)
- {
- Point2f[] point2F = p.Points();
- double width = (point2F[0].X - point2F[1].X) / 2;
- double height = (point2F[0].Y - point2F[1].Y) / 2;
- OpenCvSharp.Point p1 = new OpenCvSharp.Point(point2F[1].X + width, point2F[1].Y + height);
- OpenCvSharp.Point p2 = new OpenCvSharp.Point(point2F[2].X + width, point2F[2].Y + height);
- src.Line(p1, p2, scalar, 1);
- int wid = (int)p.Size.Width;
- double d1= wid* Micron;
- src.PutText(Math.Round(d1, 2).ToString(), p2, HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0, 255), 1);
- width = (point2F[3].X - point2F[0].X) / 2;
- height = (point2F[0].Y - point2F[3].Y) / 2;
- OpenCvSharp.Point p3 = new OpenCvSharp.Point(point2F[0].X + width, point2F[3].Y + height);
- OpenCvSharp.Point p4 = new OpenCvSharp.Point(point2F[1].X + width, point2F[2].Y + height);
- src.Line(p3, p4, scalar, 1);
- int hei = (int)p.Size.Height;
- double d2 = hei * Micron;
- src.PutText(Math.Round(d2, 2).ToString(), p3, HersheyFonts.HersheyPlain, 1, new Scalar(0, 0, 255, 255), 1);
- }
- }
- if (isJu)
- {
-
- src.DrawContours(rectListPoint, -1, scalar, 1);
- }
- return src;
- }
-
- /// <summary>
- /// 单晶删除颗粒
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DebrisRemoval_Cryst_Del(Mat src)
- {
- temp_ap = src.CvtColor(ColorConversionCodes.BGR2GRAY);
- using (new Window("s", WindowMode.Normal, temp_ap))
- {
- Cv2.WaitKey(0);
- }
- //寻找连通分量
- Mat labelMat = new Mat();
- Mat stats = new Mat();
- Mat centroids = new Mat();
- int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
- //寻找在范围内需要删除的碎屑
- keyValuePairs.Clear();
-
- if (delPointFs != null && delPointFs.Count > 0)
- {
- for (int i = 0; i < delPointFs.Count; i++)
- {
- int qx = (int)delPointFs[i].X;
- int qy = (int)delPointFs[i].Y;
- int label = labelMat.At<int>(qy, qx);
- if (label > 0 && !keyValuePairs.ContainsKey(label))
- {
- keyValuePairs.Add(label, 1);
- }
- }
- }
-
- labelMat.ForEachAsInt32(CommonForEachDel);
-
-
- return temp_ap.Clone();
- }
- private static void CommonForEachDel(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0 && keyValuePairs.ContainsKey(v))
- {
- temp_ap.Set<int>(y, x, 0);
- }
- }
- //寻找角点做角曲率
- private static double GetRoundness1(int width, int height, int x, int y)
- {
- OpenCvSharp.Point core = new OpenCvSharp.Point();
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
- double dist = 0;
- double maxdist = 0;
- for (int i = 0; i < width; i++)
- {
- for (int j = 0; j < height; j++)
- {
- OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
- dist = Cv2.PointPolygonTest(contours[0], point, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- core = point;
- }
- }
- }
- Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
- double roundness = 0;
- //寻找角点
- InputArray contoursAll = InputArray.Create(contours[0]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- Point2f[] cornersPoint = Cv2.GoodFeaturesToTrack(ground, 100, 0.01, 30, new Mat(), 7, false, 0.04);
- foreach (var item in cornersPoint)
- {
- Cv2.Circle(ground, Convert.ToInt16(item.X), Convert.ToInt16(item.Y), 10, Scalar.White, 2);
- int index = contours[0].ToList().FindIndex(u => Math.Abs(u.X - item.X) < 3 && Math.Abs(u.Y - item.Y) < 3);
- List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
- list.Add(item);
- int nv = 10;
- if (index > nv)
- {
- list.Add(contours[0][index - nv]);
- }
- else
- {
- int ind = nv - index;
- list.Add(contours[0][contours[0].Length - nv - 1]);
- }
- if (index + nv < contours[0].Length)
- {
- list.Add(contours[0][index + nv]);
- }
- else
- {
- list.Add(contours[0][index + nv - contours[0].Length]);
- }
- double dis1, dis2, dis3;
- double cosA, sinA, dis;
- OpenCvSharp.Point2f P1 = list[0];
- OpenCvSharp.Point2f P2 = list[1];
- OpenCvSharp.Point2f P3 = list[2];
- dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
- dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
- dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
- dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
- cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
- sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
- double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
- curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
- roundness += curvity;
- }
- double ri = roundness / maxdist;
- ri = ri / cornersPoint.Length;
- using (new Window("ss", WindowMode.Normal, ground))
- {
- Cv2.WaitKey(0);
- }
- return ri;
- }
- //寻找凸包做角曲率
- private static double GetRoundness2(int width, int height, int x, int y)
- {
- OpenCvSharp.Point core = new OpenCvSharp.Point();
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(ground, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- Mat open = Mat.Zeros(ground.Size(), MatType.CV_8UC3);
- double dist = 0;
- double maxdist = 0;
- for (int i = 0; i < width; i++)
- {
- for (int j = 0; j < height; j++)
- {
- OpenCvSharp.Point point = new OpenCvSharp.Point(x + i, y + j);
- dist = Cv2.PointPolygonTest(contours[0], point, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- core = point;
- }
- }
- }
- //寻找角点
- InputArray contoursAll = InputArray.Create(contours[0]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- //内切圆
- Cv2.Circle(ground, Convert.ToInt16(core.X), Convert.ToInt16(core.Y), Convert.ToInt32(maxdist), Scalar.Black, 2);
- double roundness = 0;
- Cv2.DrawContours(open, new List<List<OpenCvSharp.Point>>() { outArr }, 0, Scalar.White, 2);
- for (int i = 0; i < outArr.Count(); i++)
- {
- Point2f item = outArr[i];
- List<OpenCvSharp.Point2f> list = new List<OpenCvSharp.Point2f>();
- list.Add(item);
- if (i == 0)
- {
- list.Add(outArr[outArr.Count() - 1]);
- }
- else
- {
- list.Add(outArr[i - 1]);
- }
- if (i == (outArr.Count() - 1))
- {
- list.Add(outArr[0]);
- }
- else
- {
- list.Add(outArr[i + 1]);
- }
- double dis1, dis2, dis3;
- double cosA, sinA, dis;
- OpenCvSharp.Point2f P1 = list[0];
- OpenCvSharp.Point2f P2 = list[1];
- OpenCvSharp.Point2f P3 = list[2];
- dis1 = Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y));
- dis2 = Math.Sqrt((P1.X - P3.X) * (P1.X - P3.X) + (P1.Y - P3.Y) * (P1.Y - P3.Y));
- dis3 = Math.Sqrt((P2.X - P3.X) * (P2.X - P3.X) + (P2.Y - P3.Y) * (P2.Y - P3.Y));
- dis = dis1 * dis1 + dis3 * dis3 - dis2 * dis2;
- cosA = dis / (2 * dis1 * dis3);//余弦定理求角度
- sinA = Math.Sqrt(1 - cosA * cosA);//求正弦
- double curvity = 0.5 * dis2 / sinA;//正弦定理求外接圆半径
- curvity = 1 / curvity;//半径的倒数是曲率,半径越小曲率越大
- roundness += curvity;
- }
- double ri = roundness / maxdist;
- ri = ri / outArr.Count();
- using (new Window("open", WindowMode.Normal, open))
- using (new Window("ss", WindowMode.Normal, ground))
- {
- Cv2.WaitKey(0);
- }
- return ri;
- }
- private static readonly object locker = new object();
- //获取连通域点
- private static void CommonForEachForCon(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0)
- {
- try
- {
- lock (locker)
- {
- AllFields[v - 1].Add(new OpenCvSharp.Point(x, y));
- }
- }
- catch (Exception e)
- {
- throw;
- }
- }
- }
- private static void CommonForEachForArc(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0 && hindex != v)
- {
- ground.Set<int>(y, x, 0);
- }
- }
- /// <summary>
- /// 单晶Canny去噪点
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DebrisRemoval_CrystCanny(Mat src)
- {
- temp_ap = src;
- //寻找连通分量
- Mat labelMat = new Mat();
- Mat stats = new Mat();
- Mat centroids = new Mat();
- int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
- //寻找在范围内需要删除的碎屑
- keyValuePairs.Clear();
- for (int h = 1; h < centroids.Height; h++)
- {
- int areaField1 = stats.At<int>(h, 4);
- int x = stats.At<int>(h, 0);
- int y = stats.At<int>(h, 1);
- int width = stats.At<int>(h, 2);
- int height = stats.At<int>(h, 3);
- //面积小于30的孔隙删除
- if (areaField1 <= 500)
- {
- keyValuePairs.Add(h, 1);
- }
- }
- labelMatForSel = labelMat;
- labelMat.ForEachAsInt32(CommonForEachForInt32_CrystCanny);
- return temp_ap;
- }
- private static void CommonForEachForInt32_CrystCanny(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0 && keyValuePairs.ContainsKey(v))
- {
- temp_ap.Set<int>(y, x, 0);
- }
- }
- #endregion
- #region 有视场 二值提取
- /// <summary>
- /// 二值操作-二值提取-有视场
- /// </summary>
- /// <param name="src">视场mat</param>
- /// <param name="mat">原图mat</param>
- /// <param name="lists">参数列表</param>
- /// <returns></returns>
- public static Mat ImageBinaryExtraction(Mat source, Mat mat, List<Args> lists, bool findContours = false)
- {
- //以下是参数信息---------------------
- ///1个颜色区间还是2个
- colorInterval = 1;
- //第一个二值区间
- colorOneStart = 0;
- colorOneEnd = 0;
- //第二个二值区间
- colorTwoStart = 0;
- colorTwoEnd = 0;
- //第三个二值区间
- colorThreeStart = 0;
- colorThreeEnd = 0;
- //处理细节
- //删除边界对象
- bool deleteBoundaryObject = false;
- //孔洞填充
- bool holeFilling = false;
- //碎屑删除
- bool debrisRemoval = false;
- //碎屑删除面积起
- debrisAreaStart = 0;
- //碎屑删除面积止
- debrisAreaEnd = 0;
- //二值样式
- //1实心 2边线
- int binaryStyle = 0;
- //相颜色
- Color phaseColor = Color.Red;
- //目标选择
- int targetSelection = 1;
- for (int i = 0; i < lists.Count; i++)
- {
- Args args = lists[i];
- switch (args.Key)
- {
- case "colorInterval":
- {
- if (args.Value is Boolean)
- colorInterval = (Boolean)args.Value ? 2 : 1;
- else
- colorInterval = (int)args.Value;
- }
- break;
- case "scope1":
- colorOneStart = (int)((List<double>)args.Value)[0];
- colorOneEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope2":
- colorTwoStart = (int)((List<double>)args.Value)[0];
- colorTwoEnd = (int)((List<double>)args.Value)[1];
- break;
- case "scope3":
- colorThreeStart = (int)((List<double>)args.Value)[0];
- colorThreeEnd = (int)((List<double>)args.Value)[1];
- break;
- case "deleteBoundaryObject":
- deleteBoundaryObject = (bool)args.Value;
- break;
- case "holeFilling":
- holeFilling = (bool)args.Value;
- break;
- case "debrisRemoval":
- debrisRemoval = (bool)args.Value;
- break;
- case "binaryStyle":
- binaryStyle = (int)args.Value;
- break;
- case "phaseColor":
- phaseColor = Color.FromArgb((int)args.Value);
- break;
- case "targetSelection":
- targetSelection = (int)args.Value;
- break;
- case "scope4":
- debrisAreaStart = (int)((List<double>)args.Value)[0];
- debrisAreaEnd = (int)((List<double>)args.Value)[1];
- break;
- default:
- break;
- }
- }
- vec4B.Item0 = phaseColor.B;
- vec4B.Item1 = phaseColor.G;
- vec4B.Item2 = phaseColor.R;
- vec4B.Item3 = phaseColor.A;
- //二值提取
- Mat src = BinarizationWithView(source);
- //目标选择
- if (targetSelection != 2)
- src = CalcContoursByTargetSelection_New(temp_view, targetSelection, source);
- //碎屑删除,参考冈萨雷斯,414,9.5.3,连通分量提取
- if (debrisRemoval && debrisAreaEnd > 0)
- src = DebrisRemoval_NewWithView(src);
- //孔洞填充,参考冈萨雷斯,413,9.5.2
- if (holeFilling)
- src = HoleFilling_NewWithView(src);
- //实心/边线,参考冈萨雷斯,412,9.5.1,边界提取
- if (binaryStyle == 2)
- {
- Cv2.Erode(src, temp, null);
- src = src - temp;
- src = BaseTools.MergeMatFromMatArr(src, vec4B);
- }
- return src;
- }
- /// <summary>
- /// 二值提取
- /// </summary>
- /// <param name="source">视场图像</param>
- /// <param name="mat">原图像</param>
- /// <param name="colorInterval">1个或2个颜色区间</param>
- /// <param name="colorOneStart"></param>
- /// <param name="colorOneEnd"></param>
- /// <param name="colorTwoStart"></param>
- /// <param name="colorTwoEnd"></param>
- /// <param name="colorThreeStart"></param>
- /// <param name="colorThreeEnd"></param>
- /// <param name="phaseColor">相颜色</param>
- /// <returns></returns>
- private static Mat BinarizationWithView(Mat source)
- {
- Mat[] arr = source.Split();
- alpha = arr[3];
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp_view = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- srcGray.ForEachAsByte(GrayForEachAsByteWithView);
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void GrayForEachAsByteWithView(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (colorInterval == 1)
- {
- if (v >= colorOneStart && v <= colorOneEnd)
- {
- if (alpha.At<byte>(y, x) > 0)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- temp_view.Set<Vec4b>(y, x, vec4B);
- }
- else
- {
- temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
- }
- }
- }
- else
- {
- if (((v >= colorTwoStart && v <= colorTwoEnd) || (v >= colorThreeStart && v <= colorThreeEnd)))
- {
- if (alpha.At<byte>(y, x) > 0)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- temp_view.Set<Vec4b>(y, x, vec4B);
- }
- else
- {
- temp_view.Set<Vec4b>(y, x, new Vec4b(vec4B.Item0, vec4B.Item1, vec4B.Item2, 0));
- }
- }
- }
- }
- /// <summary>
- /// 新碎屑删除,使用连通分量找寻碎屑
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat DebrisRemoval_NewWithView(Mat src)
- {
- Mat[] arr = src.Split();
- rgb_ap = BaseTools.MergeMatFromMatArr(arr);
- temp_ap = arr[3].Clone();
- //寻找连通分量
- Mat labelMat = new Mat();
- Mat stats = new Mat();
- Mat centroids = new Mat();
- int nonenum = Cv2.ConnectedComponentsWithStats(temp_ap, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
- //寻找在范围内需要删除的碎屑
- keyValuePairs.Clear();
- for (int h = 1; h < centroids.Height; h++)
- {
- int areaField1 = stats.At<int>(h, 4);
- if (debrisAreaStart <= areaField1 && areaField1 <= debrisAreaEnd)
- {
- keyValuePairs.Add(h, 1);
- }
- }
- labelMat.ForEachAsInt32(CommonForEachForInt32);
- //合并rgb和透明度
- Mat[] mats = rgb_ap.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = temp_ap;
- Cv2.Merge(arr, src);
- return src;
- }
- /// <summary>
- /// 新孔洞填充,采用形态学填充
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat HoleFilling_NewWithView(Mat src)
- {
- Mat[] arr2 = src.Split();
- Mat tempc = arr2[3];
- //去掉透明层
- Mat mat = src.CvtColor(ColorConversionCodes.BGRA2BGR);
- //填充孔洞
- mat = BaseTools.FillHole(mat, new Scalar(255 - vec4B.Item0, 255 - vec4B.Item1, 255 - vec4B.Item2));
- tempc = BaseTools.FillHole(tempc, new Scalar(255));
- //循环处理
- mat.ForEachAsVec3b(RGBForEachAsByteForHoleFillingNewWithView);
- Mat[] arr1 = mat.Split();
- arr2[0] = arr1[0];
- arr2[1] = arr1[1];
- arr2[2] = arr1[2];
- arr2[3] = tempc;
- Cv2.Merge(arr2, src);
- return src;
- }
- private static void RGBForEachAsByteForHoleFillingNewWithView(Vec3b* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- if (value->Item0 == 255 && value->Item1 == 255 && value->Item2 == 255)
- {
- value->Item0 = vec4B.Item0;
- value->Item1 = vec4B.Item1;
- value->Item2 = vec4B.Item2;
- }
- }
- /// <summary>
- /// 目标选择
- /// </summary>
- /// <param name="src"></param>
- /// <param name="mat"></param>
- /// <param name="targetSelection"></param>
- /// <param name="source"></param>
- /// <returns></returns>
- public static Mat CalcContoursByTargetSelection_New(Mat src, int targetSelection, Mat source)
- {
- Mat[] arr = src.Split();
- alpha = arr[3].Clone();
- Mat rgb = BaseTools.MergeMatFromMatArr(arr);
- Mat alphatemp = arr[3].Clone();
- Mat mask = Mat.Zeros(rgb.Rows + 2, rgb.Cols + 2, MatType.CV_8UC1);
- //考虑循环填充,填充视场的透明层和原图的透明层,然后比较填充区域的大小
- //但是循环的时候需要少循环像素,可以处理视场的透明层,减少循环量
- //同时记录种子点,然后根据targetSelection判断是填充透明还是不透明
- Mat rgbClone = rgb.Clone();
- List<OpenCvSharp.Point> points = new List<OpenCvSharp.Point>();
- for (int h = 0; h < alphatemp.Height; h++)
- {
- for (int w = 0; w < alphatemp.Width; w++)
- {
- int v = alphatemp.At<byte>(h, w);
- if (v > 0)
- {
- int a = Cv2.FloodFill(alphatemp, new OpenCvSharp.Point(w, h), new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- int b = Cv2.FloodFill(rgbClone, new OpenCvSharp.Point(w, h), new Scalar(0, 0, 0), out rect, null, null, FloodFillFlags.Link8);
- if (a != b)
- {
- points.Add(new OpenCvSharp.Point(w, h));
- }
- }
- }
- }
- if (points.Count > 0)
- {
- foreach (OpenCvSharp.Point p in points)
- {
- if (targetSelection == 1)
- {
- Cv2.FloodFill(alpha, p, new Scalar(0), out rect, null, null, FloodFillFlags.Link8);
- }
- else if (targetSelection == 3)
- {
- Cv2.FloodFill(rgb, mask, p, new Scalar(vec4B.Item0, vec4B.Item1, vec4B.Item2), out rect, null, null, FloodFillFlags.Link8);
- }
- }
- }
- if (targetSelection == 3)
- {
- Mat t = new Mat(mask, new Rect(1, 1, rgb.Width, rgb.Height));
- alpha = alpha + t * 255;
- }
- //合并rgb和透明度
- Mat[] mats = rgb.Split();
- arr[0] = mats[0];
- arr[1] = mats[1];
- arr[2] = mats[2];
- arr[3] = alpha;
- Cv2.Merge(arr, src);
- return src;
- }
- #endregion
- private static void CommonForEachForInt32(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0 && keyValuePairs.ContainsKey(v))
- {
- rgb_ap.Set<Vec3b>(y, x, new Vec3b(0, 0, 0));
- temp_ap.Set<int>(y, x, 0);
- //手动画圆
- if (ListRadiusColor.Count > 0)
- {
- int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
- if (ListRadiusColor.Count > 1)
- {
- for (int i = 0; i < ListRadiusColor.Count - 1; i++)
- {
- int r = i == 0 ? 0 : ListRadiusColor.ElementAt(ListRadiusColor.Count - i).Key;
- int r2 = ListRadiusColor.ElementAt(ListRadiusColor.Count - 1 - i).Key;
- if (r < d && d <= r2)
- {
- poAreaList[i]--;
- break;
- }
- }
- }
- }
- else if (circleCount > 1)
- {
- int d = Convert.ToInt32(Math.Sqrt((x - center.X) * (x - center.X) + (y - center.Y) * (y - center.Y)));
- for (int i = 0; i < circleCount; i++)
- {
- int r = Convert.ToInt32(CircleR * (i));
- int r2 = Convert.ToInt32(CircleR * (i + 1));
- if (r < d && d <= r2)
- {
- poAreaList[i]--;
- break;
- }
- }
- }
- }
- }
- private static void CommonForEachForSel(int* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- int v = *value;
- if (v > 0 && keyValueSel.ContainsKey(v))
- {
- rgb_ap.Set<Vec3b>(y, x, new Vec3b(255, 255, 0));
- }
- }
- /// <summary>
- /// 开裂球识别霍夫圆
- /// </summary>
- /// <param name="src"></param>
- public static Mat DrwCrackBall(Mat src)
- {
- temp = src.Clone();
- Mat dst = new Mat();
- //1:因为霍夫圆检测对噪声比较敏感,所以首先对图像做一个中值滤波或高斯滤波(噪声如果没有可以不做)
- Mat m1 = new Mat();
- Cv2.MedianBlur(temp, m1, 3); // ksize必须大于1且是奇数
- //2:转为灰度图像
- Mat m2 = m1.Clone();
- // m1.Release();
- Cv2.CvtColor(m1, m2, ColorConversionCodes.BGR2GRAY);
- CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 130, 60, 25, 35, 80);
- temp.CopyTo(dst);
- //大圆
- for (int i = 0; i < cs.Length; i++)
- {
- //画圆
- 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);
- //加强圆心显示
- Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias);
- }
- Mat srcBlack;
- int sucessCs = 0;
- int badCs = 0;
- for (int i = 0; i < cs.Length; i++)
- {
- int left = (int)cs[i].Center.X - (int)cs[i].Radius;
- int right = (int)cs[i].Center.X + (int)cs[i].Radius;
- int top = (int)cs[i].Center.Y - (int)cs[i].Radius;
- int bottom = (int)cs[i].Center.Y + (int)cs[i].Radius;
- if (left < 10 || right - 10 > temp.Width || top < 10 || bottom - 10 > temp.Height - 140)
- {
- continue;
- }
- srcBlack = new Mat(temp.Height, temp.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
- //画圆
- Cv2.Circle(srcBlack, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, Scalar.White, 1, LineTypes.AntiAlias);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(srcBlack, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- Cv2.DrawContours(srcBlack, contours, -1, Scalar.White, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- //取所有的点
- List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
- int rows = srcBlack.Height, cols = srcBlack.Width;
- for (int k = 0; k < rows; k++)
- {
- IntPtr a = srcBlack.Ptr(k);
- byte* b = (byte*)a.ToPointer();
- for (int j = 0; j < cols; j++)
- {
- if (b[j] != 0)
- {
- srPoints.Add(new OpenCvSharp.Point(j, k));
- }
- }
- }
- for (int j = 0; j < srPoints.Count; j++)
- {
- int item = temp.Get<int>(srPoints[j].Y, srPoints[j].X);
- srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
- }
- Rect bigrect = Cv2.BoundingRect(contours[0]);
- Mat rect = new Mat(srcBlack, bigrect);
- //Cv2.EqualizeHist(rect, dst);
- Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
- //Cv2.MedianBlur(dst, dst, 1);
- Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
- Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
- Mat bb = new Mat(aa.Height, aa.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
- Cv2.Circle(bb, (int)center.X, (int)center.Y, (int)cs[i].Radius - 15, Scalar.White, 1, LineTypes.AntiAlias);
- OpenCvSharp.Point[][] contoursCircleLine;
- HierarchyIndex[] hierarchyLine;
- Cv2.FindContours(bb, out contoursCircleLine, out hierarchyLine, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point> contoursCircleLineOne = new List<OpenCvSharp.Point>();
- for (int m = 0; m < contoursCircleLine.Length; m++)
- {
- for (int n = 0; n < contoursCircleLine[m].Length; n++)
- {
- contoursCircleLineOne.Add(contoursCircleLine[m][n]);
- }
- }
- //内缩
- Rect bigRect = new Rect(0, 0, rect.Width, rect.Height);
- for (int nX = bigRect.X; nX <= bigRect.Right; nX++)
- {
- for (int nY = bigRect.Y; nY <= bigRect.Bottom; nY++)
- {
- double localPos = Cv2.PointPolygonTest(contoursCircleLineOne, new Point2f(nX, nY), false);
- if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
- {
- }
- else
- {
- aa.Set<int>(nX, nY, 0);
- }
- }
- }
- OpenCvSharp.Point[][] contours1 = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchy1 = new HierarchyIndex[] { };
- Cv2.FindContours(aa, out contours1, out hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- // Cv2.CvtColor(aa, aa, ColorConversionCodes.RGB2BGR);
- List<OpenCvSharp.Point[]> contoursHoleList = contours1.OrderByDescending(t => t.Count()).ToList();
- //if (contoursHoleList.Count == 0)
- //{
- // continue;
- //}
- double isk = 0;
- float widthto = 0;
- float heightto = 0;
- for (int k = 0; k < contours1.Count(); k++)
- {
- RotatedRect rectR = Cv2.MinAreaRect(contours1[k]); //计算每个轮廓最小外接矩形
- Rect rectB = Cv2.BoundingRect(contours1[k]);
- float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
- float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
- height = height == 0 ? 1 : height;
- double distance = 0;
- for (int m = 0; m < contours1[k].Count(); m++)
- {
- Point2f centerCoutours = new Point2f(contours1[k][m].X, contours1[k][m].Y);
- distance += centerCoutours.DistanceTo(center);
- }
- distance = distance / contours1[k].Count();
- OpenCvSharp.Point[] lineDmax = new OpenCvSharp.Point[2];
- RotatedRect minRect;
- // double ratio = GetDMax(contours[k], out lineDmax) / GetDMin(contours[k], out minRect);
- if (distance > 55)
- {
- //再边缘
- //Cv2.DrawContours(aa, contours, k, Scalar.Yellow, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- }
- else if (/*ratio > 2 && */Cv2.ArcLength(contours1[k], true) < 15)
- {
- //像素太少的去掉
- // Cv2.DrawContours(aa, contours, k, Scalar.Blue, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- }
- else
- {
- widthto = widthto + width;
- isk = isk + Cv2.ContourArea(contours1[k]);
- if (Cv2.ContourArea(contours1[k]) > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
- {
- break;
- }
- //最终想要的裂缝
- //Cv2.DrawContours(aa, contours1, k, Scalar.Green, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- List<OpenCvSharp.Point> bigmap = new List<OpenCvSharp.Point>();
- foreach (OpenCvSharp.Point item in contours1[k])
- {
- bigmap.Add(new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y });
- }
- List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
- tol.Add(bigmap);
- Cv2.DrawContours(temp, tol, 0, colorList[1], 1, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- }
- }
- if (isk > Math.PI * cs[i].Radius * cs[i].Radius * 0.3)
- {
- continue;
- }
- if (isk > 0)
- {
- heightto = (float)isk / widthto;
- heightto = heightto < 1 ? 1 : heightto;
- //画圆
- Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[1], 2, LineTypes.AntiAlias);
- //加强圆心显示
- Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[1], 6, LineTypes.AntiAlias);
- }
- else
- {
- //画圆
- Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius, colorList[0], 2, LineTypes.AntiAlias);
- //加强圆心显示
- Cv2.Circle(temp, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, colorList[0], 6, LineTypes.AntiAlias);
- }
- 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 };
- poList.Add(po);
- }
- return temp.Clone();
- }
- /// <summary>
- /// 开裂球识别分水岭
- /// </summary>
- /// <param name="src"></param>
- public static Mat DrwCrackBall_New(Mat src, Mat source)
- {
- temp = source.Clone();
- Mat gray = new Mat();
- Mat dst = new Mat();
- Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
- OpenCvSharp.Point[][] cs;
- HierarchyIndex[] hierarchycs;
- Cv2.FindContours(gray, out cs, out hierarchycs, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- particlePixles.Clear();
- Mat srcBlack;
- int sucessCs = 0;
- int badCs = 0;
- int index = 1;
- double heig = (double)140 / (double)1920;
- for (int i = 0; i < cs.Length; i++)
- {
- //边界颗粒去除
- int coutp = 0;
- for (int j = 0; j < cs[i].Length; j++)
- {
- int cspx = cs[i][j].X;
- int cspy = cs[i][j].Y;
- if (cspx == 0 || cspy == 0 || cspx > src.Cols - 5 || cspy > src.Rows - heig * src.Rows - 5)
- {
- coutp++;
- }
- }
- if (coutp > 5)
- {
- continue;
- }
- //面积过小去除
- if (Cv2.ContourArea(cs[i]) < 4000)
- {
- continue;
- }
- Rect bigrect = Cv2.BoundingRect(cs[i]);
- if (CreackBallPointFs.Count > 0)
- {
- bool isnei = false;
- foreach (var item in CreackBallPointFs)
- {
- double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
- if (dq > 0)
- {
- isnei = true;
- break;
- }
- }
- if (isnei)
- {
- continue;
- }
- }
- //圆度过大去除
- //afa参考代码
- double s = Cv2.ContourArea(cs[i]);//轮廓面积
- double c = Cv2.ArcLength(cs[i], true); //轮廓周长
- double afa = 4 * Math.PI * s / (c * c); //afa计算
- afa = Math.Abs(afa - 1);
- //if (afa > 0.6)
- //{
- // continue;
- //}
- afa = afa * 1000;
- if (CreackBallPointFsK.Count > 0)
- {
- bool isnei = false;
- foreach (var item in CreackBallPointFsK)
- {
- double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
- if (dq > 0)
- {
- isnei = true;
- break;
- }
- }
- if (isnei)
- {
- Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 1, (int)afa };
- poList.Add(po1);
- continue;
- }
- }
- if (CreackBallPointFsP.Count > 0)
- {
- bool isnei = false;
- foreach (var item in CreackBallPointFsP)
- {
- double dq = Cv2.PointPolygonTest(cs[i], new Point2f(item.X, item.Y), false);
- if (dq > 0)
- {
- isnei = true;
- break;
- }
- }
- if (isnei)
- {
- Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- List<int> po1 = new List<int>() { (int)bigrect.X, (int)bigrect.Y, (int)bigrect.Height, -1, -1, 0, (int)afa };
- poList.Add(po1);
- continue;
- }
- }
- srcBlack = new Mat(gray.Height, gray.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
- Cv2.DrawContours(srcBlack, cs, i, Scalar.White, -1, LineTypes.Link4, hierarchycs, 2, new OpenCvSharp.Point(0, 0));
- //取所有的点
- List<OpenCvSharp.Point> srPoints = new List<OpenCvSharp.Point>();
- int rows = srcBlack.Height,
- cols = srcBlack.Width;
- for (int k = 0; k < rows; k++)
- {
- IntPtr a = srcBlack.Ptr(k);
- byte* b = (byte*)a.ToPointer();
- for (int j = 0; j < cols; j++)
- {
- if (b[j] != 0)
- {
- srPoints.Add(new OpenCvSharp.Point(j, k));
- }
- }
- }
- for (int j = 0; j < srPoints.Count; j++)
- {
- int item = source.Get<int>(srPoints[j].Y, srPoints[j].X);
- srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
- }
- double outR = Math.Sqrt(s / Math.PI) * 0.5;
- double dist = 0;
- double maxdist = 0;
- //中心点
- OpenCvSharp.Point ballCenter = new OpenCvSharp.Point();
- foreach (var item in srPoints)
- {
- dist = Cv2.PointPolygonTest(cs[i], item, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- ballCenter = item;
- }
- }
- List<OpenCvSharp.Point> sel = new List<OpenCvSharp.Point>();
- for (int k = 0; k < cs[i].Length; k++)
- {
- sel.Add(cs[i][k]);
- }
- Mat rect = new Mat(srcBlack, bigrect);
- Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
- Mat aa = dst.Threshold(colorOneStart, colorOneEnd, ThresholdTypes.BinaryInv);
- for (int x = 0; x < aa.Cols; x++)
- {
- for (int y = 0; y < aa.Rows; y++)
- {
- double localPos = Cv2.PointPolygonTest(sel, new Point2f(x + bigrect.X, y + bigrect.Y), false);
- if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘
- {
- }
- else
- {
- aa.Set<int>(y, x, 0);
- }
- }
- }
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
- //开操作,也可省落变量前缀名
- Cv2.MorphologyEx(aa, aa, MorphTypes.Dilate, kernel, new OpenCvSharp.Point(-1, -1));
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t.Count()).ToList();
- double isk = 0;
- float widthto = 0;
- double heightto = 0;
- double arclength = 0;
- Point2f center = new Point2f(aa.Cols / 2, aa.Rows / 2);
- double area = Cv2.ContourArea(cs[i]);
- double ra = aa.Cols < aa.Rows ? aa.Cols / 2 : aa.Rows / 2;
- for (int k = 0; k < contoursHoleList.Count(); k++)
- {
- double tarea = Cv2.ContourArea(contoursHoleList[k]);
- RotatedRect rectR = Cv2.MinAreaRect(contoursHoleList[k]); //计算每个轮廓最小外接矩形
- Rect rectB = Cv2.BoundingRect(contoursHoleList[k]);
- float width = rectR.Size.Width >= rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
- float height = rectR.Size.Width < rectR.Size.Height ? rectR.Size.Width : rectR.Size.Height;
- height = height == 0 ? 1 : height;
- List<OpenCvSharp.Point> poingtForUse = new List<OpenCvSharp.Point>();
- List<OpenCvSharp.Point> tempList = new List<OpenCvSharp.Point>();
- int outCount = 0;
- foreach (OpenCvSharp.Point item in contoursHoleList[k])
- {
- OpenCvSharp.Point point1 = new OpenCvSharp.Point() { X = item.X + bigrect.X, Y = item.Y + bigrect.Y };
- double d = Cv2.PointPolygonTest(cs[i], point1, true);
- tempList.Add(point1);
- if (d < 5)
- {
- outCount++;
- }
- }
- if (((outCount * 100) / contoursHoleList[k].Count()) < 70)
- {
- tempList.ForEach(p => poingtForUse.Add(p));
- }
- // double ratio = GetDMax(contoursHoleList[k], out lineDmax) / GetDMin(contoursHoleList[k], out minRect);
- double carea = Cv2.ContourArea(contoursHoleList[k]);
- double cleng = Cv2.ArcLength(contoursHoleList[k], true); //轮廓周长
- double cafa = 4 * Math.PI * s / (c * c); //afa计算
- cafa = Math.Abs(cafa - 1);
- if (poingtForUse.Count < 25)
- {
- }
- else if (cleng < 30)
- {
- }
- else
- {
- arclength = arclength + Cv2.ArcLength(contoursHoleList[k], true);
- widthto = widthto + width;
- isk = isk + Cv2.ContourArea(contoursHoleList[k]);
- List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
- tol.Add(poingtForUse);
- Cv2.DrawContours(temp, tol, 0, colorList[1], -1, LineTypes.Link8, null, 2, new OpenCvSharp.Point(0, 0));
- //for (int p = 0; p < poingtForUse.Count(); p++)
- //{
- // temp.Set<Vec4b>(poingtForUse[p].Y, poingtForUse[p].X, vec4BList[1]);
- //}
- }
- }
- if (isk > 0)
- {
- heightto = isk / arclength;
- heightto = heightto < 1 ? 1 : heightto;
- Cv2.DrawContours(temp, cs, i, new Scalar(0, 0, 255, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- }
- else
- {
- Cv2.DrawContours(temp, cs, i, new Scalar(255, 0, 0, 255), 2, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- }
- particlePixles.Add(index++, sel);
- 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 };
- poList.Add(po);
- }
- return temp.Clone();
- }
- /// <summary>
- /// 开裂球选择
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat SelectBall(Mat src, int x, int y, int r)
- {
- temp = src.Clone();
- //画圆
- // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
- //加强圆心显示
- Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
- return temp;
- }
- /// <summary>
- /// 开裂球选择
- /// </summary>
- /// <param name="src"></param>
- /// <returns></returns>
- private static Mat SelectBallInt(Mat src, int index)
- {
- temp = src.Clone();
- //画圆
- // Cv2.Circle(temp, x, y, r, colorList[4], 2, LineTypes.AntiAlias);
- List<List<OpenCvSharp.Point>> tol = new List<List<OpenCvSharp.Point>>();
- tol.Add(particlePixles[index]);
- Cv2.DrawContours(temp, tol, 0, colorList[4], 4, LineTypes.Link8, null, 4, new OpenCvSharp.Point(0, 0));
- RotatedRect rectR = Cv2.MinAreaRect(particlePixles[index]);
- double are = Cv2.ContourArea(particlePixles[index]);
- //加强圆心显示
- // Cv2.Circle(temp, x + r / 2, y + r / 2, 8, colorList[4], 6, LineTypes.AntiAlias);
- return temp;
- }
- private static void GetHalfCircles(Mat color)
- {
- Mat canny = new Mat();
- Mat gray = new Mat();
- Cv2.CvtColor(color, gray, ColorConversionCodes.BGRA2GRAY);
- Cv2.Canny(gray, canny, 200, 20);
- CircleSegment[] circles = Cv2.HoughCircles(gray, HoughMethods.Gradient, 1, 80, 70, 24, 33, 52);
- for (int i = 0; i < circles.Length; i++)
- {
- //加强圆心显示
- Cv2.Circle(color, (int)circles[i].Center.X, (int)circles[i].Center.Y, 3, new Scalar(0, 255, 255), -1, LineTypes.AntiAlias);
- //画圆
- 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);
- }
- Mat dt = new Mat();
- Cv2.BitwiseNot(canny, canny);
- Cv2.DistanceTransform(canny, dt, DistanceTypes.L2, DistanceMaskSize.Mask3);
- float minInlierDist = 2.0f;
- for (int i = 0; i < circles.Length; i++)
- {
- int counter = 0;
- int inlier = 0;
- Point2f center = circles[i].Center;
- float radius = circles[i].Radius;
- float maxInlierDist = radius / 25.0f;
- if (maxInlierDist < minInlierDist) maxInlierDist = minInlierDist;
- for (float t = 0; t < 2 * Math.PI; t += 0.1f)
- {
- counter++;
- float cX = radius * (float)Math.Cos(t) + circles[i].Center.X;
- float cY = radius * (float)Math.Sin(t) + circles[i].Center.Y;
- if (cX < 0)
- {
- cX = 0;
- }
- if (cY < 0)
- {
- cY = 0;
- }
- if (dt.At<float>((int)cY, (int)cX) < maxInlierDist)
- {
- inlier++;
- Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(0, 255, 0));
- }
- else
- {
- Cv2.Circle(color, (int)cX, (int)cY, 3, new Scalar(255, 0, 0));
- }
- }
- }
- using (new Window("color", WindowMode.Normal, color))
- {
- Cv2.WaitKey(0);
- }
- }
- /// <summary>
- /// 二值提取隔膜
- /// </summary>
- /// <param name="source">源</param>
- /// <param name="colorInterval">1个或2个颜色区间</param>
- /// <param name="colorOneStart"></param>
- /// <param name="colorOneEnd"></param>
- /// <param name="colorTwoStart"></param>
- /// <param name="colorTwoEnd"></param>
- /// <param name="colorThreeStart"></param>
- /// <param name="colorThreeEnd"></param>
- /// <returns></returns>
- private static Mat BinarizationForM(Mat source)
- {
- Mat srcGray;
- if (source.Type() == MatType.CV_8UC1)
- {
- srcGray = source;
- }
- else
- {
- srcGray = source.CvtColor(ColorConversionCodes.BGR2GRAY);
- }
- temp = new Mat(source.Rows, source.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- try
- {
- srcGray.ForEachAsByte(GrayForEachAsByteForM);
- }
- catch (Exception)
- {
- throw;
- }
- return temp.Clone();
- }
- /// <summary>
- /// 并行循环
- /// </summary>
- /// <param name="value"></param>
- /// <param name="position"></param>
- private static void GrayForEachAsByteForM(byte* value, int* position)
- {
- int y = position[0];
- int x = position[1];
- byte v = *value;
- if (v >= colorOneStart && v <= colorOneEnd && y < imageHight - 70)
- {
- temp.Set<Vec4b>(y, x, vec4B);
- }
- }
-
- }
- }
|