12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369 |
- using OpenCvSharp;
- using PaintDotNet.Annotation;
- using PaintDotNet.Base;
- using PaintDotNet.Base.CommTool;
- using PaintDotNet.Base.Functionodel;
- using PaintDotNet.Base.SettingModel;
- using PaintDotNet.Data.Param;
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Windows.Forms;
- namespace PaintDotNet
- {
- class BinaryClassForB
- {
- private int menuId;
- protected static string ParamKey_binaryStyle = "binaryStyle";//二值样式
- //protected static string ParamKey_displaygrid = "displaygrid";//显示网格
- //protected static string ParamKey_displaysections = "displaysections";//显示截点
- /// <summary>
- /// 是否针对全图进行二值化操作
- /// </summary>
- public bool processWholeMat = false;
- /// <summary>
- /// 是否显示视场
- /// </summary>
- public Boolean ShowDrawClassView = true;
- /// <summary>
- /// 调色板
- /// </summary>
- PaintDotNet.ColorsForm colorsForm1;
- /// <summary>
- /// 构造工作结构
- /// </summary>
- private Dictionary<int, DocumentItem> documentItems;
- /// <summary>
- /// 需要的数据在这里引用
- /// </summary>
- CustomControl.BinaryControlSmaller bmc;
- /// <summary>
- /// 需要的数据在这里引用
- /// </summary>
- CustomControl.BinaryControl bc;
- AppWorkspace appWorkspace;
- DocumentWorkspaceWindow documentWorkspace;
- ListView listView1;
- public DedicatedAnalysis.Battery.BatteryCrackBallDialog parent { get; set; }
- //二次球与单晶
- public DedicatedAnalysis.Battery.BatteryBallAndCrystalDialog parentCrystal { get; set; }
- //单晶
- public DedicatedAnalysis.Battery.BatteryCrystalDialog parentSinglCrystal { get; set; }
- //单晶
- public DedicatedAnalysis.Battery.BatteryPrimaryDialog parentPrimary { get; set; }
- /// <summary>
- /// 是否要调用二值化的算法
- /// </summary>
- private bool toApplyBinary = true;
- /// <summary>
- /// 处理程序
- /// </summary>
- private ParamObject action = new Data.Action.Action0001();
- /// <summary>
- /// 二值参数配置值(当前图片)
- /// </summary>
- private BinaryExtractionModel binaryExtractionModel;
- /// <summary>
- /// 二值参数是否进行全部应用,用于更新图片二值化效果,默认为false
- /// </summary>
- private Dictionary<string, bool> binaryModelFlag = new Dictionary<string, bool>();
- /// <summary>
- /// 二值参数配置值(全部图片的)
- /// </summary>
- private Dictionary<string, BinaryExtractionModel> binaryModelDict = new Dictionary<string, BinaryExtractionModel>();
- /// <summary>
- /// 二值(备份全部图片)
- /// </summary>
- private Dictionary<string, Mat> binaryData1Dict = new Dictionary<string, Mat>();
- /// <summary>
- /// 相0的图片,处理多视场使用
- /// </summary>
- public Mat PhaseModels0Mat;
- /// <summary>
- /// 辅助线集成
- /// </summary>
- public PaintDotNet.DedicatedAnalysis.GrainSizeStandard.IntegrationClass.GrainSizeGuideClass guideClass;
- public ComboBox comboBox1;
- public static Mat dstBinary;
- //最大轮廓
- public OpenCvSharp.Point[] maxContour = new OpenCvSharp.Point[] { };
- //中心点
- public OpenCvSharp.Point center = new OpenCvSharp.Point();
- //指定圆心
- public OpenCvSharp.Point SetCenter = new OpenCvSharp.Point();
- double maxArea = 0;
- //半径
- public int r = 0;
- //半径
- public int R = 0;
- //同心圆数
- public int CilCount = 0;
- /// 存储轮廓集合
- private List<List<PointF>> lineList = new List<List<PointF>>();
- /// 存储添加孔隙集合
- private List<List<PointF>> kongLineList = new List<List<PointF>>();
- /// 存储删除孔隙集合
- private List<PointF> delLineList = new List<PointF>();
- /// 存储轮廓集合
- private List<List<PointF>> lineList_ball = new List<List<PointF>>();
- /// 存储开裂球
- private List<PointF> kailie_ball = new List<PointF>();
- /// 存储普通球
- private List<PointF> putong_ball = new List<PointF>();
- //存储选择球
- private PointF selectPointFs = new PointF();
- //处理后画过轮廓的截面孔隙图
- private Mat LunkMat = new Mat();
- //处理后的单晶图片
- private Bitmap bitDJ;
- //模块编号:1开裂球,2单晶,3二次球与单晶
- public int imageType { set; get; }
- //单晶尺寸
- public double pointsize { set; get; }
- //边界
- public int border { set; get; }
- //长宽比
- public double HW { set; get; }
- //面积率
- public double AreaRatio { set; get; }
- //底边区域
- public int borderBottom { set; get; }
- //保留小数位数
- public int numDecimals { set; get; }
- //筛选条件
- public int CheckState { set; get; }
- //是否画测距
- public bool isDis = false;
-
- //是否画矩形
- public bool isJu = false;
- /// <summary>
- /// 单位标尺
- /// </summary>
- public double unitLength = 1;
- //测量区域
- public List<OpenCvSharp.Point> Contour { set; get; }
- //提示框内容
- public string tipString = "";
- /// <summary>
- /// 公开的事件,每次二值化之后需要的计算事件写在这里
- /// </summary>
- public event EventHandler BinaryImplFinishAction;
- private void OnBinaryImplFinishAction()
- {
- if (BinaryImplFinishAction != null)
- {
- BinaryImplFinishAction(this, new EventArgs());
- }
- }
- public BinaryClassForB(int menuId)
- {
- this.menuId = menuId;
- }
- public void InitBinaryControlEvent()
- {
- if (bmc != null)
- {
- bmc.InitBinaryControlEvent();
- bmc.BinaryGetParamAction += new EventHandler(this.bcBinaryGetParamAction);
- bmc.AutoThresClickAction += new EventHandler(this.bcAutoThresClickAction);
- bmc.InverseClickAction += new EventHandler(this.bcBinaryGetParamAction);
- bmc.InverseClickAction += new EventHandler(this.bcApplyButtonImplAction);
- bmc.RadioButton1ChangedAction += new EventHandler(this.bcBinaryGetParamAction);
- bmc.RadioButton2ChangedAction += new EventHandler(this.bcBinaryGetParamAction);
- bmc.ApplyButtonImplAction += new EventHandler(this.bcApplyButtonImplAction);
- bmc.BinaryCheckedChangedAction += new EventHandler(this.bcBinaryCheckedChanged);
- bmc.OriginCheckedChangedAction += new EventHandler(this.bcOriginCheckedChanged);
- bmc.BinaryEditClickAction += new EventHandler(this.bcBinaryEditClickAction);
- bmc.PanelColorClickAction += new EventHandler(this.bcPanelColorClickAction);//初始化颜色点击事件
- return;
- }
- if (bc == null)
- return;
- bc.InitBinaryControlEvent();
- bc.BinaryGetParamAction += new EventHandler(this.bcBinaryGetParamAction);
- bc.AutoThresClickAction += new EventHandler(this.bcAutoThresClickAction);
- bc.InverseClickAction += new EventHandler(this.bcBinaryGetParamAction);
- bc.InverseClickAction += new EventHandler(this.bcApplyButtonImplAction);
- bc.RadioButton1ChangedAction += new EventHandler(this.bcBinaryGetParamAction);
- bc.RadioButton2ChangedAction += new EventHandler(this.bcBinaryGetParamAction);
- bc.ApplyButtonImplAction += new EventHandler(this.bcApplyButtonImplAction);
- bc.BinaryCheckedChangedAction += new EventHandler(this.bcBinaryCheckedChanged);
- bc.OriginCheckedChangedAction += new EventHandler(this.bcOriginCheckedChanged);
- bc.BinaryEditClickAction += new EventHandler(this.bcBinaryEditClickAction);
- bc.PanelColorClickAction += new EventHandler(this.bcPanelColorClickAction);//初始化颜色点击事件
- }
- /// <summary>
- /// 相颜色点击事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcPanelColorClickAction(object sender, EventArgs e)
- {
- this.colorsForm1.UserPrimaryColor = ColorBgra.FromColor(bmc != null ? bmc.BinaryBackColor : bc.BinaryBackColor);
- this.colorsForm1.ShowDialog();
- }
- /// <summary>
- /// 二值筛选
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcBinaryEditClickAction(object sender, EventArgs e)
- {
- if (this.documentWorkspace.PhaseModels[0].mat == null)
- {
- MessageBox.Show(PdnResources.GetString("Menu.Pleaseperonfirst.text"));
- return;
- }
- PaintDotNet.DedicatedAnalysis.GrainSizeStandard.IntegrationClass.GrainBinaryBoundaryEditingDialog boundaryEditingDialog = new PaintDotNet.DedicatedAnalysis.GrainSizeStandard.IntegrationClass.GrainBinaryBoundaryEditingDialog(this.appWorkspace, this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index, bmc != null ? bmc.BinaryBackColor : bc.BinaryBackColor
- , this.documentWorkspace.PhaseModels[0].mat.Clone(), ShowDrawClassView, this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].GetRuler(MeasurementUnit.Micron));
- ////1013###19326 晶粒度的晶界编辑页面,需要把辅助线带过去(客户编辑只处理辅助线位置的晶界)
- if (this.guideClass != null && this.comboBox1 != null && this.comboBox1.SelectedItem != null)
- {
- boundaryEditingDialog.GuideClass = this.guideClass;
- boundaryEditingDialog.SelectedItem = this.comboBox1.SelectedItem;
- }
- if (boundaryEditingDialog.ShowDialog() == DialogResult.OK)
- {
- this.documentWorkspace.PhaseModels[0].mat = boundaryEditingDialog.PhaseMat.Clone();
- OnBinaryImplFinishAction();
- }
- }
- /// <summary>
- /// 显示原图勾选改变事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcOriginCheckedChanged(object sender, EventArgs e)
- {
- if (bc == null && bmc == null)
- return;
- int BinaryCheckFlag = 0;
- if (bmc != null ? bmc.OriginChecked : bc.OriginChecked)
- BinaryCheckFlag += 1;
- if (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked)
- BinaryCheckFlag += 2;
- this.binaryExtractionModel.BinaryCheckFlag = BinaryCheckFlag;
- }
- /// <summary>
- /// 二值化勾选改变事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcBinaryCheckedChanged(object sender, EventArgs e)
- {
- if (bc == null && bmc == null)
- return;
- int BinaryCheckFlag = 0;
- if (bmc != null ? bmc.OriginChecked : bc.OriginChecked)
- BinaryCheckFlag += 1;
- if (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked)
- BinaryCheckFlag += 2;
- this.binaryExtractionModel.BinaryCheckFlag = BinaryCheckFlag;
- if ((bmc != null ? bmc.BinaryChecked : bc.BinaryChecked) && !(bmc != null ? bmc.OriginChecked : bc.OriginChecked))
- {
- this.documentWorkspace.PhaseModels[0].choise = true;
- }
- else
- {
- this.documentWorkspace.PhaseModels[0].choise = false;
- }
- if (toApplyBinary)
- this.applyButtonImpl();
- else
- OnBinaryImplFinishAction();
- toApplyBinary = true;
- if (this.listView1.FocusedItem == null || !(bmc != null ? bmc.BinaryChecked : bc.BinaryChecked))
- this.documentWorkspace.Refresh();
- }
- /// <summary>
- /// 自动阈值
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void bcAutoThresClickAction(object sender, EventArgs e)
- {
- if (bc == null && bmc == null)
- return;
- Bitmap bitmap = null;
- if (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0)
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- if (bitmap != null)
- {
- //先计算阈值
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat gray = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
- double otsu = Cv2.Threshold(gray, gray, 0, 255, ThresholdTypes.Triangle/*.Otsu*/);
- if (otsu <= 10 || otsu >= 245)
- {
- otsu = Cv2.Threshold(mat.CvtColor(ColorConversionCodes.BGR2GRAY), gray, 0, 255, ThresholdTypes.Otsu);//.Triangle
- }
- //如果当前是两个区间,则需要重新计算一次
- if (this.ColorInterval == 2)
- {
- if (bmc != null)
- bmc.OnInverseClickAction();
- else
- bc.OnInverseClickAction();
- this.ColorInterval = (bmc != null ? bmc.getInverseStyle() : bc.getInverseStyle());
- }
- else
- {
- if (bmc != null)
- bmc.setInverseStyle(1);
- else
- bc.setInverseStyle(1);
- }
- //给控件赋值
- if (bmc != null)
- bmc.scope1Start = 0;
- else
- bc.scope1Start = 0;
- if (bmc != null)
- bmc.scope1End = otsu;
- else
- bc.scope1End = otsu;
- //处理直方图
- if (bmc != null)
- bmc.UpdateVerticalBarWithOneScope(0, Convert.ToInt32(bmc.scope1End));
- else
- bc.UpdateVerticalBarWithOneScope(0, Convert.ToInt32(bc.scope1End));
- mat.Dispose();
- GC.Collect();
- this.bcApplyButtonImplAction(sender, e);
- }
- else
- {
- MessageBox.Show(PdnResources.GetString("Menu.Pleaseselectapicturefirst.text"));
- }
- }
- /// <summary>
- /// 执行读取参数的事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcBinaryGetParamAction(object sender, EventArgs e)
- {
- if (bc == null && bmc == null)
- return;
- this.binaryExtractionModel.ColorInterval = (bmc != null ? bmc.getInverseStyle() : bc.getInverseStyle());//###
- this.binaryExtractionModel.BinaryStyle = (bmc != null ? bmc.BinaryStyle : bc.BinaryStyle);
- this.binaryExtractionModel.ColorOneStart = (int)(bmc != null ? bmc.scope1Start : bc.scope1Start);
- this.binaryExtractionModel.ColorOneEnd = (int)(bmc != null ? bmc.scope1End : bc.scope1End);
- this.binaryExtractionModel.ColorTwoStart = (int)(bmc != null ? bmc.scope2Start : bc.scope2Start);
- this.binaryExtractionModel.ColorTwoEnd = (int)(bmc != null ? bmc.scope2End : bc.scope2End);
- this.binaryExtractionModel.ColorThreeStart = (int)(bmc != null ? bmc.scope3Start : bc.scope3Start);
- this.binaryExtractionModel.ColorThreeEnd = (int)(bmc != null ? bmc.scope3End : bc.scope3End);
- this.initParamsToAction();
- }
- /// <summary>
- /// 获取相的工作结构
- /// </summary>
- /// <param name="index">指明获取第几个相的工作结构</param>
- /// <returns></returns>
- public List<PhaseModel> getPhaseModels(int index)
- {
- return this.documentItems[index].phaseModels;
- }
- /// <summary>
- /// ListView图片选择改变事件
- /// </summary>
- /// <param name="bitmap">选择改变后的图片</param>
- public void listView1_SelectedIndexChanged(Bitmap bitmap, string imagesKey = null)
- {
- Document document = Document.FromImage(bitmap);
- this.documentWorkspace.Document = document;
- this.documentWorkspace.Visible = true;
- this.documentWorkspace.GraphicsList = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].GraphicsList;
- this.documentWorkspace.PhaseModels = new List<PhaseModel>();
- this.documentWorkspace.PhaseModels.AddRange(this.getPhaseModels(this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index));
- LunkMat = null;
- if (imageType != 4)
- {
- this.applyButtonImpl();
- }
- if (imagesKey != null && binaryModelFlag.ContainsKey(imagesKey)/*用于更新图片二值化效果*/)
- {
- this.documentWorkspace.PhaseModels[0].choise = (this.binaryExtractionModel.BinaryCheckFlag == 2);// (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked);
- binaryModelFlag[imagesKey] = false;
- if (bmc != null)
- bmc.BinaryChecked = this.documentWorkspace.PhaseModels[0].choise || (this.binaryExtractionModel.BinaryCheckFlag > 1);
- else
- bc.BinaryChecked = this.documentWorkspace.PhaseModels[0].choise || (this.binaryExtractionModel.BinaryCheckFlag > 1);
- }
- else if ((bc != null || bmc != null) && !this.documentWorkspace.PhaseModels[0].choise
- && (this.binaryExtractionModel.BinaryCheckFlag <= 1))
- if (bmc != null)
- bmc.BinaryChecked = false;
- else
- bc.BinaryChecked = false;
- if (imagesKey != null)
- {
- if (this.binaryExtractionModel.BinaryCheckFlag % 2 == 1)
- {
- if (bmc != null)
- bmc.OriginChecked = true;
- else
- bc.OriginChecked = true;
- }
- else
- {
- if (bmc != null)
- bmc.OriginChecked = false;
- else
- bc.OriginChecked = false;
- }
- }
- //显示直方图
- if (bc != null || bmc != null)
- if (bmc != null)
- bmc.CreateHistogram(bitmap, true, 339, 130, 0);
- else
- bc.CreateHistogram(bitmap, true, 339, 130, 0);
- this.RefreshHistogramControl1Values();
- }
- /// <summary>
- /// 构造相的工作结构
- /// </summary>
- /// <param name="phaseNames">相的命名,如果只有二值则只传PdnResources.GetString("Menu.BinaryAction.BinaryExtraction.Text")即可,没有特殊情况命名第一个相为PdnResources.GetString("Menu.BinaryAction.BinaryExtraction.Text")</param>
- /// <param name="bmc"></param>
- /// <param name="appWorkspace"></param>
- /// <param name="documentWorkspace"></param>
- public void createDocumentItemsSmaller(string[] phaseNames, CustomControl.BinaryControlSmaller bmc, AppWorkspace appWorkspace
- , DocumentWorkspaceWindow documentWorkspace, ListView listView1)
- {
- this.bmc = bmc;
- this.appWorkspace = appWorkspace;
- this.documentWorkspace = documentWorkspace;
- this.listView1 = listView1;
- this.initParams();
- for (int i = 0; i < phaseNames.Length; i++)
- {
- PhaseModel model = new PhaseModel();
- model.choise = true;
- model.mat = null;
- model.color = (i == 0 && bmc != null) ? bmc.BinaryBackColor.ToArgb() : Color.Green.ToArgb();//###
- model.position = documentWorkspace.PhaseModels.Count + 1;
- model.name = phaseNames[i];
- documentWorkspace.PhaseModels.Add(model);
- }
- this.documentItems = new Dictionary<int, DocumentItem>();
- // 构造工作结构
- for (int i = 0; i < appWorkspace.DocumentWorkspaces.Length; i++)
- {
- Bitmap bitmap = appWorkspace.DocumentWorkspaces[i].CompositionSurface.CreateAliasedBitmap();
- GraphicsList graphicsList = new GraphicsList();
- for (int j = 0; j < appWorkspace.DocumentWorkspaces[i].GraphicsList.Count; j++)
- {
- graphicsList.Add(appWorkspace.DocumentWorkspaces[i].GraphicsList[j]);
- }
- List<PhaseModel> phaseModels = new List<PhaseModel>();
- for (int j = 0; j < phaseNames.Length; j++)
- {
- //二值化相关
- if (j == 0)
- {
- PhaseModel analysisModel = appWorkspace.DocumentWorkspaces[i].AnalysisPhaseModel;
- if (analysisModel == null)
- {
- PhaseModel model = new PhaseModel();
- model.choise = true;
- model.mat = null;
- model.color = bmc != null ? bmc.BinaryBackColor.ToArgb() : Color.Green.ToArgb();
- model.position = phaseModels.Count + 1;
- model.name = phaseNames[j];
- phaseModels.Add(model);
- }
- else
- phaseModels.Add(analysisModel);
- }
- else
- {
- PhaseModel model = new PhaseModel();
- model.choise = true;
- model.mat = null;
- model.color = Color.Green/*panel2.BackColor*/.ToArgb();//###
- model.position = phaseModels.Count + 1;
- model.name = phaseNames[j];
- phaseModels.Add(model);
- }
- }
- this.documentItems.Add(i, new DocumentItem(bitmap, graphicsList, phaseModels));
- }
- //
- //调色板
- //
- this.colorsForm1 = new ColorsForm();
- this.colorsForm1.StartPosition = FormStartPosition.CenterScreen;
- this.colorsForm1.setSaveBtn_Click(new System.EventHandler(this.colorsForm1Changed));
- this.InitParameterToControl();//###
- if (this.binaryExtractionModel != null)
- this.applyButtonImpl();
- this.InitBinaryControlEvent();
- }
- /// <summary>
- /// 无视场执行运算
- /// </summary>
- public OpenCvSharp.Mat PerformProcess(OpenCvSharp.Mat src) { return action.PerformProcess(src); }
- /// <summary>
- /// 无视场执行运算
- /// </summary>
- public OpenCvSharp.Mat PerformProcess(OpenCvSharp.Mat src, Base.Functionodel.PhaseModel phaseModel, System.Drawing.Point point) { return action.PerformProcess(src, phaseModel, point); }
- /// <summary>
- /// 无视场执行运算
- /// </summary>
- public OpenCvSharp.Mat PerformProcessGetdata(OpenCvSharp.Mat src, out List<List<int>> data) { return action.PerformProcessGetdata(src, out data); }
- /// 无视场执行运算
- /// </summary>
- public OpenCvSharp.Mat PerformProcessGetdata(OpenCvSharp.Mat src, OpenCvSharp.Mat source, out List<List<int>> data) { return action.PerformProcessGetdata(src, source, out data); }
- /// <summary>
- /// 多视场执行运算
- /// </summary>
- /// <param name="src">视场mat</param>
- /// <param name="mat">原图mat</param>
- /// <returns></returns>
- public OpenCvSharp.Mat PerformProcess(OpenCvSharp.Mat src, OpenCvSharp.Mat mat) { return action.PerformProcess(src, mat); }
- public int ColorInterval
- {
- get
- {
- return this.binaryExtractionModel.ColorInterval;
- }
- set
- {
- this.binaryExtractionModel.ColorInterval = value;
- }
- }
- private void colorsForm1Changed(object sender, EventArgs e)
- {
- Color color = this.colorsForm1.UserPrimaryColor.ToColor();
- this.SetBinaryBackColor(color);//改变参数配置的相颜色
- this.colorsForm1.Close();
- }
- /// <summary>
- /// 把参数的值设置到控件上
- /// </summary>
- public void InitParameterToControl()
- {
- if (this.binaryExtractionModel != null)
- {
- if (bc != null || bmc != null)
- {
- if (this.binaryExtractionModel.BinaryCheckFlag > 1)
- {
- if (bmc != null)
- bmc.BinaryChecked = true;
- else
- bc.BinaryChecked = true;
- }
- if (this.binaryExtractionModel.BinaryCheckFlag % 2 == 1)
- {
- if (bmc != null)
- bmc.OriginChecked = true;
- else
- bc.OriginChecked = true;
- }
- if (imageType == 2)
- {
- return;
- }
- //阈值相关
- //1个颜色区间还是2个
- if (bmc != null)
- bmc.setInverseStyle((this.binaryExtractionModel.ColorInterval == 1) ? 1 : 2);
- else
- bc.setInverseStyle((this.binaryExtractionModel.ColorInterval == 1) ? 1 : 2);
- //删除事件
- if (bmc != null)
- bmc.DeleteEventHandler();
- else
- bc.DeleteEventHandler();
- if (imageType == 2)
- {
- return;
- }
- if (bmc != null)
- bmc.scope1End = this.binaryExtractionModel.ColorOneEnd;
- else
- bc.scope1End = this.binaryExtractionModel.ColorOneEnd;
- if (bmc != null)
- bmc.scope1Start = this.binaryExtractionModel.ColorOneStart;
- else
- bc.scope1Start = this.binaryExtractionModel.ColorOneStart;
- if (bmc != null)
- bmc.scope2End = this.binaryExtractionModel.ColorTwoEnd;
- else
- bc.scope2End = this.binaryExtractionModel.ColorTwoEnd;
- if (bmc != null)
- bmc.scope2Start = this.binaryExtractionModel.ColorTwoStart;
- else
- bc.scope2Start = this.binaryExtractionModel.ColorTwoStart;
- if (bmc != null)
- bmc.scope3End = this.binaryExtractionModel.ColorThreeEnd;
- else
- bc.scope3End = this.binaryExtractionModel.ColorThreeEnd;
- if (bmc != null)
- bmc.scope3Start = this.binaryExtractionModel.ColorThreeStart;
- else
- bc.scope3Start = this.binaryExtractionModel.ColorThreeStart;
- if (bmc != null)
- bmc.BinaryStyle = this.binaryExtractionModel.BinaryStyle;
- else
- bc.BinaryStyle = this.binaryExtractionModel.BinaryStyle;
- if (bmc != null)
- bmc.BinaryBackColor = Color.FromArgb(this.binaryExtractionModel.PhaseColor);
- else
- bc.BinaryBackColor = Color.FromArgb(this.binaryExtractionModel.PhaseColor);
- //添加事件
- if (bmc != null)
- bmc.AddEventHandler();
- else
- bc.AddEventHandler();
- if (bmc != null)
- bmc.InitParameterToControl();
- else
- bc.InitParameterToControl();
- }
- }
- }
- /// <summary>
- /// 更新显示直方图的数据
- /// </summary>
- public void RefreshHistogramControl1Values()
- {
- ////显示直方图
- //if (bc != null || bmc != null)
- // if (bmc != null)
- // bmc.CreateHistogram(bitmap, true, 339, 130, 0);
- // else
- // bc.CreateHistogram(bitmap, true, 339, 130, 0);
- if (bmc != null)
- bmc.InitParameterToControl(this.binaryExtractionModel.ColorInterval);
- else if (bc != null)
- bc.InitParameterToControl(this.binaryExtractionModel.ColorInterval);
- }
- public void SetBinaryBackColor(Color color)
- {
- if (bmc != null)
- bmc.BinaryBackColor = color;//设置panel背景
- else
- bc.BinaryBackColor = color;//设置panel背景
- this.binaryExtractionModel.PhaseColor = color.ToArgb();
- //###
- foreach (Args args in action.Lists)
- {
- if (args.Key == "phaseColor")
- {
- args.Value = color.ToArgb();//this.binaryExtractionModel.PhaseColor
- break;
- }
- }
- this.applyButtonImpl();
- }
- /// <summary>
- /// 保证二值化颜色赋值到action
- /// </summary>
- public void loadParams()
- {
- if (bc == null && bmc == null)
- return;
- foreach (Args args in action.Lists)
- {
- switch (args.Key)
- {
- case "scope1"://不反选时候的范围
- if (bmc != null)
- bmc.ScopeValue1ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- else
- bc.ScopeValue1ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- break;
- case "scope2"://反选时候的范围1
- if (bmc != null)
- bmc.ScopeValue2ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- else
- bc.ScopeValue2ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- break;
- case "scope3"://反选时候的范围2
- if (bmc != null)
- bmc.ScopeValue3ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- else
- bc.ScopeValue3ChangedAction += new EventHandler(((DecimalScope)args).numberScope_ValueChanged);
- break;
- case "phaseColor":
- args.Value = this.binaryExtractionModel.PhaseColor;
- break;
- default:
- break;
- }
- }
- }
- /// <summary>
- /// 执行二值方法的事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void bcApplyButtonImplAction(object sender, EventArgs e)
- {
- this.applyButtonImpl(/*bitmap*/);
- }
- private bool cornerHarris_demo()
- {
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- string newbitmap = subPath + "\\mask.jpg";
- Bitmap bmOld = new Bitmap(newbitmap);
- int iwidth = bmOld.Width;
- int iHeight = bmOld.Height;
- Bitmap newBmp = new Bitmap(bmOld);
- Bitmap bitmap1 = newBmp.Clone(new Rectangle(0, 0, iwidth, iHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
- bitDJ = bitmap1;
- Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap1);
- Mat gray = new Mat();
- Cv2.CvtColor(src, gray, ColorConversionCodes.BGRA2GRAY);
- using (new Window("ss", WindowMode.Normal, gray))
- {
- Cv2.WaitKey(0);
- }
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(gray, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- for (int h = 0; h < contours.Length; h++)
- {
- if (contours[h].Length < 20)
- {
- continue;
- }
- Mat src_gray = Mat.Zeros(src.Size(), MatType.CV_8UC1);
- src_gray.DrawContours(contours, h, new Scalar(255), -1);
- //src_gray.Resize(new OpenCvSharp.Size(src_gray.Width * 3, src_gray.Height * 3));
- Mat dst = src_gray.Clone();
- using (new Window("s1", WindowMode.Normal, dst))
- {
- Cv2.WaitKey(0);
- }
- // Cv2.MedianBlur(src_gray, src_gray, 9);
- Point2f[] cornersPoint = Cv2.GoodFeaturesToTrack(src_gray, 100, 0.01, 30, new Mat(), 3, false, 0.04);
- foreach (var item in cornersPoint)
- {
- Cv2.Circle(dst, Convert.ToInt16(item.X), Convert.ToInt16(item.Y), 10, Scalar.White, 2);
- }
- using (new Window("ss", WindowMode.Normal, dst))
- {
- Cv2.WaitKey(0);
- }
- }
- return false;
- }
- ///// <summary>
- ///// 参数改变时,重新处理图像
- ///// </summary>
- /// <param name="imagesKey">不是当前显示图片的需要传值</param>
- /// <param name="analysisPicture">不是当前显示图片的需要传值</param>
- /// <param name="bitmap">不带视场处理的需要传值</param>
- /// <param name="imageType">模块编号:1开裂球,2单晶,3二次球与单晶,4开裂球</param>
- public void applyButtonImpl(string imagesKey = null, int analysisPicture = -1, Bitmap bitmap = null)
- {
- List<List<int>> data = new List<List<int>>() { };
- Mat newMat = new Mat();
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- switch (imageType)
- {
- case 2:
- #region 单晶
- if (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0)
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- //cornerHarris_demo();
- //判断是否存在视场,如果存在视场,则把视场提取出来,进行处理//可能会带视场//########################
- DocumentView documentWorkspace = this.documentWorkspace;
- // string name = this.listView1.FocusedItem.Name.Split('.')[0];
- string name = "inputImg";
-
- if (analysisPicture == -1)
- {
- action.Lists.Add(new Args() { Key = "imageType", Value = 12 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "pointsize", Value = pointsize });
- action.Lists.Add(new Args() { Key = "borderBottom", Value = borderBottom });
- action.Lists.Add(new Args() { Key = "Micron", Value = unitLength });
- action.Lists.Add(new Args() { Key = "border", Value = border });
- action.Lists.Add(new Args() { Key = "HW", Value = HW });
- action.Lists.Add(new Args() { Key = "AreaRatio", Value = AreaRatio });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = null });
- action.Lists.Add(new Args() { Key = "AddPontins", Value = null });
- action.Lists.Add(new Args() { Key = "Contour", Value = null });
- action.Lists.Add(new Args() { Key = "isDis", Value = isDis });
- action.Lists.Add(new Args() { Key = "isJu", Value = isJu });
- System.Threading.ThreadStart copyThreadProcCrystal =
- delegate ()
- {
- try
- {
- //检查是否存在文件夹
- //string subPath = @"C:\MetisTemp";
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- if (false == System.IO.Directory.Exists(subPath))
- {
- //创建pic文件夹
- System.IO.Directory.CreateDirectory(subPath);
- }
- else
- {
- DirectoryInfo di = new DirectoryInfo(subPath);
- FileSystemInfo[] fileinfo = di.GetFileSystemInfos();
- try
- {
- foreach (FileSystemInfo item in fileinfo)
- {
- //if(item.Name!= "mask.jpg")
- item.Delete();
- // File.Delete(item.FullName);
- }
- }
- catch (Exception e)
- {
- }
- }
- string savepath = subPath + "\\" + name + ".png";
- string isCpu = System.Configuration.ConfigurationManager.AppSettings["CpuORGpu"];
- bitmap.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);
- //1金相/2析出物 0是cpu,1是GPU 尺寸0是自动算
- string sArguments = subPath + " " + name + ".png 2 " + isCpu + " 0";
- //string sArguments = "-filepath "+subPath + "\\" + name + ".png --useGpu " + isCpu + " --diameter 30,20";
- System.Diagnostics.Process p = new System.Diagnostics.Process();
- //p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\crystal\\crystal.exe";
- p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\educt\\educt.exe";
- //p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\granule_engine_3G\\granule_engine.exe";
- p.StartInfo.Arguments = sArguments;//python命令的参数
- p.StartInfo.UseShellExecute = false;
- p.StartInfo.RedirectStandardInput = true;
- p.StartInfo.RedirectStandardOutput = true;
- p.StartInfo.RedirectStandardError = true;
- p.StartInfo.CreateNoWindow = true;
- string strOutput = null;
- p.Start();
- strOutput = p.StandardOutput.ReadToEnd();
- p.WaitForExit();
- p.Close();
- string newbitmap = subPath + "\\mask.jpg";
- //Bitmap bmOld = new Bitmap(newbitmap);
- //int iwidth = bmOld.Width;
- //int iHeight = bmOld.Height;
- //Bitmap newBmp = new Bitmap(bmOld);
- //Bitmap bitmap1 = newBmp.Clone(new Rectangle(0, 0, iwidth, iHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
- //bitDJ = (Bitmap)bitmap1.Clone();
- // newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap1), out data);
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- if (string.IsNullOrEmpty(tipString))
- {
- procClass.StartProgressAction(/*currentForm*/parentSinglCrystal, itemCount, copyThreadProcCrystal, progressEvents, null);
- }
- else
- {
- procClass.StartProgressAction(/*currentForm*/parentSinglCrystal, itemCount, copyThreadProcCrystal, progressEvents, tipString);
- }
- }
- }
- #endregion
- break;
- case 4:
- #region 开裂球
- if (bc == null && bmc == null)
- return;
- //long start = Cv2.GetTickCount();
- if (bitmap != null ||
- (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0) && (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked))
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 4 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- string name = this.listView1.FocusedItem.Name.Split('.')[0];
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- #region 人工只能找轮廓
- //检查是否存在文件夹
- //string subPath = @"C:\MetisTemp";
- //string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- //if (false == System.IO.Directory.Exists(subPath))
- //{
- // //创建pic文件夹
- // System.IO.Directory.CreateDirectory(subPath);
- //}
- //else
- //{
- // DirectoryInfo di = new DirectoryInfo(subPath);
- // FileSystemInfo[] fileinfo = di.GetFileSystemInfos();
- // foreach (FileSystemInfo item in fileinfo)
- // {
- // item.Delete();
- // // File.Delete(item.FullName);
- // }
- //}
- //string savepath = subPath + "\\" + name + ".png";
- //bitmap.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);
- ////1金相/2析出物 0是cpu1是GPU 尺寸0是自动算
- //string sArguments = subPath + " " + name + ".png 1 0 0";
- //System.Diagnostics.Process p = new System.Diagnostics.Process();
- ////p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\crystal\\crystal.exe";
- //p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\educt\\educt.exe";
- //p.StartInfo.Arguments = sArguments;//python命令的参数
- //p.StartInfo.UseShellExecute = false;
- //p.StartInfo.RedirectStandardInput = true;
- //p.StartInfo.RedirectStandardOutput = true;
- //p.StartInfo.RedirectStandardError = true;
- //p.StartInfo.CreateNoWindow = true;
- //string strOutput = null;
- //p.Start();
- //strOutput = p.StandardOutput.ReadToEnd();
- //p.WaitForExit();
- //p.Close();
- //string newbitmap = subPath + "\\mask.jpg";
- //Bitmap bmOld = new Bitmap(newbitmap);
- //int iwidth = bmOld.Width;
- //int iHeight = bmOld.Height;
- //Bitmap newBmp = new Bitmap(bmOld);
- //Bitmap bitmap1 = newBmp.Clone(new Rectangle(0, 0, iwidth, iHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
- //bitDJ = bitmap1;
- //Mat pyston = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap1);
- #endregion
- #region 分水岭找轮廓
- newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- PhaseModel model = new PhaseModel();
- model.color = -14607873;
- model.mat = new OpenCvSharp.Mat();
- newMat.CopyTo(model.mat);
- newMat = this.PerformProcess(newMat, model, new System.Drawing.Point());
- LunkMat = newMat.Clone();
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 14 });
- data.Clear();
- #endregion
- newMat = this.PerformProcessGetdata(LunkMat, OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parent, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- #endregion
- break;
- case 3:
- #region 二次球与单晶
- if (bc == null && bmc == null)
- return;
- //long start = Cv2.GetTickCount();
- if (bitmap != null ||
- (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0) && (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked))
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "CircleCount", Value = 0 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 3 });
- newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- #endregion
- break;
- case 1:
- #region 截面孔隙
- if (bc == null && bmc == null)
- return;
- //long start = Cv2.GetTickCount();
- if (bitmap != null ||
- (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0) && (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked))
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- //判断是否存在视场,如果存在视场,则把视场提取出来,进行处理//可能会带视场//########################
- DocumentView documentWorkspace = this.documentWorkspace;
- //GetParameter2();
- if (analysisPicture == -1)
- {
- if (LunkMat != null && LunkMat.Rows > 10)
- {
- }
- else
- {
- Mat maptomat = getimage(bitmap);
- LunkMat = maptomat.Clone();
- List<Scalar> colorList = new List<Scalar>() { new Scalar(0, 0, 255, 255), new Scalar(0, 255, 0, 255), new Scalar(0, 255, 255, 255), new Scalar(128, 0, 128, 255), new Scalar(230, 216, 173, 255) };
- double dist = 0;
- double maxdist = 0;
- //InputArray contoursAll = InputArray.Create(maxContour);
- //List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- //OutputArray hull = OutputArray.Create(outArr);
- //Cv2.ConvexHull(contoursAll, hull, true);
- //using (new Window("InputImage", WindowMode.Normal, LunkMat))
- //{
- // Cv2.WaitKey(0);
- //}
- if (CilCount > 1)
- {
- for (int i = 0; i < maptomat.Cols; i = i + 50)
- {
- for (int j = 0; j < maptomat.Rows; j = j + 50)
- {
- OpenCvSharp.Point point = new OpenCvSharp.Point(i, j);
- dist = Cv2.PointPolygonTest(maxContour, point, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- center = point;
- }
- }
- }
- R = Convert.ToInt32(maxdist);
- r = Convert.ToInt32(maxdist) / CilCount;
- }
- SetCenter = center;
- //r = r - 10;
- action.Lists.Add(new Args() { Key = "CircleCount", Value = CilCount });
- action.Lists.Add(new Args() { Key = "CircleR", Value = r });
- action.Lists.Add(new Args() { Key = "Center", Value = center });
- action.Lists.Add(new Args() { Key = "imageType", Value = 1 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = null });
- action.Lists.Add(new Args() { Key = "AddPontins", Value = null });
- }
- newMat = this.PerformProcessGetdata(LunkMat, out data);
- List<int> CircleDate = data[0];
- CircleDate[CircleDate.Count - 1] = Convert.ToInt32(maxArea);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- }
- if (analysisPicture == -1)
- OnBinaryImplFinishAction();
- #endregion
- break;
- case 5:
- #region 隔膜
- if (bc == null && bmc == null)
- return;
- //long start = Cv2.GetTickCount();
- if (bitmap != null ||
- (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0) && (bmc != null ? bmc.BinaryChecked : bc.BinaryChecked))
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- // double d = GetRuler();
- //判断是否存在视场,如果存在视场,则把视场提取出来,进行处理//可能会带视场//########################
- DocumentView documentWorkspace = this.documentWorkspace;
- //GetParameter2();
- if (analysisPicture == -1)
- {
- action.Lists.Add(new Args() { Key = "CircleCount", Value = 0 });
- action.Lists.Add(new Args() { Key = "imageType", Value = 5 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- }
- if (analysisPicture == -1)
- OnBinaryImplFinishAction();
- #endregion
- break;
- case 6:
- #region 前驱截面一次颗粒
- if (bc == null && bmc == null)
- return;
- if (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0)
- {
- bool processWholeMat11 = (bitmap != null);
- if (bitmap == null)
- /*Bitmap */
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- //判断是否存在视场,如果存在视场,则把视场提取出来,进行处理//可能会带视场//########################
- DocumentView documentWorkspace = this.documentWorkspace;
- string name = "inputImg";
- double d = documentWorkspace.GetRuler(MeasurementUnit.Micron);
- if (analysisPicture == -1)
- {
- action.Lists.Add(new Args() { Key = "imageType", Value = 12 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "pointsize", Value = pointsize });
- action.Lists.Add(new Args() { Key = "Micron", Value = d });
- action.Lists.Add(new Args() { Key = "border", Value = border });
- action.Lists.Add(new Args() { Key = "HW", Value = HW });
- action.Lists.Add(new Args() { Key = "AreaRatio", Value = AreaRatio });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = null });
- action.Lists.Add(new Args() { Key = "AddPontins", Value = null });
- action.Lists.Add(new Args() { Key = "Contour", Value = null });
- System.Threading.ThreadStart copyThreadProcCrystal =
- delegate ()
- {
- try
- {
- //检查是否存在文件夹
- //string subPath = @"C:\MetisTemp";
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- if (false == System.IO.Directory.Exists(subPath))
- {
- //创建pic文件夹
- System.IO.Directory.CreateDirectory(subPath);
- }
- else
- {
- DirectoryInfo di = new DirectoryInfo(subPath);
- FileSystemInfo[] fileinfo = di.GetFileSystemInfos();
- foreach (FileSystemInfo item in fileinfo)
- {
- item.Delete();
- // File.Delete(item.FullName);
- }
- }
- string savepath = subPath + "\\" + name + ".png";
- string isCpu = System.Configuration.ConfigurationManager.AppSettings["CpuORGpu"];
- bitmap.Save(savepath, System.Drawing.Imaging.ImageFormat.Png);
- //1金相/2析出物 0是cpu,1是GPU 尺寸0是自动算
- string sArguments = subPath + " " + name + ".png 1 " + isCpu + " 0";
- System.Diagnostics.Process p = new System.Diagnostics.Process();
- //p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\crystal\\crystal.exe";
- p.StartInfo.FileName = System.Environment.CurrentDirectory + "\\educt\\educt.exe";
- p.StartInfo.Arguments = sArguments;//python命令的参数
- p.StartInfo.UseShellExecute = false;
- p.StartInfo.RedirectStandardInput = true;
- p.StartInfo.RedirectStandardOutput = true;
- p.StartInfo.RedirectStandardError = true;
- p.StartInfo.CreateNoWindow = true;
- string strOutput = null;
- p.Start();
- strOutput = p.StandardOutput.ReadToEnd();
- p.WaitForExit();
- p.Close();
- string newbitmap = subPath + "\\mask.jpg";
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(parentPrimary, itemCount, copyThreadProcCrystal, progressEvents, null);
- }
- }
- #endregion
- break;
- }
- }
- /// <summary>
- /// 同心圆绘制返回数据
- /// </summary>
- /// <returns></returns>
- public List<List<int>> getCircleDate(int count)
- {
- if (bmc != null) { bmc.isedit = true; }
- if (bc != null) { bc.isedit = true; }
- CilCount = count;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- // Mat maptomat = getimage(bitmap);
- if (LunkMat != null && LunkMat.Rows > 10)
- {
- }
- else
- {
- Mat maptomat = getimage(bitmap);
- LunkMat = maptomat.Clone();
- }
- List<Scalar> colorList = new List<Scalar>() { new Scalar(0, 0, 255, 255), new Scalar(0, 255, 0, 255), new Scalar(0, 255, 255, 255), new Scalar(128, 0, 128, 255), new Scalar(230, 216, 173, 255) };
- double dist = 0;
- double maxdist = 0;
-
- if (SetCenter != null && SetCenter.X > 0)
- {
- center = SetCenter;
- if (count > 0)
- r = R / count;
- else
- r = R;
- }
- else
- {
- InputArray contoursAll = InputArray.Create(maxContour);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- for (int i = 0; i < LunkMat.Cols; i = i + 50)
- {
- for (int j = 0; j < LunkMat.Rows; j = j + 50)
- {
- OpenCvSharp.Point point = new OpenCvSharp.Point(i, j);
- dist = Cv2.PointPolygonTest(outArr.ToArray(), point, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- center = point;
- }
- }
- }
- R = Convert.ToInt32(maxdist);
- if (count > 0)
- r = Convert.ToInt32(maxdist) / count;
- else
- r = R;
- }
-
- action.Lists.Add(new Args() { Key = "CircleCount", Value = count });
- action.Lists.Add(new Args() { Key = "CircleR", Value = r });
- action.Lists.Add(new Args() { Key = "Center", Value = center });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- Mat newMat = this.PerformProcessGetdata(LunkMat, out data);
- if (data.Count > 0)
- {
- List<int> CircleDate = data[0];
- CircleDate[CircleDate.Count - 1] = Convert.ToInt32(maxArea);
- }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 手动同心圆绘制返回数据
- /// </summary>
- /// <returns></returns>
- public List<List<int>> getCircleDate(Dictionary<int, Color> ListRadiusColor)
- {
- if (bmc != null) { bmc.isedit = true; }
- if (bc != null) { bc.isedit = true; }
-
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- // Mat maptomat = getimage(bitmap);
- if (LunkMat != null && LunkMat.Rows > 10)
- {
- }
- else
- {
- Mat maptomat = getimage(bitmap);
- LunkMat = maptomat.Clone();
- }
- action.Lists.Add(new Args() { Key = "ListRadiusColor", Value = ListRadiusColor });
- action.Lists.Add(new Args() { Key = "Center", Value = center });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- Mat newMat = this.PerformProcessGetdata(LunkMat, out data);
- if (data.Count > 0)
- {
- List<int> CircleDate = data[0];
- CircleDate[CircleDate.Count - 1] = Convert.ToInt32(maxArea);
- }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 绘制轮廓
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuo(List<List<PointF>> pointFs, List<List<PointF>> KongPointFs, List<PointF> delPointFs)
- {
- if (this.listView1.Items.Count == 0)
- {
- return null;
- }
- lineList = pointFs;
- kongLineList = KongPointFs;
- delLineList = delPointFs;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat maptomat = getimage(bitmap);
- // Mat maptomat = getLineMat(bitmap);
- LunkMat = maptomat.Clone();
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = delPointFs });
- Mat newMat = this.PerformProcessGetdata(maptomat, out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- List<int> CircleDate = data[0];
- CircleDate[CircleDate.Count - 1] = Convert.ToInt32(maxArea);
- return data;
- }
- /// <summary>
- /// 重新绘制轮廓
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuoNew(List<List<PointF>> pointFs, List<List<PointF>> KongPointFs, List<PointF> delPointFs)
- {
- lineList = pointFs;
- kongLineList = KongPointFs;
- delLineList = delPointFs;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat maptomat = getLineMat(bitmap);
- // Mat maptomat = getLineMat(bitmap);
- LunkMat = maptomat.Clone();
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = delPointFs });
- Mat newMat = this.PerformProcessGetdata(maptomat, out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- List<int> CircleDate = data[0];
- CircleDate[CircleDate.Count - 1] = Convert.ToInt32(maxArea);
- return data;
- }
- /// <summary>
- /// 选择颗粒
- /// </summary>
- /// <returns></returns>
- public void DrwLunKuoSel(int index)
- {
- List<List<int>> data = new List<List<int>>() { };
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = index });
- Mat newMat = this.PerformProcessGetdata(LunkMat, out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- }
- /// <summary>
- /// 选择隔膜孔隙
- /// </summary>
- /// <returns></returns>
- public void MembranesSel(int index)
- {
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = index });
- Mat newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- }
- /// <summary>
- /// 绘制轮廓单晶
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuoDJ(List<List<PointF>> pointFs, List<List<PointF>> KongPointFs, List<PointF> delPointFs)
- {
- lineList = pointFs;
- kongLineList = KongPointFs;
- delLineList = delPointFs;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = delPointFs });
- Mat newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 绘制轮廓二次球均匀性
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuoBallAndCrystal(List<int> options, List<PointF> KongPointFs, List<PointF> delPointFs, List<List<PointF>> LKPointFs)
- {
- kailie_ball = KongPointFs;
- delLineList = delPointFs;
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- action.Lists.Add(new Args() { Key = "BlurSiaze", Value = options[0] });
- action.Lists.Add(new Args() { Key = "param2", Value = options[1] });
- action.Lists.Add(new Args() { Key = "minRadius", Value = options[2] });
- action.Lists.Add(new Args() { Key = "maxRadius", Value = options[3] });
- action.Lists.Add(new Args() { Key = "boundary", Value = options[4] });
- action.Lists.Add(new Args() { Key = "BallPointFs", Value = kailie_ball });
- action.Lists.Add(new Args() { Key = "CrystalPointFs", Value = delLineList });
- action.Lists.Add(new Args() { Key = "CrystalLunkuo", Value = LKPointFs });
- newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parentCrystal, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.PhaseModels[0].color = (bmc != null ? bmc.BinaryBackColor.ToArgb() : bc.BinaryBackColor.ToArgb());
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 初始化二值化相关的变量
- /// </summary>
- public void initParams()
- {
- string xmlFilePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\BinaryConfig\\Default_" + this.menuId + ".xml";
- bool createNewFile = !System.IO.File.Exists(xmlFilePath);
- if (createNewFile)
- xmlFilePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\BinaryExtraction\\Default.xml";
- this.binaryExtractionModel = XmlSerializeHelper.DESerializer<BinaryExtractionModel>(FileOperationHelper.ReadStringFromFile(xmlFilePath, FileMode.Open));
- if (createNewFile)
- this.binaryExtractionModel.BinaryCheckFlag = 0;
- if (imageType == 2)
- {
- //binaryExtractionModel.ColorOneEnd = 200;
- pointsize = Convert.ToDouble(binaryExtractionModel.ColorOneStart) / 100;
- border = binaryExtractionModel.ColorOneEnd / 100;
- HW = Convert.ToDouble(binaryExtractionModel.ColorTwoStart) / 100;
- AreaRatio = Convert.ToDouble(binaryExtractionModel.ColorTwoEnd) / 100;
- CheckState = binaryExtractionModel.ColorThreeStart;
- borderBottom = binaryExtractionModel.ColorThreeEnd / 100;
- numDecimals = Convert.ToInt32(binaryExtractionModel.DebrisAreaStart);
- }
- if (imageType == 4)
- {
- binaryExtractionModel.ColorOneEnd = 200;
- }
- this.initParamsToAction();
- }
- /// <summary>
- /// 把参数的值设置到action
- /// </summary>
- public void initParamsToAction()
- {
- foreach (Args args in action.Lists)
- {
- if (args.Key == "colorInterval")
- args.Value = this.binaryExtractionModel.ColorInterval;
- else if (args.Key == "binaryStyle")
- args.Value = this.binaryExtractionModel.BinaryStyle;
- else if (args.Key == "scope1")
- {
- ((List<double>)args.Value)[0] = (int)(this.binaryExtractionModel.ColorOneStart);
- ((List<double>)args.Value)[1] = (int)(this.binaryExtractionModel.ColorOneEnd);
- }
- else if (args.Key == "scope2")
- {
- ((List<double>)args.Value)[0] = (int)(this.binaryExtractionModel.ColorTwoStart);
- ((List<double>)args.Value)[1] = (int)(this.binaryExtractionModel.ColorTwoEnd);
- }
- else if (args.Key == "scope3")
- {
- ((List<double>)args.Value)[0] = (int)(this.binaryExtractionModel.ColorThreeStart);
- ((List<double>)args.Value)[1] = (int)(this.binaryExtractionModel.ColorThreeEnd);
- }
- else if (args.Key == "phaseColor")//#22092
- {
- args.Value = this.binaryExtractionModel.PhaseColor;
- }
- }
- }
- /// <summary>
- /// 保存变量
- /// </summary>
- public void saveParams(List<int> paramsList)
- {
- this.binaryExtractionModel.ColorOneStart = paramsList[0];
- this.binaryExtractionModel.ColorOneEnd = paramsList[1];
- this.binaryExtractionModel.ColorTwoStart = paramsList[2];
- this.binaryExtractionModel.ColorTwoEnd = paramsList[3];
- this.binaryExtractionModel.ColorThreeEnd = paramsList[4];
- this.binaryExtractionModel.ColorThreeStart = paramsList[6];
- this.binaryExtractionModel.DebrisAreaStart = paramsList[5];
- string xmlFilePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\BinaryConfig\\Default_" + this.menuId + ".xml";
- string userInfoXml = XmlSerializeHelper.XmlSerialize<BinaryExtractionModel>(this.binaryExtractionModel);
- FileOperationHelper.WriteStringToFile(userInfoXml, xmlFilePath, System.IO.FileMode.Create);
- }
- /// <summary>
- /// 保存二值化相关的变量
- /// </summary>
- public void saveParams()
- {
- string xmlFilePath = Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\BinaryConfig\\Default_" + this.menuId + ".xml";
- string userInfoXml = XmlSerializeHelper.XmlSerialize<BinaryExtractionModel>(this.binaryExtractionModel);
- FileOperationHelper.WriteStringToFile(userInfoXml, xmlFilePath, System.IO.FileMode.Create);
- }
- #region 内部类
- internal class LocalListViewItem
- {
- public DocumentWorkspace Value { get; }
- public string Display { get; }
- public LocalListViewItem(DocumentWorkspace Value, string Display)
- {
- this.Value = Value;
- this.Display = Display;
- }
- }
- internal class DocumentItem
- {
- public Bitmap bitmap;
- public GraphicsList graphicsList;
- public List<PhaseModel> phaseModels;
- public DocumentItem(Bitmap bitmap, GraphicsList graphicsList, List<PhaseModel> phaseModels)
- {
- this.bitmap = bitmap;
- this.graphicsList = graphicsList;
- this.phaseModels = phaseModels;
- }
- }
- #endregion
- #region 前驱截面
- private Mat getLineMat(Bitmap img)
- {
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- double dist = 0;
- double maxdist = 0;
- List<PointF> pointList = lineList[0];
- List<List<OpenCvSharp.Point>> list = new List<List<OpenCvSharp.Point>>();
- List<OpenCvSharp.Point> point = new List<OpenCvSharp.Point>();
- if (kongLineList.Count > 0)
- {
- List<List<OpenCvSharp.Point>> Allkonglist = new List<List<OpenCvSharp.Point>>() { };
- for (int i = 0; i < kongLineList.Count; i++)
- {
- List<OpenCvSharp.Point> konglist = new List<OpenCvSharp.Point>();
- for (int j = 0; j < kongLineList[i].Count; j++)
- {
- OpenCvSharp.Point po = new OpenCvSharp.Point() { X = (int)kongLineList[i][j].X, Y = (int)kongLineList[i][j].Y };
- konglist.Add(po);
- }
- Allkonglist.Add(konglist);
- }
- for (int kong = 0; kong < kongLineList.Count; kong++)
- {
- Cv2.DrawContours(mat, Allkonglist, kong, new Scalar(0, 0, 0, 255), Cv2.FILLED);
- }
- }
- for (int i = 0; i < pointList.Count(); i++)
- {
- point.Add(new OpenCvSharp.Point() { X = (int)pointList[i].X, Y = (int)pointList[i].Y });
- }
- list.Add(point);
- Mat mask = Mat.Zeros(mat.Size(), MatType.CV_8UC1);
- Cv2.DrawContours(mask, list, 0, new Scalar(255, 255, 255, 255), -1);
- maxContour = point.ToArray();
- InputArray contoursAll = InputArray.Create(maxContour);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- maxArea = Cv2.ContourArea(maxContour);
- Cv2.ConvexHull(contoursAll, hull, true);
- if (SetCenter != null && SetCenter.X > 0&& CilCount>0)
- {
- center = SetCenter;
- r = R / CilCount;
- }
- else
- {
- for (int i = 0; i < mat.Cols; i = i + 50)
- {
- for (int j = 0; j < mat.Rows; j = j + 50)
- {
- OpenCvSharp.Point point1 = new OpenCvSharp.Point(i, j);
- dist = Cv2.PointPolygonTest(outArr, point1, true);
- if (dist > maxdist)
- {
- maxdist = dist;
- center = point1;
- }
- }
- }
- R = Convert.ToInt32(maxdist);
- r = Convert.ToInt32(maxdist);
- }
- // r = r - 10;
- action.Lists.Add(new Args() { Key = "maxContour", Value = maxContour });
- action.Lists.Add(new Args() { Key = "CircleCount", Value = CilCount });
- action.Lists.Add(new Args() { Key = "CircleR", Value = r });
- action.Lists.Add(new Args() { Key = "Center", Value = center });
- action.Lists.Add(new Args() { Key = "imageType", Value = 1 });
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- Mat dst = new Mat();
- mat.CopyTo(dst, mask);
- return dst;
- }
- private Mat getimage(Bitmap img)
- {
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- Mat g_grayImage = new Mat();
- Mat g_dstImage = new Mat();
- Mat g_bwImage = new Mat();
- Mat mask = Mat.Zeros(mat.Size(), MatType.CV_8UC1);
- Mat dst = new Mat();
- if (lineList.Count > 0)
- {
- for (int line = 0; line < lineList.Count; line++)
- {
- List<PointF> pointList = lineList[line];
- for (int i = 0; i < pointList.Count - 1; i++)
- {
- Cv2.Line(mat, new OpenCvSharp.Point() { X = (int)pointList[i].X, Y = (int)pointList[i].Y }, new OpenCvSharp.Point() { X = (int)pointList[i + 1].X, Y = (int)pointList[i + 1].Y }, new Scalar(0, 0, 0), 20);
- }
- }
- }
- if (kongLineList.Count > 0)
- {
- List<List<OpenCvSharp.Point>> Allkonglist = new List<List<OpenCvSharp.Point>>() { };
- for (int i = 0; i < kongLineList.Count; i++)
- {
- List<OpenCvSharp.Point> konglist = new List<OpenCvSharp.Point>();
- for (int j = 0; j < kongLineList[i].Count; j++)
- {
- OpenCvSharp.Point point = new OpenCvSharp.Point() { X = (int)kongLineList[i][j].X, Y = (int)kongLineList[i][j].Y };
- konglist.Add(point);
- }
- Allkonglist.Add(konglist);
- }
- for (int kong = 0; kong < kongLineList.Count; kong++)
- {
- Cv2.DrawContours(mat, Allkonglist, kong, new Scalar(0, 0, 0, 255), Cv2.FILLED);
- }
- }
- //灰度图
- Cv2.CvtColor(mat, g_grayImage, ColorConversionCodes.BGR2GRAY);
- Cv2.Erode(g_grayImage, g_grayImage, null);
- Cv2.Erode(g_grayImage, g_grayImage, null);
- //算子
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5), new OpenCvSharp.Point(2, 2));
- //闭操作
- Cv2.MorphologyEx(g_grayImage, g_dstImage, MorphTypes.Close, kernel, new OpenCvSharp.Point(-1, -1));
- //平均阈值
- Scalar scalar = Cv2.Mean(g_dstImage);
- double val = scalar.Val0 + 11;
- //图像二值化
- Cv2.Threshold(g_dstImage, g_bwImage, val, 255, ThresholdTypes.Binary);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //轮廓
- Cv2.FindContours(g_bwImage, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- Mat view = mask.Clone();
- int maxcontourIdx = 0;
- maxArea = 0;
- for (int i = 0; i < contours.Length; i++)
- {
- double area = Cv2.ContourArea(contours[i]);
- if (area > maxArea)
- {
- maxArea = area;
- maxContour = contours[i];
- maxcontourIdx = i;
- }
- //Cv2.DrawContours(view, contours, i, new Scalar(255, 255, 255, 255), -1);
- }
-
- //Mat matret = new Mat(mat.Rows, mat.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- //Cv2.DrawContours(matret, contours, maxcontourIdx, new Scalar(255, 0, 255, 255), 2);
- InputArray contoursAll = InputArray.Create(contours[maxcontourIdx]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- List<OpenCvSharp.Point> hullpoint = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- Cv2.DrawContours(mask, new List<List<OpenCvSharp.Point>> { outArr }, 0, new Scalar(255, 255, 255, 255), -1);
- action.Lists.Add(new Args() { Key = "maxContour", Value = outArr.ToArray() });
- maxContour = outArr.ToArray();
- //using (new Window("ss",WindowMode.Normal, view))
- //{
- // Cv2.WaitKey(0);
- //}
- maxArea = Cv2.ContourArea(outArr);
- mat.CopyTo(dst, mask);
- //List<OpenCvSharp.Point> ret = expand_polygon(maxContour);
- //Cv2.DrawContours(dst, new List<List<OpenCvSharp.Point>> { ret }, 0, new Scalar(255, 255, 255, 255), -1);
- //Cv2.ImShow("ss", dst);
- return dst;
- }
- private List<OpenCvSharp.Point> expand_polygon(OpenCvSharp.Point[] pList)
- {
- List<OpenCvSharp.Point> points = new List<OpenCvSharp.Point>() { };
- List<Point2f> dpList = new List<Point2f>() { }, ndpList = new List<Point2f>() { };
- int count = pList.Count();
- for (int i = 0; i < count; i++)
- {
- int next = (i == (count - 1) ? 0 : (i + 1));
- dpList.Add(pList[next] - pList[i]);
- double unitLen = 1.0 / Math.Sqrt(dpList[i].DotProduct(dpList[i]));
- ndpList.Add(dpList[i] * unitLen);
- }
- // 3. compute Line
- float SAFELINE = -1.3f;//负数为内缩, 正数为外扩。 需要注意算法本身并没有检测内缩多少后折线会自相交,那不是本代码的示范意图
- for (int i = 0; i < count; i++)
- {
- int startIndex = (i == 0 ? (count - 1) : (i - 1));
- int endIndex = i;
- float sinTheta = (float)ndpList[startIndex].CrossProduct(ndpList[endIndex]);
- Point2f orientVector = ndpList[endIndex] - ndpList[startIndex];//i.e. PV2-V1P=PV2+PV1
- OpenCvSharp.Point temp_out;
- temp_out.X = Convert.ToInt32(pList[i].X + SAFELINE / sinTheta * orientVector.X);
- temp_out.Y = Convert.ToInt32(pList[i].Y + SAFELINE / sinTheta * orientVector.Y);
- points.Add(temp_out);
- }
- return points;
- }
- /// <summary>
- /// 自动阈值
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- public void bcDefault()
- {
- if (bc == null && bmc == null)
- return;
- Bitmap bitmap = null;
- if (listView1.FocusedItem != null || this.listView1.SelectedItems != null && this.listView1.SelectedItems.Count > 0)
- bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- if (bitmap != null)
- {
- //先计算阈值
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat gray = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
- double otsu = Cv2.Threshold(gray, gray, 0, 255, ThresholdTypes.Triangle/*.Otsu*/);
- if (otsu <= 10 || otsu >= 245)
- {
- otsu = Cv2.Threshold(mat.CvtColor(ColorConversionCodes.BGR2GRAY), gray, 0, 255, ThresholdTypes.Otsu);//.Triangle
- }
- //如果当前是两个区间,则需要重新计算一次
- if (this.ColorInterval == 2)
- {
- if (bmc != null)
- bmc.OnInverseClickAction();
- else
- bc.OnInverseClickAction();
- this.ColorInterval = (bmc != null ? bmc.getInverseStyle() : bc.getInverseStyle());
- }
- else
- {
- if (bmc != null)
- bmc.setInverseStyle(1);
- else
- bc.setInverseStyle(1);
- }
- // Scalar scalar = Cv2.Mean(mat);
- int val = 0;
- switch (imageType)
- {
- case 2:
- val = GetDefultValueForCrystal(mat);
- //给控件赋值
- if (bmc != null)
- bmc.scope1Start = val;
- else
- bc.scope1Start = val;
- if (bmc != null)
- bmc.scope1End = 200;
- else
- bc.scope1End = 200;
- break;
- case 3:
- val = GetDefultValueForCrystal(mat);
- //给控件赋值
- if (bmc != null)
- bmc.scope1Start = val;
- else
- bc.scope1Start = val;
- if (bmc != null)
- bmc.scope1End = 245;
- else
- bc.scope1End = 245;
- break;
- case 4:
- val = GetDefultValueForBall(mat);
- //给控件赋值
- if ((bmc != null && bmc.scope1Start == val) || (bc != null && bc.scope1Start == val))
- {
- val = val + 1;
- }
- if (bmc != null)
- bmc.scope1Start = val;
- else
- bc.scope1Start = val;
- if (bmc != null)
- bmc.scope1End = 200;
- else
- bc.scope1End = 200;
- break;
- case 1:
- val = GetDefultValue(mat);
- //给控件赋值
- if (bmc != null)
- bmc.scope1Start = 0;
- else
- bc.scope1Start = 0;
- if (bmc != null)
- bmc.scope1End = val;
- else
- bc.scope1End = val;
- break;
- case 5:
- val = GetDefultValue(mat);
- //给控件赋值
- if (bmc != null)
- bmc.scope1Start = 0;
- else
- bc.scope1Start = 0;
- if (bmc != null)
- bmc.scope1End = val;
- else
- bc.scope1End = val;
- break;
- }
- //处理直方图
- if (bmc != null)
- bmc.UpdateVerticalBarWithOneScope(Convert.ToInt32(bmc.scope1Start), Convert.ToInt32(bmc.scope1End));
- else
- bc.UpdateVerticalBarWithOneScope(Convert.ToInt32(bmc.scope1Start), Convert.ToInt32(bc.scope1End));
- mat.Dispose();
- GC.Collect();
- }
- else
- {
- MessageBox.Show(PdnResources.GetString("Menu.Pleaseselectapicturefirst.text"));
- }
- }
- /// <summary>
- /// 计算截面孔隙初始值
- /// </summary>
- /// <param name="mat"></param>
- private int GetDefultValue(Mat mat)
- {
- //配置输出的结果存储的 空间 ,用MatND类型来存储结果
- Mat hist = new Mat();
- Mat Gaos = new Mat();
- Cv2.GaussianBlur(mat, Gaos, new OpenCvSharp.Size(7, 7), 0);
- //设置计算直方图的维度
- int dims = 1;
- //直方图的每一个维度的柱条的数目(就是将数值分组,共有多少组)
- int[] histSize = { 255 };
- Rangef[] pranges = new Rangef[1];//一个通道,范围
- pranges[0].Start = 0.0F;//从0开始(含)
- pranges[0].End = 256.0F;//到256结束(不含)
- //6--计算直方图
- Cv2.CalcHist(new Mat[1] { mat }, new int[] { 0 }, new Mat(), hist, dims, histSize, pranges);
- int nHistSize = 256;
- float maxY = 0;
- int maxX = 0;
- List<float> vs = new List<float>() { };
- List<double> list = new List<double>() { };
- for (int i = 1; i < nHistSize - 1; i++)
- {
- float y = hist.At<float>(i);
- list.Add(y);
- }
- //maxX= GetHist(mat.Clone());
- double[] dd = cubicSmooth7(list.ToArray(), list.Count());
- int len = Convert.ToInt32(dd.Max()).ToString().Length;
- int xline = 1;
- for (int i = 0; i < len - 2; i++)
- {
- xline = xline * 10;
- }
- List<double> maxList = new List<double>() { };
- for (int i = 3; i < list.Count() - 1; i++)
- {
- double Y2 = dd[i];
- double Y1 = dd[i - 3];
- double angleOfLine = Math.Atan2((Y2 - Y1), 3 * xline) * 180 / Math.PI;
- maxList.Add(angleOfLine);
- }
- for (int i = maxList.Count() - 5; i > 10; i--)
- {
- double t1 = maxList[i];
- double t2 = maxList[i + 1];
- if (t1 - t2 < 0)
- {
- maxX = i;
- break;
- }
- }
- maxX = getMax(maxList, maxList.Count() - 15);
- for (int i = maxX - 10; i > 10; i--)
- {
- double def = 0;
- for (int j = i; j < i + 5; j++)
- {
- def = def + (dd[j + 1] - dd[j]);
- }
- }
- //通过斜率计算坡底
- List<double> angle = new List<double>() { };
- for (int i = maxX - 10; i > 10; i--)
- {
- double Y2 = dd[i];
- double Y1 = dd[i - 3];
- double angleOfLine = Math.Atan2((Y2 - Y1), 3 * xline) * 180 / Math.PI;
- angle.Add(angleOfLine);
- }
- int N = 0;
- for (int i = 10; i < angle.Count() - 1; i++)
- {
- double t1 = angle[i];
- double t2 = angle[i + 1];
- if (t1 < 10 && t1 - t2 < 0.1)
- {
- N = i;
- break;
- }
- }
- //原点
- PointF p0 = new PointF(0, 0);
- //波峰顶点
- PointF p1 = new PointF(maxX, Convert.ToInt32(dd[maxX]));
- int pn = 0;
- double maxD = 0;
- //通过最远距离计算坡底
- for (int i = maxX / 2; i < maxX; i++)
- {
- PointF p = new PointF(i, Convert.ToInt32(dd[i]));
- double d = GetMinDistance(p0, p1, p);
- if (maxD < d)
- {
- maxD = d;
- pn = i;
- }
- }
- return pn;
- }
- /// <summary>
- /// 计算隔膜孔隙初始值
- /// </summary>
- /// <param name="mat"></param>
- private int GetDefultValueForMem(Mat mat)
- {
- //配置输出的结果存储的 空间 ,用MatND类型来存储结果
- Mat hist = new Mat();
- Mat Gaos = new Mat();
- Cv2.GaussianBlur(mat, Gaos, new OpenCvSharp.Size(7, 7), 0);
- //设置计算直方图的维度
- int dims = 1;
- //直方图的每一个维度的柱条的数目(就是将数值分组,共有多少组)
- int[] histSize = { 255 };
- Rangef[] pranges = new Rangef[1];//一个通道,范围
- pranges[0].Start = 0.0F;//从0开始(含)
- pranges[0].End = 256.0F;//到256结束(不含)
- //6--计算直方图
- Cv2.CalcHist(new Mat[1] { mat }, new int[] { 0 }, new Mat(), hist, dims, histSize, pranges);
- int nHistSize = 256;
- float maxY = 0;
- int maxX = 0;
- List<float> vs = new List<float>() { };
- List<double> list = new List<double>() { };
- for (int i = 1; i < nHistSize - 1; i++)
- {
- float y = hist.At<float>(i);
- list.Add(y);
- if (y > maxY)
- {
- maxY = y;
- maxX = i;
- }
- }
- return maxX;
- }
- private int getMax(List<double> maxList, int init)
- {
- int ret = init;
- for (int i = init; i > 10; i--)
- {
- int pre = 0;
- int after = 0;
- for (int t = i; t < i + 10; t++)
- {
- if (maxList[t] < 0)
- {
- pre++;
- }
- }
- for (int t = i; t > i - 10; t--)
- {
- if (maxList[t] > 0)
- {
- after++;
- }
- }
- if (pre > 8 && after > 8)
- {
- ret = i;
- break;
- }
- //double t1 = maxList[i];
- //double t2 = maxList[i + 1];
- //if (t1>=10&&t2>=10&&t1-t2>0)
- //{
- // ret = i;
- // break;
- //}
- }
- return ret;
- }
- /// <summary>
- /// 计算单晶初始值
- /// </summary>
- /// <param name="mat"></param>
- private int GetDefultValueForCrystal(Mat mat)
- {
- //配置输出的结果存储的 空间 ,用MatND类型来存储结果
- Mat hist = new Mat();
- Mat Gaos = new Mat();
- //Cv2.GaussianBlur(mat, Gaos, new OpenCvSharp.Size(7, 7), 0);
- //设置计算直方图的维度
- int dims = 1;
- //直方图的每一个维度的柱条的数目(就是将数值分组,共有多少组)
- int[] histSize = { 255 };
- Rangef[] pranges = new Rangef[1];//一个通道,范围
- pranges[0].Start = 0.0F;//从0开始(含)
- pranges[0].End = 256.0F;//到256结束(不含)
- //6--计算直方图
- Cv2.CalcHist(new Mat[1] { mat }, new int[] { 0 }, new Mat(), hist, dims, histSize, pranges);
- int nHistSize = 256;
- float maxY = 0;
- int maxX = 0;
- List<float> vs = new List<float>() { };
- List<double> list = new List<double>() { };
- for (int i = 1; i < nHistSize - 1; i++)
- {
- float y = hist.At<float>(i);
- list.Add(y);
- }
- //maxX= GetHist(mat.Clone());
- double[] dd = cubicSmooth7(list.ToArray(), list.Count());
- List<double> maxList = new List<double>() { };
- for (int i = 3; i < list.Count() - 1; i++)
- {
- double Y2 = dd[i];
- double Y1 = dd[i - 3];
- double angleOfLine = Math.Atan2((Y2 - Y1), 30000) * 180 / Math.PI;
- maxList.Add(angleOfLine);
- }
- for (int i = maxList.Count() - 5; i > 10; i--)
- {
- double t1 = maxList[i];
- double t2 = maxList[i + 1];
- if (t1 - t2 < 0)
- {
- maxX = i;
- break;
- }
- }
- int max2 = list.FindIndex(s => s == list.Max());
- //波峰
- maxX = getMax(maxList, maxList.Count() - 15);
- //原点
- PointF p0 = new PointF(255, 0);
- //波峰顶点
- PointF p1 = new PointF(max2, Convert.ToInt32(dd[max2]));
- int pn = 0;
- double maxD = 0;
- if (imageType == 2)
- {
- //通过最远距离计算坡底
- for (int i = max2; i < maxX; i++)
- {
- PointF p = new PointF(i, Convert.ToInt32(dd[i]));
- double d = GetMinDistance(p0, p1, p);
- if (maxD < d)
- {
- maxD = d;
- pn = i;
- }
- }
- return pn;
- //return pn + (maxX - pn) / 2;
- }
- else
- {
- //通过最远距离计算坡底
- for (int i = max2; i < 200; i++)
- {
- PointF p = new PointF(i, Convert.ToInt32(dd[i]));
- double d = GetMinDistance(p0, p1, p);
- if (maxD < d)
- {
- maxD = d;
- pn = i;
- }
- }
- return pn;
- }
- ////原点
- //PointF p0 = new PointF(255, 0);
- ////波峰顶点
- //PointF p1 = new PointF(maxX, Convert.ToInt32(dd[maxX]));
- //int pn = 0;
- //double maxD = 0;
- ////通过最远距离计算坡底
- //for (int i = maxX; i < 245; i++)
- //{
- // PointF p = new PointF(i, Convert.ToInt32(dd[i]));
- // double d = GetMinDistance(p0, p1, p);
- // if (maxD < d)
- // {
- // maxD = d;
- // pn = i;
- // }
- //}
- //return pn;
- // return maxX + N;
- }
- /// <summary>
- /// 计算开裂球初始值
- /// </summary>
- /// <param name="mat"></param>
- private int GetDefultValueForBall(Mat mat)
- {
- //配置输出的结果存储的 空间 ,用MatND类型来存储结果
- Mat hist = new Mat();
- int dims = 1;
- //直方图的每一个维度的柱条的数目(就是将数值分组,共有多少组)
- int[] histSize = { 255 };
- Rangef[] pranges = new Rangef[1];//一个通道,范围
- pranges[0].Start = 0.0F;//从0开始(含)
- pranges[0].End = 256.0F;//到256结束(不含)
- //6--计算直方图
- Cv2.CalcHist(new Mat[1] { mat }, new int[] { 0 }, new Mat(), hist, dims, histSize, pranges);
- int nHistSize = 256;
- float maxY = 0;
- int maxX = 0;
- List<float> vs = new List<float>() { };
- List<double> list = new List<double>() { };
- for (int i = 1; i < nHistSize - 1; i++)
- {
- float y = hist.At<float>(i);
- list.Add(y);
- }
- //maxX= GetHist(mat.Clone());
- double[] dd = cubicSmooth7(list.ToArray(), list.Count());
- List<double> maxList = new List<double>() { };
- for (int i = 3; i < list.Count() - 1; i++)
- {
- double Y2 = dd[i];
- double Y1 = dd[i - 3];
- double angleOfLine = Math.Atan2((Y2 - Y1), 30000) * 180 / Math.PI;
- maxList.Add(angleOfLine);
- }
- for (int i = maxList.Count() - 5; i > 10; i--)
- {
- double t1 = maxList[i];
- double t2 = maxList[i + 1];
- if (t1 - t2 < 0)
- {
- maxX = i;
- break;
- }
- }
- int max2 = list.FindIndex(s => s == list.Max());
- //波峰
- maxX = getMax(maxList, maxList.Count() - 15);
- if (maxX > max2)
- {
- PointF p0 = new PointF(max2, Convert.ToInt32(dd[max2]));
- //波峰顶点
- PointF p1 = new PointF(maxX, Convert.ToInt32(dd[maxX]));
- int pn = 0;
- double maxD = 0;
- //通过最远距离计算坡底
- for (int i = max2; i < maxX; i++)
- {
- PointF p = new PointF(i, Convert.ToInt32(dd[i]));
- double d = GetMinDistance(p0, p1, p);
- if (maxD < d)
- {
- maxD = d;
- pn = i;
- }
- }
- return pn + (maxX - pn) / 2;
- }
- else
- {
- return maxX - 10;
- }
- }
- /****点到直线的距离***
- * 过点(x1,y1)和点(x2,y2)的直线方程为:KX -Y + (x2y1 - x1y2)/(x2-x1) = 0
- * 设直线斜率为K = (y2-y1)/(x2-x1),C=(x2y1 - x1y2)/(x2-x1)
- * 点P(x0,y0)到直线AX + BY +C =0DE 距离为:d=|Ax0 + By0 + C|/sqrt(A*A + B*B)
- * 点(x3,y3)到经过点(x1,y1)和点(x2,y2)的直线的最短距离为:
- * distance = |K*x3 - y3 + C|/sqrt(K*K + 1)
- */
- public static double GetMinDistance(PointF pt1, PointF pt2, PointF pt3)
- {
- double dis = 0;
- if (pt1.X == pt2.X)
- {
- dis = Math.Abs(pt3.X - pt1.X);
- return dis;
- }
- double lineK = (pt2.Y - pt1.Y) / (pt2.X - pt1.X);
- double lineC = (pt2.X * pt1.Y - pt1.X * pt2.Y) / (pt2.X - pt1.X);
- dis = Math.Abs(lineK * pt3.X - pt3.Y + lineC) / (Math.Sqrt(lineK * lineK + 1));
- return dis;
- }
- /// <summary>
- /// 数据平滑
- /// </summary>
- /// <param name="in1"></param>
- /// <param name="N"></param>
- /// <returns></returns>
- private double[] quadraticSmooth5(double[] in1, int N)
- {
- double[] out1 = new double[in1.Length];
- int i;
- if (N < 5)
- {
- for (i = 0; i <= N - 1; i++)
- {
- out1[i] = in1[i];
- }
- }
- else
- {
- out1[0] = (31.0 * in1[0] + 9.0 * in1[1] - 3.0 * in1[2] - 5.0 * in1[3] + 3.0 * in1[4]) / 35.0;
- out1[1] = (9.0 * in1[0] + 13.0 * in1[1] + 12 * in1[2] + 6.0 * in1[3] - 5.0 * in1[4]) / 35.0;
- for (i = 2; i <= N - 3; i++)
- {
- out1[i] = (-3.0 * (in1[i - 2] + in1[i + 2]) +
- 12.0 * (in1[i - 1] + in1[i + 1]) + 17 * in1[i]) / 35.0;
- }
- out1[N - 2] = (9.0 * in1[N - 1] + 13.0 * in1[N - 2] + 12.0 * in1[N - 3] + 6.0 * in1[N - 4] - 5.0 * in1[N - 5]) / 35.0;
- out1[N - 1] = (31.0 * in1[N - 1] + 9.0 * in1[N - 2] - 3.0 * in1[N - 3] - 5.0 * in1[N - 4] + 3.0 * in1[N - 5]) / 35.0;
- }
- return out1;
- }
- public double[] cubicSmooth7(double[] in1, int N)
- {
- double[] out1 = new double[in1.Length];
- int i;
- if (N < 7)
- {
- for (i = 0; i <= N - 1; i++)
- {
- out1[i] = in1[i];
- }
- }
- else
- {
- out1[0] = (39.0 * in1[0] + 8.0 * in1[1] - 4.0 * in1[2] - 4.0 * in1[3] +
- 1.0 * in1[4] + 4.0 * in1[5] - 2.0 * in1[6]) / 42.0;
- out1[1] = (8.0 * in1[0] + 19.0 * in1[1] + 16.0 * in1[2] + 6.0 * in1[3] -
- 4.0 * in1[4] - 7.0 * in1[5] + 4.0 * in1[6]) / 42.0;
- out1[2] = (-4.0 * in1[0] + 16.0 * in1[1] + 19.0 * in1[2] + 12.0 * in1[3] +
- 2.0 * in1[4] - 4.0 * in1[5] + 1.0 * in1[6]) / 42.0;
- for (i = 3; i <= N - 4; i++)
- {
- out1[i] = (-2.0 * (in1[i - 3] + in1[i + 3]) +
- 3.0 * (in1[i - 2] + in1[i + 2]) +
- 6.0 * (in1[i - 1] + in1[i + 1]) + 7.0 * in1[i]) / 21.0;
- }
- out1[N - 3] = (-4.0 * in1[N - 1] + 16.0 * in1[N - 2] + 19.0 * in1[N - 3] +
- 12.0 * in1[N - 4] + 2.0 * in1[N - 5] - 4.0 * in1[N - 6] + 1.0 * in1[N - 7]) / 42.0;
- out1[N - 2] = (8.0 * in1[N - 1] + 19.0 * in1[N - 2] + 16.0 * in1[N - 3] +
- 6.0 * in1[N - 4] - 4.0 * in1[N - 5] - 7.0 * in1[N - 6] + 4.0 * in1[N - 7]) / 42.0;
- out1[N - 1] = (39.0 * in1[N - 1] + 8.0 * in1[N - 2] - 4.0 * in1[N - 3] -
- 4.0 * in1[N - 4] + 1.0 * in1[N - 5] + 4.0 * in1[N - 6] - 2.0 * in1[N - 7]) / 42.0;
- }
- return out1;
- }
- public double[] quadraticSmooth7(double[] in1, int N)
- {
- double[] out1 = new double[in1.Length];
- int i;
- if (N < 7)
- {
- for (i = 0; i <= N - 1; i++)
- {
- out1[i] = in1[i];
- }
- }
- else
- {
- out1[0] = (32.0 * in1[0] + 15.0 * in1[1] + 3.0 * in1[2] - 4.0 * in1[3] -
- 6.0 * in1[4] - 3.0 * in1[5] + 5.0 * in1[6]) / 42.0;
- out1[1] = (5.0 * in1[0] + 4.0 * in1[1] + 3.0 * in1[2] + 2.0 * in1[3] +
- in1[4] - in1[6]) / 14.0;
- out1[2] = (1.0 * in1[0] + 3.0 * in1[1] + 4.0 * in1[2] + 4.0 * in1[3] +
- 3.0 * in1[4] + 1.0 * in1[5] - 2.0 * in1[6]) / 14.0;
- for (i = 3; i <= N - 4; i++)
- {
- out1[i] = (-2.0 * (in1[i - 3] + in1[i + 3]) +
- 3.0 * (in1[i - 2] + in1[i + 2]) +
- 6.0 * (in1[i - 1] + in1[i + 1]) + 7.0 * in1[i]) / 21.0;
- }
- out1[N - 3] = (1.0 * in1[N - 1] + 3.0 * in1[N - 2] + 4.0 * in1[N - 3] +
- 4.0 * in1[N - 4] + 3.0 * in1[N - 5] + 1.0 * in1[N - 6] - 2.0 * in1[N - 7]) / 14.0;
- out1[N - 2] = (5.0 * in1[N - 1] + 4.0 * in1[N - 2] + 3.0 * in1[N - 3] +
- 2.0 * in1[N - 4] + in1[N - 5] - in1[N - 7]) / 14.0;
- out1[N - 1] = (32.0 * in1[N - 1] + 15.0 * in1[N - 2] + 3.0 * in1[N - 3] -
- 4.0 * in1[N - 4] - 6.0 * in1[N - 5] - 3.0 * in1[N - 6] + 5.0 * in1[N - 7]) / 42.0;
- }
- return out1;
- }
- /// <summary>
- /// 获取直方图
- /// </summary>
- /// <returns></returns>
- private int GetHist(Mat srcImage)
- {
- Mat hist = new Mat();
- Mat Gaos = new Mat();
- Cv2.GaussianBlur(srcImage, Gaos, new OpenCvSharp.Size(7, 7), 0);
- //设置计算直方图的维度
- int dims = 1;
- //直方图的每一个维度的柱条的数目(就是将数值分组,共有多少组)
- int[] histSize = { 255 };
- Rangef[] pranges = new Rangef[1];//一个通道,范围
- pranges[0].Start = 0.0F;//从0开始(含)
- pranges[0].End = 256.0F;//到256结束(不含)
- //6--计算直方图
- Cv2.CalcHist(new Mat[1] { Gaos }, new int[] { 0 }, new Mat(), hist, dims, histSize, pranges);
- Mat drawImage = Mat.Zeros(new OpenCvSharp.Size(256, 256), MatType.CV_8UC3);
- double min = 0;
- double max = 0;
- Cv2.MinMaxLoc(hist, out min, out max);
- for (int i = 0; i < 256; i++)
- {
- int value = Convert.ToInt32(Math.Round(hist.At<float>(i) * 256 * 0.9 / max, MidpointRounding.AwayFromZero));
- Cv2.Line(drawImage, new OpenCvSharp.Point(i, drawImage.Rows - 1), new OpenCvSharp.Point(i, drawImage.Rows - 1 - value), new Scalar(255, 0, 0));
- }
- //灰度图
- Cv2.CvtColor(drawImage, drawImage, ColorConversionCodes.BGR2GRAY);
- Mat g_bwImage = new Mat();
- //图像二值化
- Cv2.Threshold(drawImage, g_bwImage, 0, 255, ThresholdTypes.Binary);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //轮廓
- Cv2.FindContours(g_bwImage, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- InputArray contoursAll = InputArray.Create(contours[0]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- int retint = 0;
- for (int i = 0; i < outArr.Count; i++)
- {
- if (outArr[i].X > 230)
- {
- continue;
- }
- else if (outArr[i].X < 20)
- {
- continue;
- }
- else if (retint < outArr[i].X)
- {
- retint = outArr[i].X;
- }
- }
- // Cv2.ImShow("【直方图】", drawImage);
- return retint;
- }
- /// <summary>
- /// 获取凸包
- /// </summary>
- /// <param name="src"></param>
- private void convexity_defects(Mat src)
- {
- Mat src_copy = src.Clone();
- Mat threshold_output = new Mat(), src_gray = new Mat();
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- List<Vec4i> hierarchy;
- Cv2.CvtColor(src_copy, src_gray, ColorConversionCodes.BGR2GRAY);
- Cv2.Threshold(src_gray, threshold_output, 0, 255, ThresholdTypes.Binary);
- Cv2.FindContours(threshold_output, out contours, out hierarchyIndex, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
- List<int> hullsI = new List<int>() { };
- List<Vec4i> defect = new List<Vec4i>() { };
- InputArray contoursAll = InputArray.Create(contours[0]);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- OutputArray hulls = OutputArray.Create(hullsI);
- OutputArray defects = OutputArray.Create(defect);
- Cv2.ConvexHull(contoursAll, hull, false);
- // find int type hull
- Cv2.ConvexHull(contoursAll, hulls, false);
- InputArray hullsi = InputArray.Create(hullsI);
- // get convexity defects
- Cv2.ConvexityDefects(contoursAll, hullsi, defects);
- /// Draw contours + hull results
- Mat drawing = Mat.Zeros(threshold_output.Size(), MatType.CV_8UC3);
- Scalar color = new Scalar(210, 50, 255);
- Cv2.DrawContours(drawing, contours, 0, color, -1);
- Cv2.DrawContours(drawing, new OpenCvSharp.Point[][] { outArr.ToArray() }, 0, color, -1);
- // draw defects
- int count = contours[0].Count();
- foreach (var item in defect)
- {
- int startidx = item[0];
- OpenCvSharp.Point ptStart = contours[0][startidx]; // point of the contour where the defect begins
- int endidx = item[1];
- OpenCvSharp.Point ptEnd = contours[0][endidx]; // point of the contour where the defect ends
- int faridx = item[2];
- OpenCvSharp.Point ptFar = contours[0][faridx];// the farthest from the convex hull point within the defect
- int depth = item[3] / 256; // distance between the farthest point and the convex hull
- if (depth > 2 && depth < 500)
- {
- Cv2.Line(drawing, ptStart, ptFar, new Scalar(0, 255, 0), 2);
- Cv2.Line(drawing, ptEnd, ptFar, new Scalar(0, 255, 0), 2);
- Cv2.Circle(drawing, ptStart, 4, new Scalar(255, 0, 0), 2);
- Cv2.Circle(drawing, ptEnd, 4, new Scalar(255, 0, 0), 2);
- Cv2.Circle(drawing, ptFar, 4, new Scalar(100, 0, 255), 2);
- }
- }
- Cv2.ImShow("Hull demo", drawing);
- }
- #endregion
- #region 开裂球
- /// <summary>
- /// 忽略开裂球,设为开裂球,设为普通球
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DeleteBall(List<PointF> pointFs, List<PointF> KpointFs, List<PointF> PpointFs)
- {
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 14 });
- action.Lists.Add(new Args() { Key = "CreackBallPointFs", Value = pointFs });
- action.Lists.Add(new Args() { Key = "CreackBallPointFsK", Value = KpointFs });
- action.Lists.Add(new Args() { Key = "CreackBallPointFsP", Value = PpointFs });
- newMat = this.PerformProcessGetdata(LunkMat, OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parent, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 绘制轮廓开裂球
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuoLie(List<List<PointF>> pointFs, List<PointF> KaiPointFs, List<PointF> PuPointFs)
- {
- lineList_ball = pointFs;
- kailie_ball = KaiPointFs;
- putong_ball = PuPointFs;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat newMat = new Mat();
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- newMat = getKong(bitmap, out data);
- }
- catch (Exception)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parent, itemCount, copyThreadProc, progressEvents, null);
- // Mat newMat = getKong(bitmap, out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 绘制轮廓开裂球
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DrwLunKuoLie1(List<List<PointF>> pointFs, List<PointF> KaiPointFs, List<PointF> PuPointFs)
- {
- lineList_ball = pointFs;
- kailie_ball = KaiPointFs;
- putong_ball = PuPointFs;
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat newMat = ReGetKong(bitmap, out data);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 选择开裂球
- /// </summary>
- /// <returns></returns>
- public void DrwLunKuoLie1Selected(int select)
- {
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = select });
- Mat newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- }
- //所有点
- Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- List<int> relit = new List<int>();
- Mat g_srcImage = new Mat();
- Mat temp = new Mat();
- Vec4b vec4B = new Vec4b(255, 0, 0, 255);
- Vec4b vec4B1 = new Vec4b(0, 0, 255, 255);
- /// <summary>
- /// 获取开裂球
- /// </summary>
- /// <param name="img"></param>
- /// <returns></returns>
- private Mat getKong(Bitmap img, out List<List<int>> outdata)
- {
- particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- relit = new List<int>();
- g_srcImage = new Mat();
- temp = new Mat();
- outdata = new List<List<int>>() { };
- Mat M = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- //M.ConvertTo(g_srcImage, MatType.CV_8UC3);
- Cv2.CvtColor(M, g_srcImage, ColorConversionCodes.BGRA2BGR);
- if (lineList_ball.Count > 0)
- {
- for (int line = 0; line < lineList_ball.Count; line++)
- {
- List<PointF> pointList = lineList_ball[line];
- for (int i = 0; i < pointList.Count - 1; i++)
- {
- Cv2.Line(g_srcImage, new OpenCvSharp.Point() { X = (int)pointList[i].X, Y = (int)pointList[i].Y }, new OpenCvSharp.Point() { X = (int)pointList[i + 1].X, Y = (int)pointList[i + 1].Y }, new Scalar(0, 0, 0), 5);
- }
- }
- }
- //调试方便
- // Cv2.Resize(g_srcImage, g_srcImage,new OpenCvSharp.Size(g_srcImage.Cols / 3, g_srcImage.Rows / 3), (0.0), (0.0), OpenCvSharp.InterpolationFlags.Area);
- Mat gray = new Mat();
- Mat binary = new Mat();
- Mat shifted = new Mat(M.Size(), MatType.CV_8UC3);
- //均值漂移 滤波
- // Cv2.PyrMeanShiftFiltering(g_srcImage, shifted, 21, 51);
- Cv2.GaussianBlur(g_srcImage, shifted, new OpenCvSharp.Size(15, 15), 0);
- //灰度图
- Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
- //二值化
- double otsu = Cv2.Threshold(gray, binary, 100, 200, ThresholdTypes.Binary/*.Otsu*/);
- // distance transform
- Mat dist = new Mat();
- Cv2.DistanceTransform(binary, dist, DistanceTypes.L2, DistanceMaskSize.Mask3);
- //归一化数据
- Cv2.Normalize(dist, dist, 0, 1, NormTypes.MinMax);
- // binary
- Cv2.Threshold(dist, dist, 0.4, 1, ThresholdTypes.Binary);
- // markers
- Mat dist_m = new Mat();
- dist.ConvertTo(dist_m, MatType.CV_8UC1);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(dist_m, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- // create markers
- Mat markers = Mat.Zeros(g_srcImage.Size(), MatType.CV_32SC1);
- for (int t = 0; t < contours.Length; t++)
- {
- Cv2.DrawContours(markers, contours, t, new Scalar(t + 1), -1);
- }
- // Cv2.ImShow("分割后", markers);
- Cv2.Circle(markers, new OpenCvSharp.Point(5, 5), 30, new Scalar(255), -1);
- //形体学操作 去掉干扰
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
- Cv2.MorphologyEx(g_srcImage, g_srcImage, MorphTypes.Erode, kernel);
- Cv2.Watershed(g_srcImage, markers);
- // 颜色填充与最终显示
- int index = 0;
- for (int row = 0; row < markers.Rows; row++)
- {
- for (int col = 0; col < markers.Cols; col++)
- {
- index = markers.At<int>(row, col);
- if (index > 0 && index <= contours.Length)
- {
- if (particlePixles.ContainsKey(index))
- {
- particlePixles[index].Add(new OpenCvSharp.Point(col, row));
- }
- else
- {
- List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
- Pixles.Add(new OpenCvSharp.Point(col, row));
- particlePixles.Add(index, Pixles);
- }
- }
- }
- }
- int k = 0;
- foreach (var item in particlePixles)
- {
- if (item.Value.Count > 99999)
- {
- k = item.Key;
- break;
- }
- }
- particlePixles.Remove(k);
- //temp = Adjust.BaseImage.BaseTools.MergeMatFromMatArr(temp, vec4B);
- int q = 0;
- int iskailie = 0;
- temp = new Mat(g_srcImage.Rows, g_srcImage.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- int index1 = 0;
- foreach (var item in particlePixles)
- {
- // 将轮廓转为矩形框 , 这个最大的矩形为感兴趣的图像
- Rect rect = Cv2.BoundingRect(item.Value);
- List<OpenCvSharp.Point> pixel = item.Value;
- Mat particle = g_srcImage[rect];
- Mat back = particle.Clone();
- //Mat forwrit = M[rect];
- //Mat small = forwrit.Clone();
- //int n = 30;
- //float MaxCG = 5.5f;
- //Mat dst1 = myACE(small, n, MaxCG);
- //Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5));
- //Cv2.MorphologyEx(dst1, dst1, MorphTypes.BlackHat, element);
- //Cv2.GaussianBlur(dst1, dst1, new OpenCvSharp.Size(3, 3), 0);
- //Cv2.ImWrite("E://1/" + index1++.ToString() + ".jpg", dst1);
- ////for (int i = 0; i < small.Cols; i++)
- ////{
- //// for (int j = 0; j < small.Rows; j++)
- //// {
- //// OpenCvSharp.Point pp = new OpenCvSharp.Point() { X=i+ rect.X, Y=j+ rect.Y };
- //// if (pixel.Contains(pp))
- //// {
- //// continue;
- //// }
- //// small.Set<Vec3b>(j, i, new Vec3b(255, 0, 0));
- //// }
- ////}
- //// Cv2.ImWrite("E:/ballcut/test" + index1.ToString() + ".jpg", small);
- long aveg = 0;
- long aveb = 0;
- long aver = 0;
- foreach (var pt in pixel)
- {
- if (kailie_ball.Count > 0)
- {
- PointF p = new PointF() { X = pt.X, Y = pt.Y };
- if (kailie_ball.Contains(p))
- {
- iskailie = 1;
- break;
- }
- }
- if (putong_ball.Count > 0)
- {
- PointF p = new PointF() { X = pt.X, Y = pt.Y };
- if (putong_ball.Contains(p))
- {
- iskailie = 2;
- break;
- }
- }
- aveg += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[0];
- aveb += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[1];
- aver += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[2];
- }
- int ret = 0;
- if (iskailie == 1)
- {
- ret = 1;
- }
- else if (iskailie == 2)
- {
- ret = 0;
- }
- else
- {
- aveg = aveg / pixel.Count;
- aveb = aveb / pixel.Count;
- aver = aver / pixel.Count;
- for (int i = 0; i < back.Cols; i++)
- {
- for (int j = 0; j < back.Rows; j++)
- {
- back.Set<Vec3b>(j, i, new Vec3b((byte)aveg, (byte)aveb, (byte)aver));
- }
- }
- foreach (var pt in pixel)
- {
- back.Set<Vec3b>(pt.Y - rect.Y, pt.X - rect.X, particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X));
- }
- ret = GetSplit2(back);
- relit.Add(ret);
- }
- if (ret == 1)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(0, 0, 255, 255), 2);
- }
- else if (ret == 0)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 0, 0, 255), 2);
- }
- double area = Cv2.ContourArea(item.Value);
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- if (kailie_ball.Count > 0)
- {
- for (int i = 0; i < kailie_ball.Count; i++)
- {
- double px = kailie_ball[i].X;
- double py = kailie_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 1;
- relit[index1] = 1;
- break;
- }
- }
- }
- if (putong_ball.Count > 0)
- {
- for (int i = 0; i < putong_ball.Count; i++)
- {
- double px = putong_ball[i].X;
- double py = putong_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 0;
- relit[index1] = 0;
- break;
- }
- }
- }
- List<int> po = new List<int>() { x, y, width, height, (int)area, ret };
- outdata.Add(po);
- index1++;
- }
- Mat temp1 = new Mat();
- Cv2.Erode(temp, temp1, null);
- temp = temp - temp1;
- return temp;
- }
- private Mat ReGetKong(Bitmap img, out List<List<int>> outdata)
- {
- outdata = new List<List<int>>() { };
- if (particlePixles.Count == 0)
- {
- return null;
- }
- temp = new Mat(g_srcImage.Rows, g_srcImage.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- int index = 0;
- foreach (var item in particlePixles)
- {
- // 将轮廓转为矩形框 , 这个最大的矩形为感兴趣的图像
- Rect rect = Cv2.BoundingRect(item.Value);
- List<OpenCvSharp.Point> pixel = item.Value;
- Mat particle = g_srcImage[rect];
- int ret = relit[index];
- double area = Cv2.ContourArea(item.Value);
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- if (kailie_ball.Count > 0)
- {
- for (int i = 0; i < kailie_ball.Count; i++)
- {
- double px = kailie_ball[i].X;
- double py = kailie_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 1;
- relit[index] = 1;
- break;
- }
- }
- }
- if (putong_ball.Count > 0)
- {
- for (int i = 0; i < putong_ball.Count; i++)
- {
- double px = putong_ball[i].X;
- double py = putong_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 0;
- relit[index] = 0;
- break;
- }
- }
- }
- if (selectPointFs != null)
- {
- double px = selectPointFs.X;
- double py = selectPointFs.Y;
- if (px == x && py == y)
- {
- ret = 2;
- }
- }
- index++;
- if (ret == 1)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(0, 0, 255, 255), 2);
- }
- else if (ret == 0)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 0, 0, 255), 2);
- }
- else if (ret == 2)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 255, 0, 255), 2);
- }
- List<int> po = new List<int>() { x, y, width, height, (int)area, ret };
- outdata.Add(po);
- }
- Mat temp1 = new Mat();
- Cv2.Erode(temp, temp1, null);
- temp = temp - temp1;
- return temp;
- }
- private Mat ReGetSelect(Bitmap img)
- {
- if (particlePixles.Count == 0)
- {
- return null;
- }
- temp = new Mat(g_srcImage.Rows, g_srcImage.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- int index = 0;
- foreach (var item in particlePixles)
- {
- // 将轮廓转为矩形框 , 这个最大的矩形为感兴趣的图像
- Rect rect = Cv2.BoundingRect(item.Value);
- List<OpenCvSharp.Point> pixel = item.Value;
- Mat particle = g_srcImage[rect];
- int ret = relit[index];
- double area = Cv2.ContourArea(item.Value);
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- if (kailie_ball.Count > 0)
- {
- for (int i = 0; i < kailie_ball.Count; i++)
- {
- double px = kailie_ball[i].X;
- double py = kailie_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 1;
- relit[index] = 1;
- break;
- }
- }
- }
- if (putong_ball.Count > 0)
- {
- for (int i = 0; i < putong_ball.Count; i++)
- {
- double px = putong_ball[i].X;
- double py = putong_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 0;
- relit[index] = 0;
- break;
- }
- }
- }
- if (selectPointFs != null)
- {
- double px = selectPointFs.X;
- double py = selectPointFs.Y;
- if (px == x && py == y)
- {
- ret = 2;
- }
- }
- index++;
- if (ret == 1)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(0, 0, 255, 255), 2);
- }
- else if (ret == 0)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 0, 0, 255), 2);
- }
- else if (ret == 2)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 255, 0, 255), 2);
- }
- }
- Mat temp1 = new Mat();
- Cv2.Erode(temp, temp1, null);
- temp = temp - temp1;
- return temp;
- }
- private int GetSplit2(Mat src)
- {
- Mat shifted = new Mat(), gray = new Mat(), binary = new Mat(), dist;
- //Cv2.GaussianBlur(src, shifted, new OpenCvSharp.Size(3, 3), 0);
- Cv2.PyrMeanShiftFiltering(src, shifted, 10, 18); //模糊细节,这个参数由颗粒的大小确定
- Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
- Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5));
- Cv2.MorphologyEx(gray, gray, MorphTypes.TopHat, element);
- Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
- Mat element1 = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3));
- Cv2.MorphologyEx(binary, binary, MorphTypes.Open, element1);
- for (int i = 0; i < 4; i++)
- Cv2.MorphologyEx(binary, binary, MorphTypes.Dilate, element1);
- int height = src.Rows;
- int width = src.Cols;
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(binary, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));
- if (contours.Length == 0)
- {
- return -1;
- }
- List<OpenCvSharp.Point> arrAll = new List<OpenCvSharp.Point>();
- for (int t = 0; t < contours.Length; t++)
- {
- foreach (var item in contours[t])
- {
- arrAll.Add(item);
- }
- }
- InputArray contoursAll = InputArray.Create(arrAll);
- List<OpenCvSharp.Point> outArr = new List<OpenCvSharp.Point>();
- List<OpenCvSharp.Point> hullpoint = new List<OpenCvSharp.Point>();
- OutputArray hull = OutputArray.Create(outArr);
- Cv2.ConvexHull(contoursAll, hull, true);
- int hullcount = outArr.Count;
- OpenCvSharp.Point point0 = outArr[hullcount - 1];
- hullpoint.Add(point0);
- for (int i = 0; i < hullcount; i++)
- {
- OpenCvSharp.Point point = outArr[i];
- Cv2.Line(binary, point0, point, new Scalar(255, 255, 255));
- point0 = point;
- hullpoint.Add(point0);
- }
- bool flag = false;
- for (int t = 0; t < contours.Length; t++)
- {
- int size = contours[t].Length;
- if (size < 10)
- {
- continue;
- }
- Rect r = Cv2.BoundingRect(contours[t]);
- float rcX = r.X + r.Width / 2;
- float rcY = r.Y + r.Height / 2;
- double d = Cv2.PointPolygonTest(hullpoint, new Point2f(rcX, rcY), true);
- if ((d == 0) || (d < 0) || ((d < 15) && (d > 0))) //在凸包边缘上,在凸包的外部,在凸包的内部
- {
- continue;
- }
- else
- {
- flag = true;
- break;
- }
- }
- if (flag == true)
- {
- return 1;
- }
- return 0;
- }
- #region 赵天宇算法
- public void test(Mat src)
- {
- Mat dst = new Mat();
- //1:因为霍夫圆检测对噪声比较敏感,所以首先对图像做一个中值滤波或高斯滤波(噪声如果没有可以不做)
- Mat m1 = new Mat();
- Cv2.MedianBlur(src, 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);
- m2.Release();
- src.CopyTo(dst);
- //大圆
- for (int i = 0; i < cs.Count(); 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);
- }
- using (new Window("OutputImage", WindowMode.Normal, dst))
- using (new Window("InputImage", WindowMode.Normal, src))
- {
- Cv2.WaitKey(0);
- }
- Mat srcBlack;
- int sucessCs = 0;
- int badCs = 0;
- for (int i = 0; i < cs.Count(); i++)
- {
- srcBlack = new Mat(src.Height, src.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图
- //画圆
- 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);
- //画圆
- 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>();
- unsafe
- {
- 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 = src.Get<int>(srPoints[j].Y, srPoints[j].X);
- srcBlack.Set<int>(srPoints[j].Y, srPoints[j].X, item);
- }
- Mat rect = new Mat(srcBlack, Cv2.BoundingRect(contours[0]));
- //Cv2.EqualizeHist(rect, dst);
- Cv2.GaussianBlur(rect, dst, new OpenCvSharp.Size(3, 3), 0);
- //Cv2.MedianBlur(dst, dst, 1);
- Mat aa = dst.Threshold(50, 255, 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.Count(); m++)
- {
- for (int n = 0; n < contoursCircleLine[m].Count(); 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);
- }
- }
- }
- Cv2.FindContours(aa, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- Cv2.CvtColor(aa, aa, ColorConversionCodes.RGB2BGR);
- List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t.Count()).ToList();
- if (contoursHoleList.Count == 0)
- {
- continue;
- }
- List<int> maxList = new List<int>();
- int MaxListCount = 5;
- if (contoursHoleList.Count < MaxListCount)
- {
- MaxListCount = contoursHoleList.Count;
- }
- for (int g = 0; g < contoursHoleList.Count; g++)
- {
- maxList.Add(contoursHoleList[g].Count());
- if (g == MaxListCount - 1)
- {
- break;
- }
- }
- for (int k = 0; k < contours.Count(); k++)
- {
- RotatedRect rectR = Cv2.MinAreaRect(contours[k]); //计算每个轮廓最小外接矩形
- Rect rectB = Cv2.BoundingRect(contours[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;
- if (maxList.Contains(contours[k].Count()))
- {
- double distance = 0;
- for (int m = 0; m < contours[k].Count(); m++)
- {
- Point2f centerCoutours = new Point2f(contours[k][m].X, contours[k][m].Y);
- distance += centerCoutours.DistanceTo(center);
- }
- distance = distance / contours[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(contours[k], true) < 15)
- {
- Cv2.DrawContours(aa, contours, k, Scalar.Blue, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- }
- else
- {
- Cv2.DrawContours(aa, contours, k, Scalar.Green, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- }
- }
- else
- {
- Cv2.DrawContours(aa, contours, k, Scalar.Red, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- }
- }
- using (new Window("OutputImage", WindowMode.Normal, rect))
- using (new Window("InputImage", WindowMode.Normal, aa))
- {
- //Cv2.WaitKey(0);
- if (MessageBox.Show("当前识别率:" + ((float)sucessCs / (sucessCs + badCs) * 100) + "是否正确?", "识别判断", MessageBoxButtons.YesNo) == DialogResult.Yes)
- {
- sucessCs += 1;
- }
- else
- {
- badCs += 1;
- }
- }
- }
- MessageBox.Show("识别准确率: " + ((float)sucessCs / cs.Count() * 100));
- }
- #endregion
- #endregion
- #region 单晶
- /// <summary>
- /// 筛选单晶
- /// </summary>
- /// <returns></returns>
- public List<List<int>> ForgetCrystal(double pointsize)
- {
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 12 });
- action.Lists.Add(new Args() { Key = "pointsize", Value = pointsize });
- action.Lists.Add(new Args() { Key = "borderBottom", Value = borderBottom });
- action.Lists.Add(new Args() { Key = "border", Value = border });
- action.Lists.Add(new Args() { Key = "HW", Value = HW });
- action.Lists.Add(new Args() { Key = "AreaRatio", Value = AreaRatio });
- action.Lists.Add(new Args() { Key = "isDis", Value = isDis });
- action.Lists.Add(new Args() { Key = "isJu", Value = isJu });
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- string newbitmap = subPath + "\\mask.jpg";
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- //newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitDJ), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parentSinglCrystal, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 删除添加单晶
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DeleteCrystal(List<PointF> pointFs, List<List<PointF>> addPoints)
- {
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- List<List<OpenCvSharp.Point>> AddPoints = new List<List<OpenCvSharp.Point>>();
- if (addPoints.Count > 0)
- {
- for (int i = 0; i < addPoints.Count; i++)
- {
- List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
- addPoints[i].ForEach(p => plist.Add(new OpenCvSharp.Point((int)p.X, (int)p.Y)));
- AddPoints.Add(plist);
- }
- }
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 12 });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = pointFs });
- action.Lists.Add(new Args() { Key = "AddPontins", Value = AddPoints });
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- string newbitmap = subPath + "\\mask.jpg";
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- //newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitDJ), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(/*currentForm*/parentSinglCrystal, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 绘制单晶选择
- /// </summary>
- /// <returns></returns>
- public void DrwCrystalSelected(int select)
- {
- List<List<int>> data = new List<List<int>>() { };
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = select });
- Mat newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap), out data);
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- }
- private Mat getCutback(Bitmap img)
- {
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- Mat g_grayImage = new Mat();
- Mat g_dstImage = new Mat();
- Mat g_bwImage = new Mat();
- Mat dst = new Mat();
- //灰度图
- Cv2.CvtColor(mat, g_grayImage, ColorConversionCodes.BGR2GRAY);
- //图像二值化
- Cv2.Threshold(g_grayImage, g_bwImage, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
- Cv2.ImShow("g_bwImage", g_bwImage);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //轮廓
- Cv2.FindContours(g_bwImage, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- Mat matret = new Mat(mat.Rows, mat.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- for (int i = 0; i < contours.Length; i++)
- {
- if (Cv2.ContourArea(contours[i]) < 30)
- continue;
- Cv2.DrawContours(matret, contours, i, new Scalar(255, 144, 30, 255), -1);
- }
- Cv2.BitwiseAnd(mat, matret, dst);
- Cv2.ImShow("dst", dst);
- return dst;
- }
- /// <summary>
- /// 单晶颗粒
- /// </summary>
- private void DanJing(Bitmap img)
- {
- Mat g_srcImage = new Mat();
- Mat M = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- Cv2.CvtColor(M, g_srcImage, ColorConversionCodes.BGRA2BGR);
- //调试方便
- // Cv2.Resize(g_srcImage, g_srcImage, new OpenCvSharp.Size(g_srcImage.Cols / 3, g_srcImage.Rows / 3), (0.0), (0.0), OpenCvSharp.InterpolationFlags.Area);
- int rows = g_srcImage.Rows;
- int cols = g_srcImage.Cols;
- g_srcImage = g_srcImage[new Rect(0, 0, cols, rows - 50)];
- Mat gray = new Mat(), binary = new Mat(), shifted;
- Cv2.CvtColor(g_srcImage, gray, ColorConversionCodes.BGR2GRAY);
- Mat element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(5, 5), new OpenCvSharp.Point(2, 2));
- Cv2.MorphologyEx(gray, gray, MorphTypes.Open, element);//
- Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
- Cv2.ImShow("二值图像", binary);
- Mat labels = new Mat();
- int n_comps = Cv2.ConnectedComponents(binary, labels, PixelConnectivity.Connectivity4);
- Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- //draw
- rows = g_srcImage.Rows;
- cols = g_srcImage.Cols;
- Mat src_color = new Mat();// = Mat::zeros(imageShold.size(), CV_8UC3);
- src_color.Create(rows, cols, MatType.CV_8UC3);
- // src_color = Scalar.All(0);
- for (int x = 0; x < rows; x++)
- {
- for (int y = 0; y < cols; y++)
- {
- int label = labels.At<int>(x, y);//注意labels是CV_16U类型
- if (label != 0)
- {
- if (particlePixles.ContainsKey(label))
- {
- particlePixles[label].Add(new OpenCvSharp.Point(y, x));
- }
- else
- {
- List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
- Pixles.Add(new OpenCvSharp.Point(y, x));
- particlePixles.Add(label, Pixles);
- }
- }
- if (label == 0)
- {
- src_color.Set<Vec3b>(x, y, new Vec3b(255, 255, 255));
- continue;
- }
- Vec3b vec3 = new Vec3b((byte)((label * 10 * 10 * 10) % 255), (byte)((label * 10 * 10) % 255), (byte)((label * 10) % 255));
- src_color.Set<Vec3b>(x, y, vec3);
- }
- }
- int partnum = 0;
- int image1 = 0;
- foreach (var item in particlePixles)
- {
- List<OpenCvSharp.Point> pixel = item.Value;
- Rect rect = Cv2.BoundingRect(pixel);
- Mat particle = g_srcImage[rect];
- string windowName = string.Format("{0}", image1++) + ".jpg";
- int num = TinyParticle(particle, windowName);
- // Mat outImage =Cv2.ImRead(windowName);
- partnum += num;
- // Cv2.AddWeighted(particle, 0, outImage, 1, 0, particle);
- }
- Cv2.ImShow("原始图像", g_srcImage);
- }
- int GetNumber(int input)
- {
- int number = 0;
- while (input > 0)
- {
- if (input != 0)
- {
- number++;
- }
- input = input / 10;
- }
- return number;
- }
- int TinyParticle(Mat image, string filename)
- {
- //灰度化,滤波,Canny边缘检测
- Mat imageGray = new Mat();
- // Cv2.Resize(image, image, new OpenCvSharp.Size(image.Cols / 10, image.Rows / 3), (0.0), (0.0), OpenCvSharp.InterpolationFlags.Area);
- Cv2.PyrMeanShiftFiltering(image, image, 20, 48); //模糊细节,这个参数由颗粒的大小确定
- Cv2.CvtColor(image, imageGray, ColorConversionCodes.BGR2GRAY);//灰度转换
- //区间滤波
- for (int i = 0; i < imageGray.Rows; i++)
- {
- for (int j = 0; j < imageGray.Cols; j++)
- {
- if (imageGray.At<int>(i, j) > 105 && imageGray.At<int>(i, j) < 130)
- {
- imageGray.Set<int>(i, j, 255);
- }
- else
- {
- imageGray.Set<int>(i, j, 0);
- }
- }
- }
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- //轮廓
- Cv2.FindContours(imageGray, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- double maxArea = 0;
- List<double> listArea = new List<double>();
- List<OpenCvSharp.Point[]> paint = new List<OpenCvSharp.Point[]>();
- Random ran = new Random();
- for (int t = 0; t < contours.Length; t++)
- {
- double area = Cv2.ContourArea(contours[t]);
- int p = GetNumber((int)area);
- if (p >= 4)
- {
- int r = ran.Next(0, 255);
- int g = ran.Next(0, 255);
- int b = ran.Next(0, 255);
- Cv2.FillPoly(image, new OpenCvSharp.Point[][] { contours[t] }, new OpenCvSharp.Scalar((byte)b, (byte)g, (byte)r));
- paint.Add(contours[t]);
- }
- listArea.Add(area);
- }
- // Cv2.Resize(image, image, new OpenCvSharp.Size(image.Cols *0.1, image.Rows *0.1), (0.0), (0.0), OpenCvSharp.InterpolationFlags.Area);
- //Cv2.ImShow(filename, image);
- return paint.Count;
- }
- /// <summary>
- /// 分水岭
- /// </summary>
- /// <param name="img"></param>
- /// <returns></returns>
- private Mat GetWatershedSegment(Mat M, out List<List<int>> outdata)
- {
- List<List<OpenCvSharp.Point>> points = new List<List<OpenCvSharp.Point>>();
- particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- relit = new List<int>();
- g_srcImage = new Mat();
- temp = new Mat(); outdata = new List<List<int>>() { };
- Cv2.CvtColor(M, g_srcImage, ColorConversionCodes.BGRA2BGR);
- Mat gray = new Mat();
- Mat binary = new Mat();
- Mat shifted = new Mat(M.Size(), MatType.CV_8UC3);
- //均值漂移 滤波
- // Cv2.PyrMeanShiftFiltering(g_srcImage, shifted, 21, 51);
- Cv2.GaussianBlur(g_srcImage, shifted, new OpenCvSharp.Size(15, 15), 0);
- //灰度图
- Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
- //二值化
- double otsu = Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Otsu/*.Otsu*/);
- // distance transform
- Mat dist = new Mat();
- Cv2.DistanceTransform(binary, dist, DistanceTypes.L2, DistanceMaskSize.Mask3);
- //归一化数据
- Cv2.Normalize(dist, dist, 0, 1, NormTypes.MinMax);
- // binary
- Cv2.Threshold(dist, dist, 0.4, 1, ThresholdTypes.Binary);
- // markers
- Mat dist_m = new Mat();
- dist.ConvertTo(dist_m, MatType.CV_8UC1);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(dist_m, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- // create markers
- Mat markers = Mat.Zeros(g_srcImage.Size(), MatType.CV_32SC1);
- for (int t = 0; t < contours.Length; t++)
- {
- if (Cv2.ContourArea(contours[t]) > markers.Rows * markers.Cols * 0.1)
- {
- continue;
- }
- Cv2.DrawContours(markers, contours, t, new Scalar(t + 1), -1);
- }
- // Cv2.ImShow("分割后", markers);
- Cv2.Circle(markers, new OpenCvSharp.Point(5, 5), 30, new Scalar(255), -1);
- //形体学操作 去掉干扰
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
- Cv2.MorphologyEx(g_srcImage, g_srcImage, MorphTypes.Erode, kernel);
- Cv2.Watershed(g_srcImage, markers);
- // 颜色填充与最终显示
- int index = 0;
- for (int row = 0; row < markers.Rows; row++)
- {
- for (int col = 0; col < markers.Cols; col++)
- {
- index = markers.At<int>(row, col);
- if (index > 0 && index <= contours.Length)
- {
- if (particlePixles.ContainsKey(index))
- {
- particlePixles[index].Add(new OpenCvSharp.Point(col, row));
- }
- else
- {
- List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
- Pixles.Add(new OpenCvSharp.Point(col, row));
- particlePixles.Add(index, Pixles);
- }
- }
- }
- }
- int k = 0;
- foreach (var item in particlePixles)
- {
- if (item.Value.Count > 99999)
- {
- k = item.Key;
- }
- else
- {
- points.Add(item.Value);
- }
- }
- particlePixles.Remove(k);
- //temp = Adjust.BaseImage.BaseTools.MergeMatFromMatArr(temp, vec4B);
- int q = 0;
- int iskailie = 0;
- temp = new Mat(g_srcImage.Rows, g_srcImage.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- int index1 = 0;
- foreach (var item in particlePixles)
- {
- // 将轮廓转为矩形框 , 这个最大的矩形为感兴趣的图像
- Rect rect = Cv2.BoundingRect(item.Value);
- List<OpenCvSharp.Point> pixel = item.Value;
- Mat particle = g_srcImage[rect];
- int ret = 0;
- double area = Cv2.ContourArea(item.Value);
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- List<int> po = new List<int>() { x, y, width, height, (int)area, item.Key };
- outdata.Add(po);
- index1++;
- }
- Cv2.DrawContours(temp, points, -1, new Scalar(255, 0, 0, 255), -1);
- //Mat temp1 = new Mat();
- //Cv2.Erode(temp, temp1, null);
- //temp = temp - temp1;
- using (new Window("temp", WindowMode.Normal, temp))
- {
- Cv2.WaitKey(0);
- }
- return temp;
- Mat after = new Mat();
- Cv2.ConvertScaleAbs(markers, after);
- using (new Window("", WindowMode.Normal, after))
- {
- Cv2.WaitKey(0);
- }
- return after;
- }
- #endregion
- #region 二次球与单晶
- /// <summary>
- /// 获取开裂球
- /// </summary>
- /// <param name="img"></param>
- /// <returns></returns>
- private Mat GetBallAndCrya(Bitmap img, out List<List<int>> outdata)
- {
- particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
- relit = new List<int>();
- g_srcImage = new Mat();
- temp = new Mat();
- outdata = new List<List<int>>() { };
- Mat M = OpenCvSharp.Extensions.BitmapConverter.ToMat(img);
- //M.ConvertTo(g_srcImage, MatType.CV_8UC3);
- Cv2.CvtColor(M, g_srcImage, ColorConversionCodes.BGRA2BGR);
- if (lineList_ball.Count > 0)
- {
- for (int line = 0; line < lineList_ball.Count; line++)
- {
- List<PointF> pointList = lineList_ball[line];
- for (int i = 0; i < pointList.Count - 1; i++)
- {
- Cv2.Line(g_srcImage, new OpenCvSharp.Point() { X = (int)pointList[i].X, Y = (int)pointList[i].Y }, new OpenCvSharp.Point() { X = (int)pointList[i + 1].X, Y = (int)pointList[i + 1].Y }, new Scalar(0, 0, 0), 5);
- }
- }
- }
- //调试方便
- // Cv2.Resize(g_srcImage, g_srcImage,new OpenCvSharp.Size(g_srcImage.Cols / 3, g_srcImage.Rows / 3), (0.0), (0.0), OpenCvSharp.InterpolationFlags.Area);
- Mat gray = new Mat();
- Mat binary = new Mat();
- Mat shifted = new Mat(M.Size(), MatType.CV_8UC3);
- //均值漂移 滤波
- // Cv2.PyrMeanShiftFiltering(g_srcImage, shifted, 21, 51);
- Cv2.GaussianBlur(g_srcImage, shifted, new OpenCvSharp.Size(15, 15), 0);
- //灰度图
- Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
- //二值化
- double otsu = Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Otsu/*.Otsu*/);
- // distance transform
- Mat dist = new Mat();
- Cv2.DistanceTransform(binary, dist, DistanceTypes.L2, DistanceMaskSize.Mask3);
- //归一化数据
- Cv2.Normalize(dist, dist, 0, 1, NormTypes.MinMax);
- // binary
- Cv2.Threshold(dist, dist, 0.4, 1, ThresholdTypes.Binary);
- // markers
- Mat dist_m = new Mat();
- dist.ConvertTo(dist_m, MatType.CV_8UC1);
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
- Cv2.FindContours(dist_m, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
- // create markers
- Mat markers = Mat.Zeros(g_srcImage.Size(), MatType.CV_32SC1);
- for (int t = 0; t < contours.Length; t++)
- {
- Cv2.DrawContours(markers, contours, t, new Scalar(t + 1), -1);
- }
- // Cv2.ImShow("分割后", markers);
- Cv2.Circle(markers, new OpenCvSharp.Point(5, 5), 30, new Scalar(255), -1);
- //形体学操作 去掉干扰
- InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
- Cv2.MorphologyEx(g_srcImage, g_srcImage, MorphTypes.Erode, kernel);
- Cv2.Watershed(g_srcImage, markers);
- // 颜色填充与最终显示
- int index = 0;
- for (int row = 0; row < markers.Rows; row++)
- {
- for (int col = 0; col < markers.Cols; col++)
- {
- index = markers.At<int>(row, col);
- if (index > 0 && index <= contours.Length)
- {
- if (particlePixles.ContainsKey(index))
- {
- particlePixles[index].Add(new OpenCvSharp.Point(col, row));
- }
- else
- {
- List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
- Pixles.Add(new OpenCvSharp.Point(col, row));
- particlePixles.Add(index, Pixles);
- }
- }
- }
- }
- int k = 0;
- foreach (var item in particlePixles)
- {
- if (item.Value.Count > 99999)
- {
- k = item.Key;
- break;
- }
- }
- particlePixles.Remove(k);
- //temp = Adjust.BaseImage.BaseTools.MergeMatFromMatArr(temp, vec4B);
- int q = 0;
- int iskailie = 0;
- temp = new Mat(g_srcImage.Rows, g_srcImage.Cols, MatType.CV_8UC4, new Scalar(0, 0, 0, 0));
- int index1 = 0;
- foreach (var item in particlePixles)
- {
- // 将轮廓转为矩形框 , 这个最大的矩形为感兴趣的图像
- Rect rect = Cv2.BoundingRect(item.Value);
- List<OpenCvSharp.Point> pixel = item.Value;
- Mat particle = g_srcImage[rect];
- Mat back = particle.Clone();
- Mat forwrit = M[rect];
- Mat small = forwrit.Clone();
- long aveg = 0;
- long aveb = 0;
- long aver = 0;
- foreach (var pt in pixel)
- {
- if (kailie_ball.Count > 0)
- {
- PointF p = new PointF() { X = pt.X, Y = pt.Y };
- if (kailie_ball.Contains(p))
- {
- iskailie = 1;
- break;
- }
- }
- if (putong_ball.Count > 0)
- {
- PointF p = new PointF() { X = pt.X, Y = pt.Y };
- if (putong_ball.Contains(p))
- {
- iskailie = 2;
- break;
- }
- }
- aveg += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[0];
- aveb += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[1];
- aver += particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X)[2];
- }
- int ret = 0;
- if (iskailie == 1)
- {
- ret = 1;
- }
- else if (iskailie == 2)
- {
- ret = 0;
- }
- else
- {
- aveg = aveg / pixel.Count;
- aveb = aveb / pixel.Count;
- aver = aver / pixel.Count;
- for (int i = 0; i < back.Cols; i++)
- {
- for (int j = 0; j < back.Rows; j++)
- {
- back.Set<Vec3b>(j, i, new Vec3b((byte)aveg, (byte)aveb, (byte)aver));
- }
- }
- foreach (var pt in pixel)
- {
- back.Set<Vec3b>(pt.Y - rect.Y, pt.X - rect.X, particle.At<Vec3b>(pt.Y - rect.Y, pt.X - rect.X));
- }
- // ret = GetSplit2(back);
- relit.Add(ret);
- }
- if (ret == 1)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(0, 0, 255, 255), 2);
- }
- else if (ret == 0)
- {
- Cv2.DrawContours(temp, new List<List<OpenCvSharp.Point>>() { item.Value }, 0, new Scalar(255, 0, 0, 255), 2);
- }
- double area = Cv2.ContourArea(item.Value);
- int x = rect.X;
- int y = rect.Y;
- int width = rect.Width;
- int height = rect.Height;
- if (kailie_ball.Count > 0)
- {
- for (int i = 0; i < kailie_ball.Count; i++)
- {
- double px = kailie_ball[i].X;
- double py = kailie_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 1;
- relit[index1] = 1;
- break;
- }
- }
- }
- if (putong_ball.Count > 0)
- {
- for (int i = 0; i < putong_ball.Count; i++)
- {
- double px = putong_ball[i].X;
- double py = putong_ball[i].Y;
- if (px > x && px < (x + width) && py > y && py < (y + height))
- {
- ret = 0;
- relit[index1] = 0;
- break;
- }
- }
- }
- List<int> po = new List<int>() { x, y, width, height, (int)area, ret };
- outdata.Add(po);
- index1++;
- }
- Mat temp1 = new Mat();
- Cv2.Erode(temp, temp1, null);
- Cv2.Erode(temp1, temp1, null);
- temp = temp - temp1;
- return temp;
- }
- public void test2(string path)
- {
- using (Mat src = new Mat(path, ImreadModes.AnyColor | ImreadModes.AnyDepth))
- using (Mat dst = new Mat())
- {
- //1:因为霍夫圆检测对噪声比较敏感,所以首先对图像做一个中值滤波或高斯滤波(噪声如果没有可以不做)
- Mat m1 = new Mat();
- Cv2.MedianBlur(src, m1, 3); // ksize必须大于1且是奇数
- //2:转为灰度图像
- 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, 130, 70, 30, 35, 75);
- //CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, int.Parse(textBox14.Text), int.Parse(textBox10.Text), int.Parse(textBox11.Text), int.Parse(textBox12.Text), int.Parse(textBox13.Text));
- CircleSegment[] cs = Cv2.HoughCircles(m2, HoughMethods.Gradient, 1, 80, 70, 30, 30, 50);
- src.CopyTo(dst);
- //大圆
- for (int i = 0; i < cs.Count(); i++)
- {
- //画圆
- Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, (int)cs[i].Radius + 10, new Scalar(0, 0, 255), -1, LineTypes.AntiAlias);
- //加强圆心显示
- Cv2.Circle(dst, (int)cs[i].Center.X, (int)cs[i].Center.Y, 3, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias);
- }
- using (new Window("OutputImage", WindowMode.Normal, src))
- //using (new Window("InputImage", WindowMode.Normal, src))
- {
- Cv2.WaitKey(0);
- }
- Mat oldDst = dst.Clone();
- OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
- HierarchyIndex[] hierarchy;
- Cv2.GaussianBlur(dst, dst, new OpenCvSharp.Size(25, 25), 0, 0, BorderTypes.Default);
- Cv2.Threshold(dst, dst, 140, 255, ThresholdTypes.Binary);
- using (new Window("InputImage", WindowMode.Normal, dst))
- {
- Cv2.WaitKey(0);
- }
- Cv2.FindContours(dst, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- Cv2.CvtColor(oldDst, oldDst, ColorConversionCodes.RGB2BGR);
- Cv2.DrawContours(oldDst, contours, -1, Scalar.Green, -1, LineTypes.Link8, hierarchy, 4, new OpenCvSharp.Point(0, 0));
- using (new Window("InputImage", WindowMode.Normal, oldDst))
- {
- Cv2.WaitKey(0);
- }
- }
- }
- #endregion
- #region 二次球粒径
- /// <summary>
- /// 筛选单晶
- /// </summary>
- /// <returns></returns>
- public List<List<int>> ForgetPrimary(double pointsize)
- {
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 12 });
- action.Lists.Add(new Args() { Key = "pointsize", Value = pointsize });
- action.Lists.Add(new Args() { Key = "border", Value = border });
- action.Lists.Add(new Args() { Key = "HW", Value = HW });
- action.Lists.Add(new Args() { Key = "AreaRatio", Value = AreaRatio });
- action.Lists.Add(new Args() { Key = "Contour", Value = Contour });
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- string newbitmap = subPath + "\\mask.jpg";
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- //newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitDJ), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(parentPrimary, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- /// <summary>
- /// 删除添加单晶
- /// </summary>
- /// <returns></returns>
- public List<List<int>> DeletePrimary(List<PointF> pointFs, List<List<PointF>> addPoints)
- {
- List<List<int>> data = new List<List<int>>() { };
- ProgressThreadProcClass procClass = new ProgressThreadProcClass();
- int itemCount = 100;
- Mat newMat = new Mat();
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- ProgressThreadProcClass.IFileTransferProgressEvents progressEvents = new ProgressThreadProcClass.IFileTransferProgressEvents();
- System.Threading.ThreadStart copyThreadProc =
- delegate ()
- {
- try
- {
- List<List<OpenCvSharp.Point>> AddPoints = new List<List<OpenCvSharp.Point>>();
- if (addPoints.Count > 0)
- {
- for (int i = 0; i < addPoints.Count; i++)
- {
- List<OpenCvSharp.Point> plist = new List<OpenCvSharp.Point>();
- addPoints[i].ForEach(p => plist.Add(new OpenCvSharp.Point((int)p.X, (int)p.Y)));
- AddPoints.Add(plist);
- }
- }
- action.Lists.Add(new Args() { Key = "SelPointFs", Value = -1 });
- action.Lists.Add(new Args() { Key = "imageTypes", Value = 12 });
- action.Lists.Add(new Args() { Key = "DelPointFs", Value = pointFs });
- action.Lists.Add(new Args() { Key = "AddPontins", Value = AddPoints });
- string subPath = System.Configuration.ConfigurationManager.AppSettings["TempPath"];
- string newbitmap = subPath + "\\mask.jpg";
- Mat mask = Cv2.ImRead(newbitmap);
- newMat = this.PerformProcessGetdata(mask, out data);
- //newMat = this.PerformProcessGetdata(OpenCvSharp.Extensions.BitmapConverter.ToMat(bitDJ), out data);
- }
- catch (Exception e)
- {
- }
- finally
- {
- progressEvents.EndOperation(OperationResult.Finished);
- }
- };
- procClass.StartProgressAction(parentPrimary, itemCount, copyThreadProc, progressEvents, null);
- if (bmc != null) { bmc.data = data; bmc.isedit = true; }
- if (bc != null) { bc.data = data; bc.isedit = true; }
- documentWorkspace.PhaseModels[0].mat = newMat;
- documentWorkspace.Refresh();
- return data;
- }
- #endregion
- #region 标尺自动识别
- /// <summary>
- /// 导出图片
- /// </summary>
- /// <returns></returns>
- public Mat MargMat()
- {
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat mat1 = documentWorkspace.phaseModels[0].mat;
- Mat dst = new Mat();
- dst = mat.Clone();
- Mat[] mats = mat1.Split();
- Mat[] arr = mat.Split();
- List<Vec4b> vec4BList = new List<Vec4b>() { new Vec4b(255, 144, 30, 255), new Vec4b(255, 0, 0, 255), 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) };
- List<Vec4b> newlist = new List<Vec4b>();
- Vec4b vec4 = new Vec4b(0, 0, 0, 0);
- for (int i = 0; i < mat1.Cols; i++)
- {
- for (int j = 0; j < mat1.Rows; j++)
- {
- if (mat1.At<Vec4b>(j, i) != vec4)
- {
- dst.Set<Vec4b>(j, i, mat1.At<Vec4b>(j, i));
- }
- else
- {
- dst.Set<Vec4b>(j, i, mat.At<Vec4b>(j, i));
- }
- }
- }
- return dst;
- }
- public static byte[] Bitmap2Byte(Bitmap bitmap)
- {
- using (MemoryStream stream = new MemoryStream())
- {
- bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
- byte[] data = new byte[stream.Length];
- stream.Seek(0, SeekOrigin.Begin);
- stream.Read(data, 0, Convert.ToInt32(stream.Length));
- return data;
- }
- }
- /// <summary>
- /// 根据图片获取标尺
- /// </summary>
- /// <returns></returns>
- public double GetRuler()
- {
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat m = Mat.FromImageData(Bitmap2Byte(bitmap));
- Mat gray = mat.CvtColor(ColorConversionCodes.BGRA2GRAY);
- Mat dst = new Mat();
- Cv2.Threshold(gray, dst, 75, 255, ThresholdTypes.BinaryInv);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(dst, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t.Count()).ToList();
- Rect rect = Cv2.BoundingRect(contoursHoleList[1]);
- Rect rect2 = new Rect(new OpenCvSharp.Point(897, 1026), new OpenCvSharp.Size(639, 31));
- //进行裁剪
- Mat imgRect1 = new Mat(dst, rect2);
- Cv2.Threshold(imgRect1, imgRect1, 0, 255, ThresholdTypes.BinaryInv);
- Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(1, 1));
- Cv2.MorphologyEx(imgRect1, imgRect1, MorphTypes.Close, element);
- int minx = imgRect1.Cols;
- int maxx = 0;
- for (int i = 0; i < imgRect1.Cols; i++)
- {
- int ab = imgRect1.At<int>(3, i);
- if (ab > 0 && i < minx)
- {
- minx = i;
- }
- if (ab > 0 && i > maxx)
- {
- maxx = i;
- }
- }
- int sum = 0;
- for (int i = 0; i < imgRect1.Rows; i++)
- {
- int ab = imgRect1.At<int>(i, maxx);
- if (ab == 0)
- {
- sum++;
- }
- }
- int star = (maxx - minx) / 2 + minx;
- //Rect rect1 = new Rect(star, sum + 3, (maxx - minx) / 2, imgRect1.Rows - sum - 3);
- Cv2.FindContours(imgRect1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- if (contours.Count() > 4)
- {
- contoursHoleList = contours.OrderBy(t => t[0].X).ToList();
- Rect recta = Cv2.BoundingRect(contoursHoleList[1]);
- Rect rectb = Cv2.BoundingRect(contoursHoleList[contoursHoleList.Count - 3]);
- Rect rect1 = new Rect(recta.X, recta.Y, rectb.X - recta.X, recta.Height);
- Mat temp = imgRect1[rect1];
- Rect rectc = Cv2.BoundingRect(contoursHoleList[contoursHoleList.Count - 3]);
- Rect rectd = Cv2.BoundingRect(contoursHoleList[contoursHoleList.Count - 1]);
- Rect rectUnit = new Rect(rectc.X, rectc.Y, rectd.X - rectc.X, rectc.Height);
- Mat tempUnit = imgRect1[rectUnit];
- double unit = GetUnit(tempUnit);
- double d = GetNumForInt2(temp);
- double pix = maxx - minx;
- double ruler = (d * unit) / pix;
- return ruler;
- }
- else
- {
- return 0;
- }
- }
- /// <summary>
- /// 识别数字
- /// </summary>
- /// <param name="temp">需要对比的图片</param>
- /// <returns></returns>
- private int numRecognizer(Mat temp)
- {
- Cv2.BitwiseNot(temp, temp);
- Mat dst = Cv2.ImRead("number.png");
- Mat gray = dst.CvtColor(ColorConversionCodes.BGR2GRAY);
- //第一步找到小数点将图片切开
- OpenCvSharp.Point[][] contours1;
- HierarchyIndex[] hierarchy1;
- Cv2.FindContours(gray, out contours1, out hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHoleList = contours1.OrderBy(t => t[0].X).ToList();
- List<Mat> numList = new List<Mat>();
- for (int i = 0; i < contoursHoleList.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHoleList[i]);
- Mat numMat = gray[num];
- numList.Add(numMat);
- }
- //第一步找到小数点将图片切开
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(temp, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHole = contours.OrderBy(t => t.Count()).ToList();
- int max = 0;
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect rect = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = temp[rect];
- if (contoursHole[i].Count() > 3)
- {
- max = rect.X;
- break;
- }
- }
- Rect cut = new Rect(0, 0, max, temp.Rows);
- temp = temp[cut];
- Cv2.FindContours(temp, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHoleList1 = contours.OrderByDescending(t => t[0].X).ToList();
- int ret = 0;
- for (int i = 0; i < contoursHoleList1.Count(); i++)
- {
- if (contoursHoleList1[i].Count() > 10)
- {
- Rect num = Cv2.BoundingRect(contoursHoleList1[i]);
- Mat numMat = temp[num];
- Cv2.Resize(numMat, numMat, new OpenCvSharp.Size(numList[0].Width, numList[0].Height));
- Mat resultImage = new Mat();
- Cv2.MatchTemplate(numMat, gray, resultImage, TemplateMatchModes.SqDiffNormed);
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 1));
- ret = ret + m * (int)Math.Pow(10, i);
- }
- }
- }
- return ret;
- }
- /// <summary>
- /// 根据图片获取数据
- /// </summary>
- /// <returns></returns>
- public Dictionary<string, string> GetParameter()
- {
- Dictionary<string, string> KeyValues = new Dictionary<string, string>();
- //标尺单位模板纳米和微米
- Mat nm = Cv2.ImRead("xcw/nm.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- //读取原图
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat gray = mat.CvtColor(ColorConversionCodes.BGRA2GRAY);
- Mat dst = new Mat();
- //底下的标签是白色的,二值化找标签
- Cv2.Threshold(gray, dst, 245, 255, ThresholdTypes.Binary);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(dst, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- //找最大白色轮廓就是标签
- List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderByDescending(t => t[0].Y).ToList();
- Mat imgRect1 = new Mat();
- for (int i = 0; i < contoursHoleList.Count; i++)
- {
- if (contoursHoleList[i].Count() > 1000)
- {
- Rect rect = Cv2.BoundingRect(contoursHoleList[i]);
- imgRect1 = new Mat(gray, rect);
- break;
- }
- }
- Cv2.Threshold(imgRect1, imgRect1, 180, 255, ThresholdTypes.BinaryInv);
- #region 标尺识别
- //前5分之一是标尺
- Rect rect1 = new Rect(0, 0, imgRect1.Cols / 5, imgRect1.Rows);
- //进行裁剪`
- Mat mat1 = new Mat(imgRect1, rect1);
- Cv2.FindContours(mat1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> mat1List = contours.OrderByDescending(t => t[0].Y).ToList();
- Rect rectBC = Cv2.BoundingRect(mat1List[0]);
- int widthBC = rectBC.Width;
- mat1List.RemoveAt(0);
- mat1List = mat1List.OrderByDescending(t => t[0].X).ToList();
- Rect nmrect1 = Cv2.BoundingRect(mat1List[1]);
- Rect nmrect2 = Cv2.BoundingRect(mat1List[0]);
- Rect nmrect = new Rect(nmrect1.X, nmrect1.Y, nmrect2.X - nmrect1.X + nmrect2.Width, nmrect1.Height);
- //找标尺单位
- Mat nmMat = imgRect1[nmrect];
- Mat resultImage = new Mat();
- Cv2.MatchTemplate(nmMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- int unio = 0;
- if (x > 100)
- {
- unio = 1000;
- }
- else
- {
- unio = 1;
- }
- nmrect = new Rect(0, 0, nmrect1.X, rectBC.Y);
- mat1 = mat1[nmrect];
- int ret = GetNumForInt(mat1);
- ret = ret * unio;
- KeyValues.Add("rule", ret.ToString());
- #endregion
- #region EHT识别
- //5分之一到5分之2是EHT和WD
- Rect rect2 = new Rect(imgRect1.Cols / 5 + 58, 0, imgRect1.Cols / 5 - 100, imgRect1.Rows / 2);
- //进行裁剪`
- Mat mat2 = new Mat(imgRect1, rect2);
- Cv2.FindContours(mat2, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHole = contours.OrderByDescending(t => t[0].X).ToList();
- nmrect1 = Cv2.BoundingRect(contoursHole[1]);
- nmrect = new Rect(0, 0, nmrect1.X, mat2.Height);
- mat2 = mat2[nmrect];
- double eht = GetNum(mat2);
- KeyValues.Add("eht", eht.ToString());
- #endregion
- #region WD识别
- //5分之一到5分之2是EHT和WD
- Rect rect3 = new Rect(imgRect1.Cols / 5 + 58, imgRect1.Rows / 2, imgRect1.Cols / 5 - 100, imgRect1.Rows / 2);
- //进行裁剪`
- Mat mat3 = new Mat(imgRect1, rect3);
- Cv2.FindContours(mat3, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderByDescending(t => t[0].X).ToList();
- nmrect1 = Cv2.BoundingRect(contoursHole[1]);
- nmrect = new Rect(0, 0, nmrect1.X, mat3.Height);
- mat3 = mat3[nmrect];
- double wd = GetNum(mat3);
- KeyValues.Add("wd", wd.ToString());
- #endregion
- #region Mag识别
- //5分之2到5分之3是Mag
- Rect rect4 = new Rect(imgRect1.Cols * 2 / 5 + 80, imgRect1.Rows / 2, imgRect1.Cols / 5 - 100, imgRect1.Rows / 2);
- //进行裁剪`
- Mat mat4 = imgRect1[rect4];
- Cv2.FindContours(mat4, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderByDescending(t => t[0].X).ToList();
- nmrect1 = Cv2.BoundingRect(contoursHole[1]);
- nmrect = new Rect(0, 0, nmrect1.X, mat4.Height);
- mat4 = mat4[nmrect];
- double mag = GetNum(mat4);
- KeyValues.Add("mag", mag.ToString());
- #endregion
- #region 日期时间
- //5分之3到5分之4是时间imgRect1.Rows / 2
- Rect rect5 = new Rect(imgRect1.Cols * 3 / 5 + 99, 0, imgRect1.Cols / 5 - 95, imgRect1.Rows / 2);
- //进行裁剪`
- Mat mat5 = imgRect1[rect5];
- Cv2.FindContours(mat5, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderBy(t => t[0].X).ToList();
- nmrect1 = Cv2.BoundingRect(contoursHole[2]);
- nmrect = new Rect(0, 0, nmrect1.X, mat5.Height);
- Mat matDD = mat5[nmrect];
- //using (new Window("mat5", WindowMode.Normal, mat5))
- //{
- // Cv2.WaitKey(0);
- //}
- double dateDD = GetNumForInt(matDD);
- nmrect1 = Cv2.BoundingRect(contoursHole[5]);
- nmrect = new Rect(nmrect1.X, 0, mat5.Width - nmrect1.X, mat5.Height);
- Mat matYY = mat5[nmrect];
- double dateYY = GetNumForInt(matYY);
- int endx = nmrect1.X;
- nmrect1 = Cv2.BoundingRect(contoursHole[2]);
- nmrect = new Rect(nmrect1.X, 0, endx - nmrect1.X, mat5.Height);
- Mat matMM = mat5[nmrect];
- string dateMM = GetMonth(matMM);
- rect5 = new Rect(imgRect1.Cols * 3 / 5 + 103, imgRect1.Rows / 2, imgRect1.Cols / 5 - 95, imgRect1.Rows / 2);
- mat5 = imgRect1[rect5];
- Cv2.FindContours(mat5, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderBy(t => t[0].X).ToList();
- nmrect1 = Cv2.BoundingRect(contoursHole[2]);
- nmrect = new Rect(0, 0, nmrect1.X, mat5.Height);
- Mat matHH = mat5[nmrect];
- double dateHH = GetNumForInt(matHH);
- nmrect1 = Cv2.BoundingRect(contoursHole[4]);
- nmrect2 = Cv2.BoundingRect(contoursHole[6]);
- nmrect = new Rect(nmrect1.X, 0, nmrect2.X - nmrect1.X, mat5.Height);
- Mat matmm = mat5[nmrect];
- double datemm = GetNumForInt(matmm);
- nmrect1 = Cv2.BoundingRect(contoursHole[8]);
- nmrect = new Rect(nmrect1.X, 0, mat5.Width - nmrect1.X, mat5.Height);
- Mat matSS = mat5[nmrect];
- double dateSS = GetNumForInt(matSS);
- KeyValues.Add("time", dateYY.ToString() + "-" + dateMM + "-" + dateDD.ToString() + " " + dateHH.ToString() + ":" + datemm.ToString() + ":" + dateSS.ToString());
- //using (new Window("time",WindowMode.Normal, matmm))
- //{
- // Cv2.WaitKey(0);
- //}
- #endregion
- return KeyValues;
- }
- /// <summary>
- /// 金相图片标尺识别
- /// </summary>
- /// <returns></returns>
- public int GetParameter2()
- {
- //标尺单位模板纳米和微米
- Mat nm = Cv2.ImRead("xcw/nm.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- //读取原图
- Bitmap bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem != null ? this.listView1.FocusedItem.Index : this.listView1.SelectedItems[0].Index].CompositionSurface.CreateAliasedBitmap();
- Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
- Mat gray = mat.CvtColor(ColorConversionCodes.BGRA2GRAY);
- Mat dst = new Mat();
- //底下的标签是白色的,二值化找标签
- Cv2.Threshold(gray, dst, 245, 255, ThresholdTypes.Binary);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(dst, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- //找最大白色轮廓就是标签
- List<OpenCvSharp.Point[]> contoursHoleList = contours.OrderBy(t => t[0].Y).ToList();
- Mat imgRect1 = new Mat();
- for (int i = 0; i < contoursHoleList.Count; i++)
- {
- if (contoursHoleList[i].Count() > 100)
- {
- Rect rect = Cv2.BoundingRect(contoursHoleList[i]);
- imgRect1 = new Mat(gray, rect);
- break;
- }
- }
- using (new Window("imgRect1", WindowMode.Normal, imgRect1))
- {
- Cv2.WaitKey(0);
- }
- Cv2.Threshold(imgRect1, imgRect1, 200, 255, ThresholdTypes.BinaryInv);
- Cv2.FindContours(imgRect1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> mat1List = contours.Where(t => t.Count() > 20).OrderByDescending(t => t[0].Y).ToList();
- Rect rectBC = Cv2.BoundingRect(mat1List[0]);
- int widthBC = rectBC.Width;
- mat1List.RemoveAt(0);
- mat1List = mat1List.OrderByDescending(t => t[0].X).ToList();
- Rect nmrect1 = Cv2.BoundingRect(mat1List[1]);
- Rect nmrect2 = Cv2.BoundingRect(mat1List[0]);
- Rect nmrect = new Rect(nmrect1.X, nmrect1.Y, nmrect2.X - nmrect1.X + nmrect2.Width, nmrect1.Height);
- //找标尺单位
- Mat nmMat = imgRect1[nmrect];
- Mat resultImage = new Mat();
- Cv2.MatchTemplate(nmMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- int unio = 0;
- if (x > 100)
- {
- unio = 1000;
- }
- else
- {
- unio = 1;
- }
- nmrect = new Rect(0, 0, nmrect1.X, rectBC.Y);
- imgRect1 = imgRect1[nmrect];
- using (new Window("imgRect1", WindowMode.Normal, imgRect1))
- {
- Cv2.WaitKey(0);
- }
- int ret = GetNumForInt2(imgRect1);
- ret = ret * unio;
- return ret;
- }
- /// <summary>
- /// 识别数字带小数点
- /// </summary>
- /// <param name="temp"></param>
- /// <returns></returns>
- private double GetNum(Mat temp)
- {
- double result = 0;
- Mat nm = Cv2.ImRead("xcw/number.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(temp, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHole = contours.OrderBy(t => t.Count()).ToList();
- //小数点坐标
- int max = 0;
- int maxEnd = 0;
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect rectd = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = temp[rectd];
- if (contoursHole[i].Count() > 3)
- {
- max = rectd.X;
- maxEnd = max + rectd.Width;
- break;
- }
- }
- Rect rectLeft = new Rect(0, 0, max, temp.Height);
- Mat matLeft = temp[rectLeft];
- Cv2.FindContours(matLeft, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderByDescending(t => t[0].X).ToList();
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = matLeft[num];
- Mat resultImage = new Mat();
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.Resize(numMat, numMat, new OpenCvSharp.Size(13, 19));
- Cv2.MatchTemplate(numMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 1));
- result = result + m * Math.Pow(10, i);
- }
- }
- Rect rectRight = new Rect(maxEnd, 0, temp.Width - maxEnd, temp.Height);
- Mat matRight = temp[rectRight];
- Cv2.FindContours(matRight, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- contoursHole = contours.OrderBy(t => t[0].X).ToList();
- double w = 1;
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = matRight[num];
- Mat resultImage = new Mat();
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.Resize(numMat, numMat, new OpenCvSharp.Size(13, 19));
- Cv2.MatchTemplate(numMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- double m = Convert.ToDouble(x.ToString().Substring(0, 1));
- result = result + m * Math.Pow(10, (w) * -1);
- }
- w = w + 1;
- }
- return result;
- }
- /// <summary>
- /// 识别数字不带小数点
- /// </summary>
- /// <param name="temp"></param>
- /// <returns></returns>
- private int GetNumForInt(Mat temp)
- {
- int result = 0;
- Mat nm = Cv2.ImRead("xcw/number.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(temp, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHole = contours.OrderByDescending(t => t[0].X).ToList();
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = temp[num];
- Mat resultImage = new Mat();
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.Resize(numMat, numMat, new OpenCvSharp.Size(13, 19));
- Cv2.MatchTemplate(numMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 1));
- result = result + m * (int)Math.Pow(10, i);
- }
- }
- return result;
- }
- /// <summary>
- /// 识别月份
- /// </summary>
- /// <param name="temp"></param>
- /// <returns></returns>
- private string GetMonth(Mat temp)
- {
- string result = "Jan";
- Mat nm = Cv2.ImRead("xcw/month.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- Mat resultImage = new Mat();
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Rect rect = new Rect(1175, 0, graynm.Width - 1175, graynm.Height);
- Mat mat = graynm[rect];
- Cv2.Resize(temp, temp, new OpenCvSharp.Size(temp.Width * 1.5, temp.Height * 1.5));
- Cv2.MatchTemplate(temp, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- string[] month = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 1));
- result = month[m - 1];
- }
- else if (x > 1000)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 2));
- result = month[m - 1];
- }
- return result;
- }
- /// <summary>
- /// 识别数字不带小数点
- /// </summary>
- /// <param name="temp"></param>
- /// <returns></returns>
- private int GetNumForInt2(Mat temp)
- {
- int result = 0;
- Mat nm = Cv2.ImRead("number2.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- Cv2.Threshold(graynm, graynm, 0, 255, ThresholdTypes.Otsu);
- //第一步找到小数点将图片切开
- OpenCvSharp.Point[][] contours1;
- HierarchyIndex[] hierarchy1;
- Cv2.FindContours(graynm, out contours1, out hierarchy1, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHoleList = contours1.OrderBy(t => t[0].X).ToList();
- List<Mat> numList = new List<Mat>();
- for (int i = 0; i < contoursHoleList.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHoleList[i]);
- Mat numMat = graynm[num];
- numList.Add(numMat);
- }
- OpenCvSharp.Point[][] contours;
- HierarchyIndex[] hierarchy;
- Cv2.FindContours(temp, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone, null);
- List<OpenCvSharp.Point[]> contoursHole = contours.Where(t => t.Count() > 20).OrderByDescending(t => t[0].X).ToList();
- for (int i = 0; i < contoursHole.Count(); i++)
- {
- Rect num = Cv2.BoundingRect(contoursHole[i]);
- Mat numMat = temp[num];
- Mat resultImage = new Mat();
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- //Cv2.Resize(numMat, numMat, new OpenCvSharp.Size(numList[9].Width, numList[9].Height));
- //using (new Window("ss", WindowMode.Normal, numMat))
- //{
- // Cv2.WaitKey(0);
- //}
- Cv2.MatchTemplate(numMat, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- if (x < 1000 && x > 100)
- {
- int m = Convert.ToInt32(x.ToString().Substring(0, 1));
- result = result + m * (int)Math.Pow(10, i);
- }
- }
- return result;
- }
- private double GetUnit(Mat temp)
- {
- //using (new Window("ss",WindowMode.Normal, temp))
- //{
- // Cv2.WaitKey(0);
- //}
- //标尺单位模板纳米和微米
- Mat nm = Cv2.ImRead("nm.png");
- Mat graynm = nm.CvtColor(ColorConversionCodes.BGR2GRAY);
- Mat resultImage = new Mat();
- Cv2.MatchTemplate(temp, graynm, resultImage, TemplateMatchModes.SqDiffNormed);
- double minValue = 0, maxValue = 0;
- OpenCvSharp.Point pointMin = new OpenCvSharp.Point();
- OpenCvSharp.Point pointMax = new OpenCvSharp.Point();
- Cv2.MinMaxLoc(resultImage, out minValue, out maxValue, out pointMin, out pointMax);
- int x = pointMin.X;
- double unio = 0;
- if (x > 100)
- {
- unio = 1;
- }
- else
- {
- unio = 0.001;
- }
- return unio;
- }
- #endregion
- }
- }
|