OTSImageProcess.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116
  1. #pragma once
  2. #include "stdafx.h"
  3. #include <opencv2/core/core.hpp>
  4. #include <opencv2/highgui/highgui.hpp>
  5. #include <opencv2/opencv.hpp>
  6. #include "OTSImageProcess.h"
  7. #include "OTSImageProcessParam.h"
  8. #include <OTSFieldData.h>
  9. #include "../OTSLog/COTSUtilityDllFunExport.h"
  10. #include "FieldMgr.h"
  11. using namespace cv;
  12. using namespace std;
  13. namespace OTSIMGPROC
  14. {
  15. namespace
  16. {
  17. /***** 求两点间距离*****/
  18. float getDistance(Point pointO, Point pointA)
  19. {
  20. float distance;
  21. distance = powf((pointO.x - pointA.x), 2) + powf((pointO.y - pointA.y), 2);
  22. distance = sqrtf(distance);
  23. return distance;
  24. }
  25. /***** 点到直线的距离:P到AB的距离*****/
  26. //P为线外一点,AB为线段两个端点
  27. float getDist_P2L(Point pointP, Point pointA, Point pointB)
  28. {
  29. //求直线方程
  30. int A = 0, B = 0, C = 0;
  31. A = pointA.y - pointB.y;
  32. B = pointB.x - pointA.x;
  33. C = pointA.x*pointB.y - pointA.y*pointB.x;
  34. //代入点到直线距离公式
  35. float distance = 0;
  36. distance = ((float)abs(A*pointP.x + B * pointP.y + C)) / ((float)sqrtf(A*A + B * B));
  37. return distance;
  38. }
  39. int Side(Point P1, Point P2, Point point)
  40. {
  41. /*Point P1 = line.P1;
  42. Point P2 = line.P2;*/
  43. return ((P2.y - P1.y) * point.x + (P1.x - P2.x) * point.y + (P2.x*P1.y - P1.x*P2.y));
  44. }
  45. void FindInnerCircleInContour(vector<Point> contour, Point &center, int &radius)
  46. {
  47. Rect r = boundingRect(contour);
  48. int nL = r.x, nR = r.br().x; //轮廓左右边界
  49. int nT = r.y, nB = r.br().y; //轮廓上下边界
  50. double dist = 0;
  51. double maxdist = 0;
  52. for (int i = nL; i < nR; i++) //列
  53. {
  54. for (int j = nT; j < nB; j++) //行
  55. {
  56. //计算轮廓内部各点到最近轮廓点的距离
  57. dist = pointPolygonTest(contour, Point(i, j), true);
  58. if (dist > maxdist)
  59. {
  60. //求最大距离,只有轮廓最中心的点才距离最大
  61. maxdist = dist;
  62. center = Point(i, j);
  63. }
  64. }
  65. }
  66. radius = maxdist; //圆半径
  67. }
  68. BOOL GetParticleAverageChord(std::vector<Point> listEdge, double a_PixelSize, double &dPartFTD)
  69. {
  70. // safety check
  71. double nx = 0, ny = 0;
  72. Moments mu;
  73. mu = moments(listEdge, false);
  74. nx = mu.m10 / mu.m00;
  75. ny = mu.m01 / mu.m00;
  76. //circle(cvcopyImg, Point(nx, ny), 1, (255), 1);
  77. Point ptCenter = Point((int)nx, (int)ny);
  78. // coordinate transformation
  79. Point ptPosition;
  80. int radiusNum = 0;
  81. // get ferret diameter
  82. double sumFltDiameter = 0;
  83. int interval;
  84. int edgePointNum = listEdge.size();
  85. if (edgePointNum > 10)
  86. {
  87. interval = edgePointNum / 10;//get one line per 10 degree aproxemately
  88. }
  89. else
  90. {
  91. interval = 1;
  92. }
  93. for (int i = 0; i < edgePointNum; i++)
  94. {
  95. Point pt = listEdge[i];
  96. ptPosition.x = abs(pt.x - ptCenter.x);
  97. ptPosition.y = abs(pt.y - ptCenter.y);
  98. if (i % interval == 0)//calculate one line per 10 point ,so to speed up.don't calculate all the diameter.
  99. {
  100. double r1 = sqrt(pow(ptPosition.x, 2) + pow(ptPosition.y, 2));
  101. sumFltDiameter += r1;
  102. radiusNum += 1;
  103. //line(cvImageData, ptCenter, pt, Scalar(nBlackColor), nThickness, nLineType);
  104. }
  105. }
  106. if (radiusNum == 0)
  107. {
  108. dPartFTD = 0;
  109. }
  110. else
  111. {
  112. dPartFTD = a_PixelSize * sumFltDiameter / radiusNum * 2;
  113. }
  114. //imshow("feret center", cvImageData);
  115. return TRUE;
  116. }
  117. void linearSmooth5(WORD wordIn[], WORD wordOut[], int N = 255)//smooth algorithm
  118. {
  119. double in[256];
  120. double out[256];
  121. double smoothCurveData[256];
  122. for (int i = 0; i < 256; i++)
  123. {
  124. in[i] = (double)wordIn[i];
  125. }
  126. int i;
  127. if (N < 5)
  128. {
  129. for (i = 0; i <= N - 1; i++)
  130. {
  131. out[i] = in[i];
  132. }
  133. }
  134. else
  135. {
  136. out[0] = (3.0 * in[0] + 2.0 * in[1] + in[2] - in[4]) / 5.0;
  137. out[1] = (4.0 * in[0] + 3.0 * in[1] + 2 * in[2] + in[3]) / 10.0;
  138. for (i = 2; i <= N - 3; i++)
  139. {
  140. out[i] = (in[i - 2] + in[i - 1] + in[i] + in[i + 1] + in[i + 2]) / 5.0;
  141. }
  142. out[N - 2] = (4.0 * in[N - 1] + 3.0 * in[N - 2] + 2 * in[N - 3] + in[N - 4]) / 10.0;
  143. out[N - 1] = (3.0 * in[N - 1] + 2.0 * in[N - 2] + in[N - 3] - in[N - 5]) / 5.0;
  144. }
  145. for (int i = 0; i < N; i++)
  146. {
  147. wordOut[i] = (WORD)out[i];
  148. }
  149. }
  150. void GetMatricsParticlesFromRawParticle(COTSParticlePtr a_pOTSPart,int imageWidth,int imageHeight, double a_PixelSize, int xrayStep, COTSParticleList& matricsParts)
  151. {
  152. auto originalSegs = a_pOTSPart->GetFeature()->GetSegmentsList();
  153. std::map<int, COTSSegmentsList> segsOnTheSameHeight;
  154. for (auto s : originalSegs)
  155. {
  156. segsOnTheSameHeight[s->GetHeight()].push_back(s);
  157. }
  158. auto rect = a_pOTSPart->GetParticleRect();
  159. std::vector<CPoint> matrixPs;
  160. int colnum = ceil((double)rect.Width() / xrayStep + 0.5);
  161. if (colnum % 2 == 0) colnum += 1;//let the number to be an odd number.Then we can make the middle point in the center of the particle exactly.
  162. int rownum = ceil((double)rect.Height() / xrayStep + 0.5);
  163. if (rownum % 2 == 0) rownum += 1;
  164. CPoint theFirst = CPoint(rect.left-(colnum*xrayStep-rect.Width())/2 + xrayStep / 2, rect.top-(rownum*xrayStep-rect.Height())/2 + xrayStep / 2);
  165. for (int i = 0; i < rownum; i++)
  166. {
  167. for (int j = 0; j < colnum; j++)
  168. {
  169. double x =(double) theFirst.x + (double)j * xrayStep;
  170. double y = (double)theFirst.y + (double)i * xrayStep;
  171. CPoint thePoint = CPoint(x, y);
  172. matrixPs.push_back(thePoint);
  173. }
  174. }
  175. a_pOTSPart->SetXrayMatrixPoints(matrixPs);
  176. for (auto point : matrixPs)
  177. {
  178. COTSParticlePtr part = COTSParticlePtr(new COTSParticle());
  179. COTSSegmentsList segs;
  180. for (int i = 0; i < xrayStep; i++)
  181. {
  182. COTSSegmentPtr seg = COTSSegmentPtr(new COTSSegment());
  183. seg->SetStart(point.x - xrayStep / 2);
  184. seg->SetLength(xrayStep);
  185. seg->SetHeight(point.y - xrayStep / 2 + i);
  186. auto originalSegs = segsOnTheSameHeight[seg->GetHeight()];
  187. int currentH = seg->GetHeight();
  188. int segStart = seg->GetStart();
  189. int segEnd = seg->GetEnd();
  190. for (int i = 0; i < originalSegs.size();i++)//judge if the seg is in the original particle scope.
  191. {
  192. auto rseg = originalSegs[i];
  193. int rsegStart = rseg->GetStart();
  194. int rsegEnd = rseg->GetEnd();
  195. if (segStart > rsegEnd || rsegStart > segEnd)//there's no intersection.is not a valid seg for this original segment.
  196. {
  197. continue;
  198. }
  199. if (segStart>=rsegStart && segEnd <= rsegEnd)//contained in the original segment,is a valid seg.
  200. {
  201. segs.push_back(seg);
  202. continue;
  203. }
  204. else if (segStart>= rsegStart&& segEnd >= rsegEnd)// intersect in the head end.Modify the end of the seg .
  205. {
  206. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  207. newseg->SetStart(segStart);
  208. newseg->SetEnd(rsegEnd);
  209. newseg->SetHeight(currentH);
  210. segs.push_back(newseg);
  211. continue;
  212. }
  213. else if (segStart<= rsegStart&& segEnd >= rsegEnd)
  214. {
  215. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  216. newseg->SetStart(rsegStart);
  217. newseg->SetEnd(rsegEnd);
  218. newseg->SetHeight(currentH);
  219. segs.push_back(newseg);
  220. continue;
  221. }
  222. else if (segStart<= rsegStart&& rsegEnd >= segEnd)
  223. {
  224. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  225. newseg->SetStart(rsegStart);
  226. newseg->SetEnd(segEnd);
  227. newseg->SetHeight(currentH);
  228. segs.push_back(newseg);
  229. continue;
  230. }
  231. }
  232. }
  233. if (segs.size() > 0)
  234. {
  235. part->GetFeature()->SetSegmentsList(segs);
  236. part->CalXRayPos();
  237. part->SetFieldId(a_pOTSPart->GetFieldId());
  238. part->SetAnalysisId(a_pOTSPart->GetAnalysisId());
  239. matricsParts.push_back(part);
  240. }
  241. }
  242. }
  243. }
  244. COTSImageProcess::COTSImageProcess()
  245. {
  246. }
  247. COTSImageProcess::~COTSImageProcess()
  248. {
  249. }
  250. // use verticl line of 3 pixel to erode a image
  251. void COTSImageProcess::BErodeVertical3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  252. {
  253. WORD x, y, wcounts;
  254. if (rows <= 2 || columns <= 2)return;
  255. // top line
  256. for (x = 0; x < columns; x++)
  257. {
  258. *(target + x) = 0;
  259. }
  260. // bottom line
  261. for (x = 0; x < columns; x++)
  262. {
  263. *(target + (DWORD)(rows - 1)*columns + x) = 0;
  264. }
  265. for (y = 1; y<rows - 1; y++)
  266. {
  267. for (x = 0; x<columns; x++)
  268. {
  269. if (*(source + (DWORD)y*columns + x) == 0)
  270. {
  271. *(target + (DWORD)y*columns + x) = 0;
  272. continue;
  273. }
  274. wcounts = 0;
  275. if (*(source + (DWORD)(y - 1)*columns + x) == 255)
  276. {
  277. wcounts++;
  278. }
  279. if (*(source + (DWORD)(y + 1)*columns + x) == 255)
  280. {
  281. wcounts++;
  282. }
  283. if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;
  284. else *(target + (DWORD)y*columns + x) = 0;
  285. }
  286. }
  287. }
  288. // use left 45 degree line of 3 pixel to erode a image
  289. void COTSImageProcess::BErodeLeft45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  290. {
  291. WORD x, y, wcounts;
  292. if (rows <= 2 || columns <= 2)return;
  293. // top line
  294. for (x = 0; x < columns; x++)
  295. {
  296. *(target + x) = 0;
  297. }
  298. // bottom line
  299. for (x = 0; x < columns; x++)
  300. {
  301. *(target + (DWORD)(rows - 1)*columns + x) = 0;
  302. }
  303. // left line
  304. for (y = 0; y<rows; y++)
  305. {
  306. *(target + (DWORD)y*columns) = 0;
  307. }
  308. // right line
  309. for (y = 0; y<rows; y++)
  310. {
  311. *(target + (DWORD)y*columns + columns - 1) = 0;
  312. }
  313. for (y = 1; y < rows - 1; y++)
  314. {
  315. for (x = 1; x < columns - 1; x++)
  316. {
  317. if (*(source + (DWORD)y*columns + x) == 0)
  318. {
  319. *(target + (DWORD)y*columns + x) = 0;
  320. continue;
  321. }
  322. wcounts = 0;
  323. if (*(source + (DWORD)(y - 1)*columns + x - 1) == 255)
  324. {
  325. wcounts++;
  326. }
  327. if (*(source + (DWORD)(y + 1)*columns + x + 1) == 255)
  328. {
  329. wcounts++;
  330. }
  331. if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;
  332. else *(target + (DWORD)y*columns + x) = 0;
  333. }
  334. }
  335. }
  336. // use horizoontal line of 3 pixel to erode a image
  337. void COTSImageProcess::BErodeHorizontal3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  338. {
  339. WORD x, y, wcounts;
  340. if (rows <= 2 || columns <= 2)return;
  341. // left line
  342. for (y = 0; y<rows; y++)
  343. {
  344. *(target + (DWORD)y*columns) = 0;
  345. }
  346. // right line
  347. for (y = 0; y<rows; y++)
  348. {
  349. *(target + (DWORD)y*columns + columns - 1) = 0;
  350. }
  351. for (y = 0; y<rows; y++)
  352. {
  353. for (x = 1; x<columns - 1; x++)
  354. {
  355. if (*(source + (DWORD)y*columns + x) == 0)
  356. {
  357. *(target + (DWORD)y*columns + x) = 0;
  358. continue;
  359. }
  360. wcounts = 0;
  361. if (*(source + (DWORD)y*columns + x - 1) == 255)
  362. {
  363. wcounts++;
  364. }
  365. if (*(source + (DWORD)y*columns + x + 1) == 255)
  366. {
  367. wcounts++;
  368. }
  369. if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;
  370. else *(target + (DWORD)y*columns + x) = 0;
  371. }
  372. }
  373. }
  374. // use right 45 degree line of 3 pixel to erode a image
  375. void COTSImageProcess::BErodeRight45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  376. {
  377. WORD x, y, wcounts;
  378. if (rows <= 2 || columns <= 2)return;
  379. // top line
  380. for (x = 0; x < columns; x++)
  381. {
  382. *(target + x) = 0;
  383. }
  384. // bottom line
  385. for (x = 0; x < columns; x++)
  386. {
  387. *(target + (DWORD)(rows - 1)*columns + x) = 0;
  388. }
  389. // left line
  390. for (y = 0; y<rows; y++)
  391. {
  392. *(target + (DWORD)y*columns) = 0;
  393. }
  394. // right line
  395. for (y = 0; y<rows; y++)
  396. {
  397. *(target + (DWORD)y*columns + columns - 1) = 0;
  398. }
  399. for (y = 1; y<rows - 1; y++)
  400. {
  401. for (x = 1; x<columns - 1; x++)
  402. {
  403. if (*(source + (DWORD)y*columns + x) == 0)
  404. {
  405. *(target + (DWORD)y*columns + x) = 0;
  406. continue;
  407. }
  408. wcounts = 0;
  409. if (*(source + (DWORD)(y - 1)*columns + x + 1) == 255)
  410. {
  411. wcounts++;
  412. }
  413. if (*(source + (DWORD)(y + 1)*columns + x - 1) == 255)
  414. {
  415. wcounts++;
  416. }
  417. if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;
  418. else *(target + (DWORD)y*columns + x) = 0;
  419. }
  420. }
  421. }
  422. void COTSImageProcess::BDilateVertical3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  423. {
  424. WORD x, y;
  425. if (rows <= 2 || columns <= 2)return;
  426. // top line
  427. for (x = 0; x<columns; x++)
  428. {
  429. if (*(source + x) != 0)
  430. {
  431. *(target + x) = 0xff;
  432. }
  433. }
  434. // bottom line
  435. for (x = 0; x<columns; x++)
  436. {
  437. if (*(source + (DWORD)(rows - 1)*columns + x) != 0)
  438. {
  439. *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  440. }
  441. }
  442. for (y = 1; y<rows - 1; y++)
  443. {
  444. for (x = 1; x<columns - 1; x++)
  445. {
  446. if (*(source + (DWORD)y*columns + x) != 0)
  447. {
  448. *(target + (DWORD)y*columns + x) = 0xff;
  449. *(target + (DWORD)(y - 1)*columns + x) = 255;
  450. *(target + (DWORD)(y + 1)*columns + x) = 255;
  451. }
  452. else *(target + (DWORD)y*columns + x) = 0;
  453. }
  454. }
  455. }
  456. void COTSImageProcess::BDilateLeft45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  457. {
  458. WORD x, y;
  459. if (rows <= 2 || columns <= 2)return;
  460. // top line
  461. for (x = 0; x<columns; x++)
  462. {
  463. if (*(source + x) != 0)
  464. {
  465. *(target + x) = 0xff;
  466. }
  467. }
  468. // bottom line
  469. for (x = 0; x<columns; x++)
  470. {
  471. if (*(source + (DWORD)(rows - 1)*columns + x) != 0)
  472. {
  473. *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  474. }
  475. }
  476. // left line
  477. for (y = 0; y<rows; y++)
  478. {
  479. if (*(source + (DWORD)y*columns) != 0)
  480. {
  481. *(target + (DWORD)y*columns) = 0xff;
  482. }
  483. }
  484. // right line
  485. for (y = 0; y<rows; y++)
  486. {
  487. if (*(source + (DWORD)y*columns + columns - 1) != 0)
  488. {
  489. *(target + (DWORD)y*columns + columns - 1) = 0xff;
  490. }
  491. }
  492. for (y = 1; y<rows - 1; y++)
  493. {
  494. for (x = 1; x<columns - 1; x++)
  495. {
  496. if (*(source + (DWORD)y*columns + x) != 0)
  497. {
  498. *(target + (DWORD)y*columns + x) = 0xff;
  499. *(target + (DWORD)(y - 1)*columns + x - 1) = 255;
  500. *(target + (DWORD)(y + 1)*columns + x + 1) = 255;
  501. }
  502. else *(target + (DWORD)y*columns + x) = 0;
  503. }
  504. }
  505. }
  506. void COTSImageProcess::BDilateHorizontal3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  507. {
  508. WORD x, y;
  509. if (rows <= 2 || columns <= 2)return;
  510. // left line
  511. for (y = 0; y<rows; y++)
  512. {
  513. if (*(source + (DWORD)y*columns) != 0)
  514. {
  515. *(target + (DWORD)y*columns) = 0xff;
  516. }
  517. }
  518. // right line
  519. for (y = 0; y<rows; y++)
  520. {
  521. if (*(source + (DWORD)y*columns + columns - 1) != 0)
  522. {
  523. *(target + (DWORD)y*columns + columns - 1) = 0xff;
  524. }
  525. }
  526. for (y = 1; y<rows - 1; y++)
  527. {
  528. for (x = 1; x<columns - 1; x++)
  529. {
  530. if (*(source + (DWORD)y*columns + x) != 0)
  531. {
  532. *(target + (DWORD)y*columns + x) = 0xff;
  533. *(target + (DWORD)y*columns + x - 1) = 255;
  534. *(target + (DWORD)y*columns + x + 1) = 255;
  535. }
  536. else *(target + (DWORD)y*columns + x) = 0;
  537. }
  538. }
  539. }
  540. void COTSImageProcess::BDilateRight45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)
  541. {
  542. WORD x, y;
  543. if (rows <= 2 || columns <= 2)return;
  544. // top line
  545. for (x = 0; x<columns; x++)
  546. {
  547. if (*(source + x) != 0)
  548. {
  549. *(target + x) = 0xff;
  550. }
  551. }
  552. // bottom line
  553. for (x = 0; x<columns; x++)
  554. {
  555. if (*(source + (DWORD)(rows - 1)*columns + x) != 0)
  556. {
  557. *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  558. }
  559. }
  560. // left line
  561. for (y = 0; y<rows; y++)
  562. {
  563. if (*(source + (DWORD)y*columns) != 0)
  564. {
  565. *(target + (DWORD)y*columns) = 0xff;
  566. }
  567. }
  568. // right line
  569. for (y = 0; y<rows; y++)
  570. {
  571. if (*(source + (DWORD)y*columns + columns - 1) != 0)
  572. {
  573. *(target + (DWORD)y*columns + columns - 1) = 0xff;
  574. }
  575. }
  576. for (y = 1; y<rows - 1; y++)
  577. {
  578. for (x = 1; x<columns - 1; x++)
  579. {
  580. if (*(source + (DWORD)y*columns + x) != 0)
  581. {
  582. *(target + (DWORD)y*columns + x) = 0xff;
  583. *(target + (DWORD)(y - 1)*columns + x + 1) = 255;
  584. *(target + (DWORD)(y + 1)*columns + x - 1) = 255;
  585. }
  586. else *(target + (DWORD)y*columns + x) = 0;
  587. }
  588. }
  589. }
  590. void COTSImageProcess::BErode3(LPBYTE source, LPBYTE target, WORD wDegree, WORD rows, WORD columns)
  591. {
  592. WORD x, y, i, j, wcounts;
  593. if (rows == 1 || columns == 1)return;
  594. for (y = 1; y<rows - 1; y++)
  595. {
  596. for (x = 1; x<columns - 1; x++)
  597. {
  598. if (*(source + (DWORD)y*columns + x) == 0)
  599. {
  600. *(target + (DWORD)y*columns + x) = 0;
  601. continue;
  602. }
  603. wcounts = 0;
  604. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  605. {
  606. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  607. {
  608. if (*(source + (DWORD)i*columns + j) == 0)
  609. {
  610. wcounts++;
  611. }
  612. }
  613. }
  614. if (wcounts >= wDegree) *(target + (DWORD)y*columns + x) = 0;
  615. else *(target + (DWORD)y*columns + x) = 0xff;
  616. }
  617. }
  618. // top line
  619. for (x = 1; x<columns - (WORD)1; x++)
  620. {
  621. if (*(source + x) == 0)
  622. {
  623. *(target + x) = 0;
  624. continue;
  625. }
  626. wcounts = 0;
  627. for (i = 0; i <= 1; i++)
  628. {
  629. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  630. {
  631. if (*(source + (DWORD)i*columns + j) == 0) wcounts++;
  632. }
  633. }
  634. if (wcounts >= wDegree * 5 / 8) *(target + x) = 0;
  635. else *(target + x) = 0xff;
  636. }
  637. // bottom line
  638. for (x = 1; x<columns - 1; x++)
  639. {
  640. if (*(source + (DWORD)(rows - 1)*columns + x) == 0)
  641. {
  642. *(target + (DWORD)(rows - 1)*columns + x) = 0;
  643. continue;
  644. }
  645. wcounts = 0;
  646. for (i = (WORD)(rows - 2); i <= (WORD)(rows - 1); i++)
  647. {
  648. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  649. {
  650. if (*(source + (DWORD)i*columns + j) == 0) wcounts++;
  651. }
  652. }
  653. if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)(rows - 1)*columns + x) = 0;
  654. else *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  655. }
  656. // left line
  657. for (y = 1; y<rows - 1; y++)
  658. {
  659. if (*(source + (DWORD)y*columns) == 0)
  660. {
  661. *(target + (DWORD)y*columns) = 0;
  662. continue;
  663. }
  664. wcounts = 0;
  665. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  666. {
  667. for (j = 0; j <= 1; j++)
  668. {
  669. if (*(source + (DWORD)i*columns + j) == 0) wcounts++;
  670. }
  671. }
  672. if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)y*columns) = 0;
  673. else *(target + (DWORD)y*columns) = 0xff;
  674. }
  675. // right line
  676. for (y = 1; y<rows - 1; y++)
  677. {
  678. if (*(source + (DWORD)y*columns + columns - 1) == 0)
  679. {
  680. *(target + (DWORD)y*columns + columns - 1) = 0;
  681. continue;
  682. }
  683. wcounts = 0;
  684. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  685. {
  686. for (j = (WORD)(columns - 2); j <= (WORD)(columns - 1); j++)
  687. {
  688. if (*(source + (DWORD)i*columns + j) == 0) wcounts++;
  689. }
  690. }
  691. if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)y*columns + columns - 1) = 0;
  692. else *(target + (DWORD)y*columns + columns - 1) = 0xff;
  693. }
  694. return;
  695. }
  696. void COTSImageProcess::BDilate3(LPBYTE source, LPBYTE target, WORD wDegree, WORD rows, WORD columns)
  697. {
  698. WORD x, y, i, j, wcounts;
  699. for (y = 1; y<rows - 1; y++)
  700. {
  701. for (x = 1; x<columns - 1; x++)
  702. {
  703. if (*(source + (DWORD)y*columns + x) != 0)
  704. {
  705. *(target + (DWORD)y*columns + x) = 0xff;
  706. continue;
  707. }
  708. wcounts = 0;
  709. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  710. {
  711. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  712. {
  713. if (*(source + (DWORD)i*columns + j) != 0) wcounts++;
  714. }
  715. }
  716. if (wcounts >= wDegree) *(target + (DWORD)y*columns + x) = 0xff;
  717. else *(target + (DWORD)y*columns + x) = 0;
  718. }
  719. }
  720. // top line
  721. for (x = 1; x<columns - 1; x++)
  722. {
  723. if (*(source + x) != 0)
  724. {
  725. *(target + x) = 0xff;
  726. continue;
  727. }
  728. wcounts = 0;
  729. for (i = 0; i <= 1; i++)
  730. {
  731. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  732. {
  733. if (*(source + (DWORD)i*columns + j) != 0) wcounts++;
  734. }
  735. }
  736. if (wcounts >= wDegree * 5 / 8) // but does not mater, as we have border of 2 now
  737. {
  738. *(target + x) = 0xff;
  739. }
  740. else { *(target + x) = 0; }
  741. }
  742. // bottom line
  743. for (x = 1; x<columns - 1; x++)
  744. {
  745. if (*(source + (DWORD)(rows - 1)*columns + x) != 0)
  746. {
  747. *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  748. continue;
  749. }
  750. wcounts = 0;
  751. for (i = (WORD)(rows - 2); i <= (WORD)(rows - 1); i++)
  752. {
  753. for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)
  754. {
  755. if (*(source + (DWORD)i*columns + j) != 0) wcounts++;
  756. }
  757. }
  758. if (wcounts > wDegree * 5 / 8)
  759. {
  760. *(target + (DWORD)(rows - 1)*columns + x) = 0xff;
  761. }
  762. else
  763. {
  764. *(target + (DWORD)(rows - 1)*columns + x) = 0;
  765. }
  766. }
  767. // left line
  768. for (y = 1; y<rows - 1; y++)
  769. {
  770. if (*(source + (DWORD)y*columns) != 0)
  771. {
  772. *(target + (DWORD)y*columns) = 0xff;
  773. continue;
  774. }
  775. wcounts = 0;
  776. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  777. {
  778. for (j = 0; j <= (WORD)1; j++)
  779. {
  780. if (*(source + (DWORD)i*columns + j) != 0) wcounts++;
  781. }
  782. }
  783. if (wcounts >= wDegree * 5 / 8)
  784. {
  785. *(target + (DWORD)y*columns) = 0xff;
  786. }
  787. else
  788. {
  789. *(target + (DWORD)y*columns) = 0;
  790. }
  791. }
  792. // right line
  793. for (y = 1; y<rows - 1; y++)
  794. {
  795. if (*(source + (DWORD)y*columns + columns - 1) != 0)
  796. {
  797. *(target + (DWORD)y*columns + columns - 1) = 0xff;
  798. continue;
  799. }
  800. wcounts = 0;
  801. for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)
  802. {
  803. for (j = (WORD)(columns - 2); j <= (WORD)(columns - 1); j++)
  804. {
  805. if (*(source + (DWORD)i*columns + j) != 0) wcounts++;
  806. }
  807. }
  808. if (wcounts >= wDegree * 5 / 8)
  809. {
  810. *(target + (DWORD)y*columns + columns - 1) = 0xff;
  811. }
  812. else
  813. {
  814. *(target + (DWORD)y*columns + columns - 1) = 0;
  815. }
  816. }
  817. // four cornor points treated separately here
  818. // top-left
  819. if (*(source) != 0)
  820. {
  821. *target = 0xff;
  822. }
  823. else
  824. {
  825. wcounts = 0;
  826. if (*(source + 1) != 0) wcounts++;
  827. if (*(source + columns) != 0) wcounts++;
  828. if (*(source + columns + 1) != 0) wcounts++;
  829. // if (wcounts >= wDegree*3/8) // this is a bug here - interger division
  830. if (wcounts * 8 >= wDegree * 3)
  831. {
  832. *target = 0xff;
  833. }
  834. else
  835. {
  836. *target = 0;
  837. }
  838. }
  839. //top-right
  840. if (*(source + columns - 1) != 0)
  841. {
  842. *(target + columns - 1) = 0xff;
  843. }
  844. else
  845. {
  846. wcounts = 0;
  847. if (*(source + columns - 2) != 0) wcounts++;
  848. if (*(source + columns * 2 - 1) != 0) wcounts++;
  849. if (*(source + columns * 2 - 2) != 0) wcounts++;
  850. // if (wcounts >= wDegree*3/8) // this is a bug here - interger division
  851. if (wcounts * 8 >= wDegree * 3)
  852. {
  853. *(target + columns - 1) = 0xff;
  854. }
  855. else
  856. {
  857. *(target + columns - 1) = 0;
  858. }
  859. }
  860. //bottom-left
  861. if (*(source + (DWORD)columns * (rows - 1)) != 0)
  862. {
  863. *(target + (DWORD)columns * (rows - 1)) = 0xff;
  864. }
  865. else
  866. {
  867. wcounts = 0;
  868. if (*(source + (DWORD)columns * (rows - 1) + 1) != 0) wcounts++;
  869. if (*(source + (DWORD)columns * (rows - 2)) != 0) wcounts++;
  870. if (*(source + (DWORD)columns * (rows - 2) + 1) != 0) wcounts++;
  871. // if (wcounts >= wDegree*3/8) // this is a bug here - interger division
  872. if (wcounts * 8 >= wDegree * 3)
  873. {
  874. *(target + (DWORD)columns * (rows - 1)) = 0xff;
  875. }
  876. else
  877. {
  878. *(target + (DWORD)columns * (rows - 1)) = 0;
  879. }
  880. }
  881. //bottom-right
  882. if (*(source + (DWORD)columns * rows - 1) != 0)
  883. {
  884. *(target + (DWORD)columns * rows - 1) = 0xff;
  885. }
  886. else
  887. {
  888. wcounts = 0;
  889. if (*(source + (DWORD)columns * rows - 2) != 0) wcounts++;
  890. if (*(source + (DWORD)columns * (rows - 1) - 2) != 0) wcounts++;
  891. if (*(source + (DWORD)columns * (rows - 1) - 1) != 0) wcounts++;
  892. // if (wcounts >= wDegree*3/8) // this is a bug here - interger division
  893. if (wcounts * 8 >= wDegree * 3)
  894. {
  895. *(target + (DWORD)columns * rows - 1) = 0xff;
  896. }
  897. else
  898. {
  899. *(target + (DWORD)columns * rows - 1) = 0;
  900. }
  901. }
  902. return;
  903. }
  904. // ReZoom the picture with re-magnification
  905. BOOL COTSImageProcess::ReZoom(CString InPutPath, CString OutPutPath)
  906. {
  907. Mat cvSrcImg;
  908. string strInputPath;
  909. strInputPath = CStringA(InPutPath);
  910. // Pictures loop in folder
  911. std::vector<cv::String> ImageFolder;
  912. cv::glob(strInputPath, ImageFolder);
  913. if (ImageFolder.size() == 0)
  914. {
  915. return FALSE;
  916. }
  917. for (unsigned int nImgNum = 0; nImgNum < ImageFolder.size(); ++nImgNum) {
  918. cvSrcImg = cv::imread(ImageFolder[nImgNum], CV_LOAD_IMAGE_GRAYSCALE);
  919. // Image convolution operation
  920. //// convolution kernel
  921. float kernel[] = { -1, -1 , -1, -1 , 0, -1, -1 , -1 , -1 };
  922. cv::Mat ker = cv::Mat(nImage_Size, nImage_Size, CV_32F, &kernel);
  923. cv::Mat cvDstImg = cv::Mat(cvSrcImg.size(), cvSrcImg.type());
  924. // anchor of the kernel
  925. cv::Point anchor(-1, -1);
  926. cv::filter2D(cvSrcImg, cvDstImg, CV_32F, ker, anchor, delta, cv::THRESH_TRUNC);
  927. // Maximum Pixel Value
  928. cvDstImg = abs(cvDstImg);
  929. double minVal, maxVal;
  930. minMaxLoc(cvDstImg, &minVal, &maxVal);
  931. // Grayscale image
  932. int nReduce;
  933. Mat onesImg = Mat::ones(cvDstImg.rows, cvDstImg.cols, CV_32F) * (int)minVal;
  934. absdiff(cvDstImg, onesImg, cvDstImg);
  935. nReduce = (int)maxVal - minVal;
  936. cvDstImg = cvDstImg * nBlackColor / nReduce;
  937. // Output image convert data to int
  938. cvDstImg.convertTo(cvDstImg, CV_8U);
  939. // Process the picture to 128 pixels
  940. resize(cvDstImg, cvDstImg, Size(nPictureSize, nPictureSize));
  941. threshold(cvDstImg, cvDstImg, nProcessParam, nBlackColor, CV_THRESH_BINARY);
  942. string strOutPutPath;
  943. strOutPutPath = CStringA(OutPutPath);
  944. imwrite(strOutPutPath , cvDstImg);
  945. }
  946. return TRUE;
  947. }
  948. BOOL COTSImageProcess::RemoveBSEImageBG(CBSEImgPtr m_pBSEImg, COTSImageProcessParamPtr a_pImgProcessParam,COTSFieldDataPtr m_pFieldData)
  949. {
  950. ASSERT(m_pFieldData);
  951. if (!m_pFieldData)
  952. {
  953. LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no field data"));
  954. return FALSE;
  955. }
  956. ASSERT(m_pBSEImg);
  957. if (!m_pBSEImg)
  958. {
  959. LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no image data"));
  960. return FALSE;
  961. }
  962. ASSERT(a_pImgProcessParam);
  963. if (!a_pImgProcessParam)
  964. {
  965. LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no image process data"));
  966. return FALSE;
  967. }
  968. int nWidthImg = m_pBSEImg->GetWidth();
  969. int nHeightImg = m_pBSEImg->GetHeight();
  970. m_pFieldData->Width = nWidthImg;
  971. m_pFieldData->Height = nHeightImg;
  972. long nImgSize = nWidthImg * nHeightImg;
  973. BYTE* pSrcImg = m_pBSEImg->GetImageDataPointer();
  974. BYTE* pTempImg = new BYTE[nImgSize];
  975. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  976. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  977. long nNumParticle = 0;
  978. RemoveBackGround(m_pBSEImg, a_pImgProcessParam, imgNoBGBinary,nNumParticle);
  979. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  980. long nPtStart = a_pImgProcessParam->GetParticleGray().GetStart();
  981. long nPtEnd = a_pImgProcessParam->GetParticleGray().GetEnd();
  982. if (nNumParticle == 0)
  983. {
  984. COTSParticleList listParticleEmpty;
  985. listParticleEmpty.clear();
  986. m_pFieldData->SetParticleList(listParticleEmpty);
  987. }
  988. else
  989. {
  990. // get the area image
  991. Mat blurImg;
  992. Mat srcImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  993. //medianBlur(srcImg, blurImg, 3);//smooth the edge
  994. COTSParticleList listParticleOut;
  995. if (!GetParticles(0,0,nWidthImg, nHeightImg, srcImg.data, listParticleOut))
  996. {
  997. COTSParticleList listParticleEmpty;
  998. listParticleEmpty.clear();
  999. m_pFieldData->SetParticleList(listParticleEmpty);
  1000. }
  1001. // form a image only have particles on
  1002. COTSSegmentsList listImage;
  1003. for (auto pParticle : listParticleOut)
  1004. {
  1005. COTSFeaturePtr pFeature = pParticle->GetFeature();
  1006. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  1007. long nPixelNum = 0;
  1008. long nPixelAll = 0;
  1009. int nStartS = 0;
  1010. int nHeightS = 0;
  1011. int nLengthS = 0;
  1012. for (auto pSegment : listSegment)
  1013. {
  1014. // update image list
  1015. COTSSegmentPtr pSegNew = COTSSegmentPtr(new COTSSegment(*pSegment.get()));
  1016. listImage.push_back(pSegNew);
  1017. // get particle average gray
  1018. nStartS = pSegment->GetStart();
  1019. nHeightS = pSegment->GetHeight();
  1020. nLengthS = pSegment->GetLength();
  1021. nPixelNum += (long)nLengthS;
  1022. if (nHeightS > nHeightImg)
  1023. {
  1024. LogErrorTrace(__FILE__, __LINE__, _T("seg height is wrong."));
  1025. return FALSE;
  1026. }
  1027. if ((nStartS + nLengthS - 1) > nWidthImg)
  1028. {
  1029. LogErrorTrace(__FILE__, __LINE__, _T("seg starst and length is wrong."));
  1030. return FALSE;
  1031. }
  1032. for (unsigned int i = 0; i < nLengthS; i++)
  1033. {
  1034. if ((nStartS + i) > nWidthImg)
  1035. {
  1036. LogErrorTrace(__FILE__, __LINE__, _T("seg start is wrong."));
  1037. return FALSE;
  1038. }
  1039. else if (nHeightS > nHeightImg)
  1040. {
  1041. LogErrorTrace(__FILE__, __LINE__, _T("seg height is wrong."));
  1042. return FALSE;
  1043. }
  1044. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  1045. nPixelAll += nValueTemp;
  1046. }
  1047. }
  1048. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  1049. pParticle->SetAveGray(nAveGray);
  1050. pParticle->SetActualArea(nPixelNum);
  1051. }
  1052. m_pFieldData->SetParticleList(listParticleOut);
  1053. }
  1054. delete[]pTempImg;
  1055. return TRUE;
  1056. }
  1057. BOOL COTSImageProcess::RemoveBGByFindContour(CBSEImgPtr m_pBSEImg, COTSImageProcessParamPtr a_pImageProcessParam, COTSFieldDataPtr m_pFieldData)
  1058. {
  1059. ASSERT(m_pFieldData);
  1060. ASSERT(m_pBSEImg);
  1061. ASSERT(a_pImageProcessParam);
  1062. int nWidthImg = m_pBSEImg->GetWidth();
  1063. int nHeightImg = m_pBSEImg->GetHeight();
  1064. m_pFieldData->Width = nWidthImg;
  1065. m_pFieldData->Height = nHeightImg;
  1066. long nImgSize = nWidthImg * nHeightImg;
  1067. BYTE* pSrcImg = m_pBSEImg->GetImageDataPointer();
  1068. BYTE* pTempImg = new BYTE[nImgSize];
  1069. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  1070. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  1071. long nNumParticle = 0;
  1072. RemoveBackGround(m_pBSEImg, a_pImageProcessParam, imgNoBGBinary, nNumParticle);
  1073. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  1074. long nPtStart = a_pImageProcessParam->GetParticleGray().GetStart();
  1075. long nPtEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  1076. if (nNumParticle == 0)
  1077. {
  1078. COTSParticleList listParticleEmpty;
  1079. listParticleEmpty.clear();
  1080. m_pFieldData->SetParticleList(listParticleEmpty);
  1081. }
  1082. else
  1083. {
  1084. // get the area image
  1085. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  1086. vector<vector<Point>>contours;
  1087. findContours(cvcopyImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  1088. COTSParticleList listParticleOut;
  1089. for (size_t i = 0; i < contours.size(); i++)
  1090. {
  1091. Rect rectMax = boundingRect(contours[i]);
  1092. Mat rectROI = cvcopyImg(rectMax).clone();
  1093. //exclude the point which intersect into this bounding box but is not in this contour.
  1094. for (int nX = 0; nX < rectROI.rows; nX++)
  1095. {
  1096. for (int nY = 0; nY < rectROI.cols; nY++)
  1097. {
  1098. double localPos = pointPolygonTest(contours[i], Point2f(nX + rectMax.x, nY + rectMax.y), false);
  1099. if (localPos == -1)
  1100. {
  1101. rectROI.data[nX, nY] = 0;//set the value to 0,so we won't consider it when we find segment and feature in this ROI.
  1102. }
  1103. }
  1104. }
  1105. GetParticles(rectMax.x, rectMax.y, rectMax.width, rectMax.height, rectROI.data, listParticleOut);
  1106. }
  1107. // form a image only have particles on
  1108. //COTSSegmentsList listImage;
  1109. for (auto pParticle : listParticleOut)
  1110. {
  1111. COTSFeaturePtr pFeature = pParticle->GetFeature();
  1112. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  1113. long nPixelNum = 0;
  1114. long nPixelAll = 0;
  1115. int nStartS = 0;
  1116. int nHeightS = 0;
  1117. int nLengthS = 0;
  1118. for (auto pSegment : listSegment)
  1119. {
  1120. // get particle average gray
  1121. nStartS = pSegment->GetStart();
  1122. nHeightS = pSegment->GetHeight();
  1123. nLengthS = pSegment->GetLength();
  1124. nPixelNum += (long)nLengthS;
  1125. for (unsigned int i = 0; i < nLengthS; i++)
  1126. {
  1127. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  1128. nPixelAll += nValueTemp;
  1129. }
  1130. }
  1131. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  1132. pParticle->SetAveGray(nAveGray);
  1133. pParticle->SetActualArea(nPixelNum);
  1134. }
  1135. m_pFieldData->SetParticleList(listParticleOut);
  1136. }
  1137. delete[]pTempImg;
  1138. return TRUE;
  1139. }
  1140. BOOL COTSImageProcess::RemoveBGByCVconnectivities(CBSEImgPtr inBSEImg, COTSImageProcessParamPtr a_pImageProcessParam,double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  1141. {
  1142. ASSERT(m_pFieldData);
  1143. ASSERT(inBSEImg);
  1144. ASSERT(a_pImageProcessParam);
  1145. int nWidthImg = inBSEImg->GetWidth();
  1146. int nHeightImg = inBSEImg->GetHeight();
  1147. m_pFieldData->Width = nWidthImg;
  1148. m_pFieldData->Height = nHeightImg;
  1149. long nImgSize = nWidthImg * nHeightImg;
  1150. BYTE* pSrcImg = inBSEImg->GetImageDataPointer();
  1151. BYTE* pTempImg = new BYTE[nImgSize];
  1152. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  1153. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  1154. long nNumParticle = 0;
  1155. RemoveBackGround(inBSEImg, a_pImageProcessParam, imgNoBGBinary, nNumParticle);
  1156. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  1157. long nPtStart = a_pImageProcessParam->GetParticleGray().GetStart();
  1158. long nPtEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  1159. if (nNumParticle == 0)
  1160. {
  1161. COTSParticleList listParticleEmpty;
  1162. listParticleEmpty.clear();
  1163. m_pFieldData->SetParticleList(listParticleEmpty);
  1164. }
  1165. else
  1166. {
  1167. // get the area image
  1168. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  1169. //Mat blurImg;
  1170. //medianBlur(cvcopyImg, blurImg, 5);//get rid of the noise point.
  1171. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  1172. Mat stats, centroids;
  1173. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  1174. double rMin = a_pImageProcessParam->GetIncArea().GetStart()/2.0;
  1175. double rMax = a_pImageProcessParam->GetIncArea().GetEnd()/2.0;
  1176. double partAreaMin = rMin * rMin * 3.14159;
  1177. double partAreaMax = rMax * rMax * 3.14159;
  1178. COTSParticleList listParticleOut;
  1179. for (size_t i = 1; i < number; i++)
  1180. {
  1181. int center_x = centroids.at<double>(i, 0);
  1182. int center_y = centroids.at<double>(i, 1);
  1183. //矩形边框
  1184. int x = stats.at<int>(i, CC_STAT_LEFT);
  1185. int y = stats.at<int>(i, CC_STAT_TOP);
  1186. int w = stats.at<int>(i, CC_STAT_WIDTH);
  1187. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  1188. int area = stats.at<int>(i, CC_STAT_AREA);
  1189. double actualArea = area * a_pixelSize * a_pixelSize;
  1190. if (actualArea >= partAreaMin && actualArea < partAreaMax)
  1191. {
  1192. Rect rectMax = Rect(x, y, w, h);
  1193. Mat rectROI = labels(rectMax).clone();
  1194. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  1195. //exclude the point which intersect into this bounding box but is not in this group.
  1196. int label = i;
  1197. for (int row = 0; row < rectROI.rows; row++)
  1198. {
  1199. for (int col = 0; col < rectROI.cols; col++)
  1200. {
  1201. int v = rectROI.at<int>(row, col);
  1202. if (v == label)
  1203. {
  1204. imageROI.at<uchar>(row, col) = 255;//set the value to 255,so we won't consider other pixel when we find segment and feature in this ROI.
  1205. }
  1206. }
  1207. }
  1208. COTSParticleList roiParts;
  1209. if (GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  1210. {
  1211. if (roiParts.size() > 0)
  1212. {
  1213. COTSParticlePtr roiPart = roiParts[0];//we will find only one part in the roi.
  1214. roiPart->SetXRayPos(CPoint(center_x, center_y));
  1215. CRect r = CRect(x, y, x + w, y + h);
  1216. roiPart->SetParticleRect(r);
  1217. roiPart->SetActualArea(actualArea);
  1218. roiPart->SetPixelArea(area);
  1219. listParticleOut.push_back(roiPart);
  1220. }
  1221. }
  1222. }
  1223. }
  1224. int nTagId;
  1225. for (auto pParticle : listParticleOut)
  1226. {
  1227. COTSFeaturePtr pFeature = pParticle->GetFeature();
  1228. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  1229. long nPixelNum = 0;
  1230. long nPixelAll = 0;
  1231. int nStartS = 0;
  1232. int nHeightS = 0;
  1233. int nLengthS = 0;
  1234. for (auto pSegment : listSegment)
  1235. {
  1236. // get particle average gray
  1237. nStartS = pSegment->GetStart();
  1238. nHeightS = pSegment->GetHeight();
  1239. nLengthS = pSegment->GetLength();
  1240. nPixelNum += (long)nLengthS;
  1241. for (unsigned int i = 0; i < nLengthS; i++)
  1242. {
  1243. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  1244. nPixelAll += nValueTemp;
  1245. }
  1246. }
  1247. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  1248. pParticle->SetAveGray(nAveGray);
  1249. }
  1250. m_pFieldData->SetParticleList(listParticleOut);
  1251. }
  1252. delete[]pTempImg;
  1253. return TRUE;
  1254. }
  1255. BOOL COTSImageProcess::GetParticlesBySpecialGrayRange(CBSEImgPtr a_pBSEImg, CIntRangePtr a_grayRange,CDoubleRangePtr a_diameterRange,double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  1256. {
  1257. ASSERT(m_pFieldData);
  1258. ASSERT(a_pBSEImg);
  1259. ASSERT(a_grayRange);
  1260. int nWidthImg = a_pBSEImg->GetWidth();
  1261. int nHeightImg = a_pBSEImg->GetHeight();
  1262. m_pFieldData->Width = nWidthImg;
  1263. m_pFieldData->Height = nHeightImg;
  1264. long nImgSize = nWidthImg * nHeightImg;
  1265. BYTE* pSrcImg = a_pBSEImg->GetImageDataPointer();
  1266. BYTE* pTempImg = new BYTE[nImgSize];
  1267. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  1268. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  1269. long nNumParticle = 0;
  1270. GetSpecialGrayRangeImage(a_pBSEImg, a_grayRange, imgNoBGBinary, nNumParticle);
  1271. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  1272. if (nNumParticle == 0)
  1273. {
  1274. COTSParticleList listParticleEmpty;
  1275. listParticleEmpty.clear();
  1276. m_pFieldData->SetParticleList(listParticleEmpty);
  1277. }
  1278. else
  1279. {
  1280. // get the area image
  1281. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  1282. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  1283. Mat stats, centroids;
  1284. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  1285. double rStart = a_diameterRange->GetStart() / 2.0;
  1286. double rEnd = a_diameterRange->GetEnd() / 2.0;
  1287. double areaStart = rStart * rStart * 3.14159;
  1288. double areaEnd = rEnd * rEnd * 3.14159;
  1289. COTSParticleList listParticleOut;
  1290. for (size_t i = 1; i < number; i++)
  1291. {
  1292. int center_x = centroids.at<double>(i, 0);
  1293. int center_y = centroids.at<double>(i, 1);
  1294. //矩形边框
  1295. int x = stats.at<int>(i, CC_STAT_LEFT);
  1296. int y = stats.at<int>(i, CC_STAT_TOP);
  1297. int w = stats.at<int>(i, CC_STAT_WIDTH);
  1298. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  1299. int area = stats.at<int>(i, CC_STAT_AREA);
  1300. double actualArea = area * a_pixelSize * a_pixelSize;
  1301. if (actualArea >= areaStart && actualArea < areaEnd)
  1302. {
  1303. Rect rectMax = Rect(x, y, w, h);
  1304. Mat rectROI = labels(rectMax).clone();
  1305. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  1306. //exclude the point which intersect into this bounding box but is not in this group.
  1307. int label = i;
  1308. for (int row = 0; row < rectROI.rows; row++)
  1309. {
  1310. for (int col = 0; col < rectROI.cols; col++)
  1311. {
  1312. int v = rectROI.at<int>(row, col);
  1313. if (v == label)
  1314. {
  1315. imageROI.at<uchar>(row, col) = 255;
  1316. }
  1317. }
  1318. }
  1319. COTSParticleList roiParts;
  1320. if (!GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  1321. {
  1322. continue;
  1323. }
  1324. if (roiParts.size() > 0)
  1325. {
  1326. COTSParticlePtr roiPart = roiParts[0];
  1327. roiPart->SetXRayPos(CPoint(center_x, center_y));
  1328. CRect r = CRect(x, y, x + w, y + h);
  1329. roiPart->SetParticleRect(r);
  1330. roiPart->SetActualArea(actualArea);
  1331. roiPart->SetPixelArea(area);
  1332. listParticleOut.push_back(roiPart);
  1333. }
  1334. }
  1335. }
  1336. // form a image only have particles on
  1337. //COTSSegmentsList listImage;
  1338. for (auto pParticle : listParticleOut)
  1339. {
  1340. int area = pParticle->GetActualArea();
  1341. double pActualArea = area ;
  1342. COTSFeaturePtr pFeature = pParticle->GetFeature();
  1343. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  1344. long nPixelNum = 0;
  1345. long nPixelAll = 0;
  1346. int nStartS = 0;
  1347. int nHeightS = 0;
  1348. int nLengthS = 0;
  1349. for (auto pSegment : listSegment)
  1350. {
  1351. // get particle average gray
  1352. nStartS = pSegment->GetStart();
  1353. nHeightS = pSegment->GetHeight();
  1354. nLengthS = pSegment->GetLength();
  1355. nPixelNum += (long)nLengthS;
  1356. for (unsigned int i = 0; i < nLengthS; i++)
  1357. {
  1358. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  1359. nPixelAll += nValueTemp;
  1360. }
  1361. }
  1362. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  1363. pParticle->SetAveGray(nAveGray);
  1364. }
  1365. m_pFieldData->SetParticleList(listParticleOut);
  1366. }
  1367. delete[]pTempImg;
  1368. return TRUE;
  1369. }
  1370. CIntRangePtr COTSImageProcess::CalBackground(CBSEImgPtr m_pBSEImg)
  1371. {
  1372. auto ranges = CalcuGrayLevelRange(m_pBSEImg);
  1373. return ranges[0];
  1374. }
  1375. std::vector<CIntRangePtr> COTSImageProcess::CalcuGrayLevelRange(CBSEImgPtr m_pBSEImg)
  1376. {
  1377. CIntRangePtr pBackground = CIntRangePtr(new CIntRange());
  1378. WORD originChartData[MAXBYTE];
  1379. WORD firstSmoothChart[MAXBYTE];
  1380. WORD secondSmooth[MAXBYTE];
  1381. //1. get chart data
  1382. m_pBSEImg->SetChartData();
  1383. memcpy(originChartData, m_pBSEImg->GetBSEChart(), sizeof(WORD) * MAXBYTE);
  1384. originChartData[0] = 0;
  1385. originChartData[254] = 0;
  1386. linearSmooth5(originChartData, firstSmoothChart, MAXBYTE);
  1387. linearSmooth5(firstSmoothChart, secondSmooth, MAXBYTE);
  1388. linearSmooth5(secondSmooth, secondSmooth, MAXBYTE);
  1389. linearSmooth5(secondSmooth, secondSmooth, MAXBYTE);
  1390. linearSmooth5(secondSmooth, secondSmooth, MAXBYTE);
  1391. //2. get down edge
  1392. int nLengthEdge = MAXBYTE + 2;
  1393. WORD n_aBSEChart[MAXBYTE + 2];
  1394. memset(n_aBSEChart, 0, sizeof(WORD) * nLengthEdge);
  1395. std::map<long, std::vector<int>> peakMap;// hold all the peaks in this spectrum which are sorted by there area.
  1396. std::vector<int> currentUpSeries;
  1397. std::vector<int> currentPeakSeries;
  1398. // make sure the wave begin with up edge and end with down edge
  1399. n_aBSEChart[0] = 0;
  1400. n_aBSEChart[nLengthEdge - 1] = 0;
  1401. memcpy(&n_aBSEChart[1], &secondSmooth, sizeof(WORD) * MAXBYTE);
  1402. int nLengthCom = MAXBYTE + 1;
  1403. // up edge
  1404. for (int i = 0; i < nLengthCom; i++)
  1405. {
  1406. if (n_aBSEChart[i] <= n_aBSEChart[i + 1])//this is a upward edge
  1407. {
  1408. if (currentPeakSeries.size() > 0)
  1409. {
  1410. int seriesSize = currentPeakSeries.size();
  1411. long area = 0;
  1412. for (int i = 0; i < seriesSize; i++)
  1413. {
  1414. area = area + n_aBSEChart[currentPeakSeries[i]];
  1415. }
  1416. peakMap[area] = currentPeakSeries;
  1417. currentPeakSeries.clear();
  1418. }
  1419. currentUpSeries.push_back(i + 1);// save all the continuous up edge
  1420. }
  1421. else//this is a downward edge
  1422. {
  1423. // encounter a downward edge means upward edge series end,
  1424. if (currentUpSeries.size() > 0)
  1425. {
  1426. currentPeakSeries = currentUpSeries;
  1427. currentUpSeries.clear();
  1428. }
  1429. currentPeakSeries.push_back(i + 1);
  1430. }
  1431. }
  1432. if (currentPeakSeries.size() > 0)
  1433. {
  1434. int seriesSize = currentPeakSeries.size();
  1435. long area = 0;
  1436. for (int i = 0; i < seriesSize; i++)
  1437. {
  1438. area = area + n_aBSEChart[currentPeakSeries[i]];
  1439. }
  1440. peakMap[area] = currentPeakSeries;
  1441. currentPeakSeries.clear();
  1442. }
  1443. std::vector<CIntRangePtr> ranges;
  1444. std::map<long, std::vector<int>>::reverse_iterator it;
  1445. for (it=peakMap.rbegin();it!=peakMap.rend();it++)
  1446. {
  1447. CIntRangePtr pRange = CIntRangePtr(new CIntRange());
  1448. pRange->SetStart(it->second[0]);
  1449. pRange->SetEnd(it->second[it->second.size()-1]);
  1450. ranges.push_back(pRange);
  1451. }
  1452. return ranges;
  1453. }
  1454. void COTSImageProcess::GetSpecialGrayRangeImage(CBSEImgPtr a_pImgIn, CIntRangePtr a_SpecialGrayRange, CBSEImgPtr a_pBinImgOut, long& foundedPixelNum)
  1455. {
  1456. // the background pixel will be 0,and the other part will be 255.
  1457. ASSERT(a_pImgIn);
  1458. int nWidthImg = a_pImgIn->GetWidth();
  1459. int nHeightImg = a_pImgIn->GetHeight();
  1460. long nImgSize = nWidthImg * nHeightImg;
  1461. BYTE* pTempImg = new BYTE[nImgSize];
  1462. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  1463. BYTE* pPixel = new byte[nImgSize];
  1464. long nBGStart;
  1465. long nBGEnd;
  1466. long nNumParticle = 0;
  1467. nBGStart = a_SpecialGrayRange->GetStart();
  1468. nBGEnd = a_SpecialGrayRange->GetEnd();
  1469. // delete background
  1470. for (unsigned int i = 0; i < nImgSize; i++)
  1471. {
  1472. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  1473. {
  1474. pPixel[i] = 255;
  1475. nNumParticle++;
  1476. }
  1477. else
  1478. {
  1479. pPixel[i] = 0;
  1480. }
  1481. }
  1482. //Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);// use the medianblur method to achieve the same effect as open morphology(errod and dialate).
  1483. //pPixel = cvcopyImg.data;
  1484. COTSImageProcess::BErode3(pPixel, pTempImg, 5, nHeightImg, nWidthImg);
  1485. COTSImageProcess::BDilate3(pTempImg, pPixel, 5, nHeightImg, nWidthImg);
  1486. a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);
  1487. foundedPixelNum = nNumParticle;
  1488. delete[] pTempImg;
  1489. return;
  1490. }
  1491. void COTSImageProcess::RemoveBackGround(CBSEImgPtr a_pImgIn, COTSImageProcessParamPtr a_pImageProcessParam, CBSEImgPtr a_pBinImgOut,long& foundedPixelNum)
  1492. {
  1493. // the background pixel will be 0,and the other part will be 255.
  1494. ASSERT(a_pImgIn);
  1495. ASSERT(a_pImageProcessParam);
  1496. int nWidthImg = a_pImgIn->GetWidth();
  1497. int nHeightImg = a_pImgIn->GetHeight();
  1498. long nImgSize = nWidthImg * nHeightImg;
  1499. BYTE* pTempImg = new BYTE[nImgSize];
  1500. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  1501. BYTE* pPixel = new byte[nImgSize];
  1502. long nBGStart;
  1503. long nBGEnd;
  1504. long nPartStart;
  1505. long nPartEnd;
  1506. long nNumParticle = 0;
  1507. if (a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL)
  1508. {
  1509. nBGStart = a_pImageProcessParam->GetBGGray().GetStart();
  1510. nBGEnd = a_pImageProcessParam->GetBGGray().GetEnd();
  1511. nPartStart = a_pImageProcessParam->GetParticleGray().GetStart();
  1512. nPartEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  1513. // delete background
  1514. for (unsigned int i = 0; i < nImgSize; i++)
  1515. {
  1516. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  1517. {
  1518. pPixel[i] = 0;
  1519. }
  1520. else
  1521. {
  1522. pPixel[i] = 255;
  1523. nNumParticle++;
  1524. }
  1525. if (pSrcImg[i]<nPartStart || pSrcImg[i]>nPartEnd)
  1526. {
  1527. pPixel[i] = 0;
  1528. }
  1529. }
  1530. int errodDilateParam = a_pImageProcessParam->GetErrodDilateParam();
  1531. if (errodDilateParam > 0)
  1532. {
  1533. COTSImageProcess::BErode3(pPixel, pTempImg, errodDilateParam, nHeightImg, nWidthImg);
  1534. COTSImageProcess::BDilate3(pTempImg, pPixel, errodDilateParam, nHeightImg, nWidthImg);
  1535. }
  1536. //Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);// use the medianblur method to achieve the same effect as open morphology(errod and dialate).
  1537. //medianBlur(cvcopyImg, cvcopyImg, 5);
  1538. //pPixel = cvcopyImg.data;
  1539. }
  1540. else
  1541. {
  1542. auto range = CalBackground(a_pImgIn);
  1543. nBGStart = range->GetStart();
  1544. nBGEnd = range->GetEnd();
  1545. switch (a_pImageProcessParam->GetAutoBGRemoveType())
  1546. {
  1547. case OTS_AUTOBGREMOVE_TYPE::DOWNWARD:
  1548. for (unsigned int i = 0; i < nImgSize; i++)
  1549. {
  1550. if (pSrcImg[i] <= nBGEnd)
  1551. {
  1552. pPixel[i] = 0;
  1553. }
  1554. else
  1555. {
  1556. pPixel[i] = 255;
  1557. nNumParticle++;
  1558. }
  1559. }
  1560. break;
  1561. case OTS_AUTOBGREMOVE_TYPE::UPWARD:
  1562. for (unsigned int i = 0; i < nImgSize; i++)
  1563. {
  1564. if (pSrcImg[i] >= nBGStart)
  1565. {
  1566. pPixel[i] = 0;
  1567. }
  1568. else
  1569. {
  1570. pPixel[i] = 255;
  1571. nNumParticle++;
  1572. }
  1573. }
  1574. break;
  1575. case OTS_AUTOBGREMOVE_TYPE::MIDDLE:
  1576. for (unsigned int i = 0; i < nImgSize; i++)
  1577. {
  1578. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  1579. {
  1580. pPixel[i] = 0;
  1581. }
  1582. else
  1583. {
  1584. pPixel[i] = 255;
  1585. nNumParticle++;
  1586. }
  1587. }
  1588. break;
  1589. default:
  1590. break;
  1591. }
  1592. int errodDilateParam = a_pImageProcessParam->GetErrodDilateParam();
  1593. if (errodDilateParam > 0)
  1594. {
  1595. COTSImageProcess::BErode3(pPixel, pTempImg, errodDilateParam, nHeightImg, nWidthImg);
  1596. COTSImageProcess::BDilate3(pTempImg, pPixel, errodDilateParam, nHeightImg, nWidthImg);
  1597. }
  1598. /*Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  1599. medianBlur(cvcopyImg, cvcopyImg, 5);
  1600. pPixel = cvcopyImg.data;*/
  1601. }
  1602. a_pBinImgOut->SetImageData(pPixel,nWidthImg,nHeightImg);
  1603. foundedPixelNum = nNumParticle;
  1604. delete[] pTempImg;
  1605. return ;
  1606. }
  1607. BOOL COTSImageProcess::GetParticles(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  1608. {
  1609. ASSERT(a_pPixel);
  1610. if (!a_pPixel)
  1611. {
  1612. return FALSE;
  1613. }
  1614. //a_listParticles.clear();
  1615. COTSParticleList findedParts;
  1616. COTSSegmentsList listSegment;
  1617. listSegment.clear();
  1618. //1. get segment line by line
  1619. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  1620. {
  1621. return FALSE;
  1622. }
  1623. if ((int)listSegment.size() == 0)
  1624. {
  1625. return FALSE;
  1626. }
  1627. //2. save the temp feature
  1628. COTSFeatureList listFeature;
  1629. listFeature.clear();
  1630. if (!GetFeatureList(listSegment, listFeature))//get every feature for all the particle,the complete feature.
  1631. {
  1632. return FALSE;
  1633. }
  1634. if ((int)listFeature.size() == 0)
  1635. {
  1636. return FALSE;
  1637. }
  1638. /*COTSParticleList listParticles;
  1639. listParticles.clear();*/
  1640. if (!ChangeFeaturelist(listFeature, findedParts))
  1641. {
  1642. return FALSE;
  1643. }
  1644. for (auto f : findedParts)
  1645. {
  1646. a_listParticles.push_back(f);
  1647. }
  1648. return TRUE;
  1649. }
  1650. BOOL COTSImageProcess::GetOneParticleFromROI(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  1651. {
  1652. ASSERT(a_pPixel);
  1653. if (!a_pPixel)
  1654. {
  1655. return FALSE;
  1656. }
  1657. //a_listParticles.clear();
  1658. COTSParticleList findedParts;
  1659. COTSSegmentsList listSegment;
  1660. listSegment.clear();
  1661. //1. get segment line by line
  1662. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  1663. {
  1664. return FALSE;
  1665. }
  1666. if ((int)listSegment.size() == 0)
  1667. {
  1668. return FALSE;
  1669. }
  1670. //2. save the temp feature
  1671. COTSFeatureList listFeature;
  1672. listFeature.clear();
  1673. COTSFeaturePtr fea = COTSFeaturePtr(new COTSFeature());
  1674. fea->SetSegmentsList(listSegment);
  1675. listFeature.push_back(fea);
  1676. if ((int)listFeature.size() == 0)
  1677. {
  1678. return FALSE;
  1679. }
  1680. if (!ChangeFeaturelist(listFeature, findedParts))
  1681. {
  1682. return FALSE;
  1683. }
  1684. for (auto f : findedParts)
  1685. {
  1686. a_listParticles.push_back(f);
  1687. }
  1688. return TRUE;
  1689. }
  1690. BOOL COTSImageProcess::GetSegmentList(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSSegmentsList& a_listSegments)
  1691. {
  1692. ASSERT(a_pPixel);
  1693. long nImgSize = a_nWidth * a_nHeight;
  1694. a_listSegments.clear();
  1695. //1. get segment line by line
  1696. long nLine, nm, nn;
  1697. long nStart = 0, nLength = 0;
  1698. for (nLine = 0; nLine < a_nHeight; nLine++)
  1699. {
  1700. for (nm = 0; nm < a_nWidth; nm += (nLength + 1))
  1701. {
  1702. nLength = 0;
  1703. // get start
  1704. if (*(a_pPixel + nLine * a_nWidth + nm) != 0)
  1705. {
  1706. nStart = nm;
  1707. nLength++;
  1708. //get length
  1709. for (nn = nm + 1; nn < a_nWidth; nn++)
  1710. {
  1711. // check if segment is over, break
  1712. if (nLength != 0)
  1713. {
  1714. if (*(a_pPixel + nLine * a_nWidth + nn) == 0)
  1715. break;
  1716. }
  1717. if (*(a_pPixel + nLine * a_nWidth + nn) != 0)
  1718. {
  1719. nLength++;
  1720. }
  1721. }
  1722. // generate segment
  1723. COTSSegmentPtr pSegment = COTSSegmentPtr(new COTSSegment(nLine + top, nStart + left, nLength));
  1724. a_listSegments.push_back(pSegment);
  1725. }
  1726. else
  1727. {
  1728. continue;
  1729. }
  1730. }
  1731. }
  1732. if ((int)a_listSegments.size() == 0)
  1733. {
  1734. //LogErrorTrace(__FILE__, __LINE__, _T("no particle is found."));
  1735. return FALSE;
  1736. }
  1737. return TRUE;
  1738. }
  1739. BOOL COTSImageProcess::GetFeatureList(COTSSegmentsList& a_listSegments, COTSFeatureList& a_listFeatures)
  1740. {
  1741. COTSSegmentsList listSegmentNew;
  1742. std::map<long, COTSSegmentsList > mapOneLineSegments;
  1743. for each (auto s in a_listSegments)
  1744. {
  1745. mapOneLineSegments[s->GetHeight()].push_back(s);//sorting all the segments base on the line number.
  1746. }
  1747. std::map<long, COTSSegmentsList >::iterator lineItr = mapOneLineSegments.begin();//find the highest line
  1748. while (lineItr != mapOneLineSegments.end())
  1749. {
  1750. for (auto s = lineItr->second.begin(); s < lineItr->second.end(); )//find one segment of this line.
  1751. {
  1752. COTSSegmentPtr bottomSeg = *s;
  1753. listSegmentNew.clear();
  1754. listSegmentNew.push_back(*s);
  1755. s = lineItr->second.erase(s);
  1756. std::map<long, COTSSegmentsList >::iterator tempItr = lineItr;
  1757. tempItr++;
  1758. for (; tempItr != mapOneLineSegments.end(); tempItr++)//find all other lines of segments
  1759. {
  1760. if (tempItr->first - bottomSeg->GetHeight() > 1)
  1761. {
  1762. break;
  1763. }
  1764. for (auto nextLineSegment = tempItr->second.begin(); nextLineSegment < tempItr->second.end();)//find next line's all segments
  1765. {
  1766. if (((*nextLineSegment)->GetStart() - (bottomSeg->GetStart() + bottomSeg->GetLength())) > 1)
  1767. {
  1768. break;
  1769. }
  1770. if (bottomSeg->UpDownConection(**nextLineSegment))
  1771. {
  1772. listSegmentNew.push_back(*nextLineSegment);
  1773. bottomSeg = *nextLineSegment;
  1774. nextLineSegment = tempItr->second.erase(nextLineSegment);
  1775. break;
  1776. }
  1777. if (tempItr->second.size() > 0)
  1778. {
  1779. nextLineSegment++;
  1780. }
  1781. else
  1782. {
  1783. break;
  1784. }
  1785. }
  1786. }
  1787. COTSFeaturePtr pFeature = COTSFeaturePtr(new COTSFeature());
  1788. pFeature->SetSegmentsList(listSegmentNew);
  1789. //check if this new feature is connected with other found feature.
  1790. COTSSegmentPtr topSeg = listSegmentNew[0];//find the toppest segment of this new feature.
  1791. COTSSegmentPtr bottomSegment = listSegmentNew[listSegmentNew.size() - 1];//find the lowest segment of this new feature.
  1792. bool haveMerged = false;
  1793. for each (auto f in a_listFeatures)
  1794. {
  1795. for (auto seg : f->GetSegmentsList())
  1796. {
  1797. if (bottomSegment->UpDownConection(*seg) || topSeg->UpDownConection(*seg))
  1798. {
  1799. COTSSegmentsList segs = f->GetSegmentsList();
  1800. for (auto s : listSegmentNew)
  1801. {
  1802. segs.push_back(s);
  1803. }
  1804. f->SetSegmentsList(segs);
  1805. haveMerged = true;
  1806. break;
  1807. }
  1808. }
  1809. if (haveMerged)
  1810. {
  1811. break;
  1812. }
  1813. }
  1814. if (!haveMerged)
  1815. {
  1816. a_listFeatures.push_back(pFeature);
  1817. }
  1818. if (lineItr->second.size() == 0)
  1819. {
  1820. break;
  1821. }
  1822. }
  1823. lineItr++;
  1824. }
  1825. return true;
  1826. }
  1827. BOOL COTSImageProcess::ChangeFeaturelist(COTSFeatureList& a_listFeatures, COTSParticleList& a_listParticle)
  1828. {
  1829. for (auto pFeature : a_listFeatures)
  1830. {
  1831. COTSParticlePtr pParticle = COTSParticlePtr(new COTSParticle());
  1832. pParticle->SetFeature(pFeature);
  1833. a_listParticle.push_back(pParticle);
  1834. }
  1835. if ((int)a_listParticle.size() == 0)
  1836. {
  1837. return FALSE;
  1838. }
  1839. return TRUE;
  1840. }
  1841. BOOL COTSImageProcess::CalcuParticleImagePropertes(COTSParticlePtr a_pOTSPart, double a_PixelSize)
  1842. {
  1843. //--------- convert this particle data to image data,construct an image only with this particle.------
  1844. const int nExpand_Size = 3;
  1845. const int nWhiteColor = 0;
  1846. const int nThickness = 1;
  1847. // lineType Type of the line
  1848. const int nLineType = 8;
  1849. // get rectangle of the particle
  1850. CRect rect = a_pOTSPart->GetParticleRect();
  1851. if (a_pOTSPart->GetActualArea() < 30 * a_PixelSize)// the particle is too small that openCV can't calculate a width value of it. Then we take the upright rect of the particle as it's minArea rect.
  1852. {
  1853. double w = 0, h = 0;
  1854. w = (double)rect.Width()*a_PixelSize;
  1855. h = (double)rect.Height()*a_PixelSize;
  1856. a_pOTSPart->SetDMax(MAX(w, h));
  1857. a_pOTSPart->SetDMin(MIN(w, h));
  1858. a_pOTSPart->SetDMean((w + h) / 2);
  1859. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  1860. a_pOTSPart->SetDElong(MAX(w, h));
  1861. a_pOTSPart->SetPerimeter((w+h)*2);
  1862. a_pOTSPart->SetDPerp(MIN(w, h));
  1863. a_pOTSPart->SetDInscr(MIN(w, h));
  1864. return true;
  1865. }
  1866. // calculate the particle image data size, expand 3 pixel at the edge
  1867. Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size , rect.Width() + nExpand_Size , CV_8U);
  1868. // get the segment list
  1869. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  1870. for (auto pSegment : listSegment)
  1871. {
  1872. int nStart = pSegment->GetStart() - rect.left + nExpand_Size;
  1873. int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;
  1874. int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;
  1875. line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);
  1876. }
  1877. //--------abstract the contour of the particle.
  1878. Mat cvcopyImg;
  1879. medianBlur(particleImage, cvcopyImg, 5);//smooth the edge
  1880. vector<vector<Point>>contours;
  1881. findContours(cvcopyImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  1882. if (contours.size()==0)// the particle is too odd that openCV can't find a contour of it. Then we take the upright rect of the particle as it's minArea rect.
  1883. {
  1884. double w = 0, h = 0;
  1885. w = (double)rect.Width()*a_PixelSize;
  1886. h = (double)rect.Height()*a_PixelSize;
  1887. a_pOTSPart->SetDMax(MAX(w, h));
  1888. a_pOTSPart->SetDMin(MIN(w, h));
  1889. a_pOTSPart->SetDMean((w + h) / 2);
  1890. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  1891. a_pOTSPart->SetDElong(MAX(w, h));
  1892. a_pOTSPart->SetPerimeter((w + h) * 2);
  1893. a_pOTSPart->SetDPerp(MIN(w, h));
  1894. a_pOTSPart->SetDInscr(MIN(w, h));
  1895. return true;
  1896. }
  1897. int imaxcontour = 0, imax = 0;
  1898. for (unsigned int i = 0; i < contours.size(); i++) {
  1899. int itmp = contourArea(contours[i]);
  1900. if (imaxcontour < itmp) {
  1901. imax = i;
  1902. imaxcontour = itmp;
  1903. }
  1904. }
  1905. vector<Point > listEdge = contours[imax];
  1906. vector<vector<Point>>Outcontours;
  1907. Outcontours.push_back(listEdge);
  1908. //---------calculate the minimium rectangle
  1909. auto rRect = cv::minAreaRect(listEdge);
  1910. Point2f p[4];
  1911. rRect.points(p);
  1912. int D_MIN =getDistance(p[0], p[1]);
  1913. int D_MinRecLen = 0;//minareaRect's length(the lenger side).
  1914. for (int j = 0; j <= 2; j++)
  1915. {
  1916. //line(cvContourImg, p[j], p[(j + 1) % 4], Scalar(100, 100, 0), 2);
  1917. int d = getDistance(p[j], p[j + 1]);
  1918. if (d < D_MIN)
  1919. {
  1920. D_MIN = d;
  1921. }
  1922. if (d > D_MinRecLen)
  1923. {
  1924. D_MinRecLen = d;
  1925. }
  1926. }
  1927. a_pOTSPart->SetDMin(D_MIN*a_PixelSize);
  1928. a_pOTSPart->SetOrientation(rRect.angle);
  1929. //----------calculate the perimeter
  1930. double d = arcLength(listEdge, true);
  1931. a_pOTSPart->SetPerimeter(d*a_PixelSize);
  1932. //-----------calculate the Max Diameter. Find the min enclosing circle first ,then find the two farthest circle connected point.
  1933. Point2f center; float radius;
  1934. minEnclosingCircle(listEdge, center, radius);
  1935. //circle(cvContourImg, center, radius, Scalar(100), 2);
  1936. std::vector <Point> outContour = listEdge;
  1937. std::vector <Point> rst;
  1938. for (unsigned int k = 0; k < outContour.size(); k++)
  1939. {
  1940. Point p = outContour[k];
  1941. double d = sqrt(pow((p.x - center.x), 2) + pow((p.y - center.y), 2));
  1942. if (fabs(d - radius) < 0.01)
  1943. {
  1944. rst.push_back(p);
  1945. }
  1946. }
  1947. double D_MAX = 0;
  1948. Point lineDmax[2];
  1949. for (unsigned int m = 0; m < rst.size(); m++)
  1950. {
  1951. Point p = rst[m];
  1952. for (unsigned int n = m + 1; n < rst.size(); n++)
  1953. {
  1954. Point p1 = rst[n];
  1955. double d = sqrt(powf((p.x - p1.x), 2) + powf((p.y - p1.y), 2));
  1956. if (d > D_MAX)
  1957. {
  1958. D_MAX = d;
  1959. lineDmax[0] = p;
  1960. lineDmax[1] = p1;
  1961. }
  1962. }
  1963. }
  1964. a_pOTSPart->SetDMax(D_MAX*a_PixelSize);
  1965. //--------calculate the D_PERP property using the D_MAX's two endpoints.
  1966. std::vector<Point> curve1;
  1967. std::vector<Point> curve2;
  1968. for (unsigned int i = 0; i < outContour.size(); i++)
  1969. {
  1970. Point pt = outContour[i];
  1971. bool start = false;
  1972. int clockwise = Side(lineDmax[0], lineDmax[1], pt);// devide these points into two group ,separate into the two sides.
  1973. if (clockwise > 0)
  1974. {
  1975. curve1.push_back(pt);
  1976. }
  1977. else
  1978. {
  1979. curve2.push_back(pt);
  1980. }
  1981. }
  1982. double d_perp1 = 0, d_perp2 = 0;
  1983. for (unsigned int i = 0; i < curve1.size(); i++)
  1984. {
  1985. double d = getDist_P2L(curve1[i], lineDmax[0], lineDmax[1]);
  1986. if (d > d_perp1)
  1987. {
  1988. d_perp1 = d;
  1989. }
  1990. }
  1991. for (unsigned int i = 0; i < curve2.size(); i++)
  1992. {
  1993. double d = getDist_P2L(curve2[i], lineDmax[0], lineDmax[1]);
  1994. if (d > d_perp2)
  1995. {
  1996. d_perp2 = d;
  1997. }
  1998. }
  1999. a_pOTSPart->SetDPerp((d_perp1 + d_perp2)*a_PixelSize);
  2000. //----------find the diameter of max inscribed circle
  2001. int r;
  2002. Point inscribeCirclecenter;
  2003. FindInnerCircleInContour(outContour, inscribeCirclecenter, r);
  2004. //--------------------------------------------------------calculate the xraypos !
  2005. CRect rec = a_pOTSPart->GetParticleRect();
  2006. a_pOTSPart->SetXRayPos(CPoint(inscribeCirclecenter.x - nExpand_Size + rec.left - 1, inscribeCirclecenter.y - nExpand_Size + rec.top - 1));
  2007. a_pOTSPart->SetDInscr(r * 2 * a_PixelSize);
  2008. //---------------calculate the image other caracater: length/width realArea/minRectangeArea etc. we can use these propertes to do forward process.
  2009. double minRectArea = D_MIN * D_MinRecLen*a_PixelSize*a_PixelSize;//最小外接矩形面积
  2010. double fillRatio = a_pOTSPart->GetActualArea() / minRectArea;//实际面积与最小外接矩形面积比,that's the fill rate.
  2011. double lengthWidthRatio;
  2012. lengthWidthRatio = (double)D_MinRecLen / D_MIN;//长宽比
  2013. //decide if this shape is a strip shape :if the lenthWidthRatio>2 then it is. if the lengthWidthRatio<2 and the areaRatio<0.5 then it is.
  2014. bool isStripShape = false;
  2015. double curveLength = 0;
  2016. double D_MEAN=0;
  2017. Moments mu;
  2018. mu = moments(listEdge, false);
  2019. int nx = mu.m10 / mu.m00;
  2020. int ny = mu.m01 / mu.m00;
  2021. //circle(cvcopyImg, Point(nx, ny), 1, (255), 1);
  2022. Point ptCenter = Point((int)nx, (int)ny);
  2023. if (pointPolygonTest(listEdge, ptCenter, false) != 1)// the center point doesn't contain in the contour, we think it as curve shape.
  2024. {
  2025. isStripShape = true;
  2026. }
  2027. /*if (lengthWidthRatio >= 2 )// in PartA software this is true,but IncA because of the GB definition the everage feret diameter is always the mean value of all the chord.
  2028. {
  2029. isStripShape = true;
  2030. }*/
  2031. if (fillRatio <= 0.4)// only when the fill rate is very low,we think it as a curve shape,then we choose the mean width as the feret diameter.
  2032. {
  2033. isStripShape = true;
  2034. }
  2035. if (isStripShape)
  2036. {
  2037. curveLength = a_pOTSPart->GetPerimeter()/2 - a_pOTSPart->GetDInscr()/2;// thinking this particle as a strip rectangle.the width is the max inscribe circle diameter/2.
  2038. if (curveLength < D_MAX)
  2039. {
  2040. curveLength = D_MAX;
  2041. }
  2042. if (curveLength < MIN_DOUBLE_VALUE || a_pOTSPart->GetActualArea()<MIN_DOUBLE_VALUE)
  2043. {
  2044. D_MEAN = 0;
  2045. }
  2046. else
  2047. {
  2048. D_MEAN = a_pOTSPart->GetActualArea() / curveLength;
  2049. }
  2050. a_pOTSPart->SetDMean(D_MEAN*a_PixelSize);
  2051. a_pOTSPart->SetFeretDiameter(D_MEAN*a_PixelSize);
  2052. a_pOTSPart->SetDElong (curveLength*a_PixelSize);
  2053. }
  2054. else//it's a ball shape particle
  2055. {
  2056. curveLength = D_MAX;
  2057. double ftd = 0, maxD = 0, minD = 0, dratio = 0;
  2058. GetParticleAverageChord(outContour, a_PixelSize, ftd);
  2059. a_pOTSPart->SetDMean(ftd);
  2060. a_pOTSPart->SetFeretDiameter(ftd);
  2061. a_pOTSPart->SetDElong(curveLength*a_PixelSize);
  2062. }
  2063. return true;
  2064. }
  2065. BOOL COTSImageProcess::SplitRawParticleIntoMatricsParticle(COTSParticlePtr a_pOTSPart,int imageWidth,int imageHeight, double a_PixelSize, double a_XrayStep)
  2066. {
  2067. //--------- convert this particle data to image data,construct an image only with this particle.------
  2068. const int nExpand_Size = 3;
  2069. const int nWhiteColor = 0;
  2070. const int nThickness = 1;
  2071. // lineType Type of the line
  2072. const int nLineType = 8;
  2073. // get rectangle of the particle
  2074. CRect rect = a_pOTSPart->GetParticleRect();
  2075. if (a_pOTSPart->GetActualArea() < 30 * a_PixelSize)// the particle is too small that openCV can't calculate a width value of it. Then we take the upright rect of the particle as it's minArea rect.
  2076. {
  2077. double w = 0, h = 0;
  2078. w = (double)rect.Width() * a_PixelSize;
  2079. h = (double)rect.Height() * a_PixelSize;
  2080. a_pOTSPart->SetDMax(MAX(w, h));
  2081. a_pOTSPart->SetDMin(MIN(w, h));
  2082. a_pOTSPart->SetDMean((w + h) / 2);
  2083. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  2084. a_pOTSPart->SetDElong(MAX(w, h));
  2085. a_pOTSPart->SetPerimeter((w + h) * 2);
  2086. a_pOTSPart->SetDPerp(MIN(w, h));
  2087. a_pOTSPart->SetDInscr(MIN(w, h));
  2088. return true;
  2089. }
  2090. // calculate the particle image data size, expand 3 pixel at the edge
  2091. Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size, rect.Width() + nExpand_Size, CV_8U);
  2092. // get the segment list
  2093. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  2094. for (auto pSegment : listSegment)
  2095. {
  2096. int nStart = pSegment->GetStart() - rect.left + nExpand_Size;
  2097. int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;
  2098. int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;
  2099. line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);
  2100. }
  2101. //--------abstract the contour of the particle.
  2102. Mat cvcopyImg;
  2103. medianBlur(particleImage, cvcopyImg, 5);//smooth the edge
  2104. vector<vector<Point>>contours;
  2105. findContours(cvcopyImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  2106. if (contours.size() == 0)// the particle is too odd that openCV can't find a contour of it. Then we take the upright rect of the particle as it's minArea rect.
  2107. {
  2108. double w = 0, h = 0;
  2109. w = (double)rect.Width() * a_PixelSize;
  2110. h = (double)rect.Height() * a_PixelSize;
  2111. a_pOTSPart->SetDMax(MAX(w, h));
  2112. a_pOTSPart->SetDMin(MIN(w, h));
  2113. a_pOTSPart->SetDMean((w + h) / 2);
  2114. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  2115. a_pOTSPart->SetDElong(MAX(w, h));
  2116. a_pOTSPart->SetPerimeter((w + h) * 2);
  2117. a_pOTSPart->SetDPerp(MIN(w, h));
  2118. a_pOTSPart->SetDInscr(MIN(w, h));
  2119. return true;
  2120. }
  2121. int imaxcontour = 0, imax = 0;
  2122. for (unsigned int i = 0; i < contours.size(); i++) {
  2123. int itmp = contourArea(contours[i]);
  2124. if (imaxcontour < itmp) {
  2125. imax = i;
  2126. imaxcontour = itmp;
  2127. }
  2128. }
  2129. vector<Point > listEdge = contours[imax];
  2130. if (a_XrayStep > 0)
  2131. {
  2132. COTSParticleList matricsParts;
  2133. int xrayStep = a_XrayStep;// *a_PixelSize;
  2134. GetMatricsParticlesFromRawParticle(a_pOTSPart, imageWidth,imageHeight,a_PixelSize, xrayStep, matricsParts);
  2135. a_pOTSPart->SetSubParticles(matricsParts);
  2136. }
  2137. //-----------
  2138. }
  2139. BOOL COTSImageProcess::SplitRawParticleIntoGreyScaleParticle(COTSParticlePtr a_pOTSPart, double a_PixelSize ,CBSEImgPtr fieldImg)
  2140. {
  2141. //--------- convert this particle data to image data,construct an image only with this particle.------
  2142. const int nExpand_Size = 3;
  2143. const int nWhiteColor = 0;
  2144. const int nThickness = 1;
  2145. // lineType Type of the line
  2146. const int nLineType = 8;
  2147. // get rectangle of the particle
  2148. CRect rect = a_pOTSPart->GetParticleRect();
  2149. if (a_pOTSPart->GetActualArea() < 5 * a_PixelSize)// the particle is too small that openCV can't calculate a width value of it. Then we take the upright rect of the particle as it's minArea rect.
  2150. {
  2151. double w = 0, h = 0;
  2152. w = (double)rect.Width() * a_PixelSize;
  2153. h = (double)rect.Height() * a_PixelSize;
  2154. a_pOTSPart->SetDMax(MAX(w, h));
  2155. a_pOTSPart->SetDMin(MIN(w, h));
  2156. a_pOTSPart->SetDMean((w + h) / 2);
  2157. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  2158. a_pOTSPart->SetDElong(MAX(w, h));
  2159. a_pOTSPart->SetPerimeter((w + h) * 2);
  2160. a_pOTSPart->SetDPerp(MIN(w, h));
  2161. a_pOTSPart->SetDInscr(MIN(w, h));
  2162. return true;
  2163. }
  2164. // calculate the particle image data size, expand 3 pixel at the edge
  2165. CBSEImgPtr onePartImg = CBSEImgPtr(new CBSEImg(CRect(0,0, fieldImg->GetWidth(), fieldImg->GetHeight())));
  2166. // get the segment list
  2167. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  2168. for (auto pSegment : listSegment)
  2169. {
  2170. for (int i = 0; i < pSegment->GetLength(); i++)
  2171. {
  2172. int x = pSegment->GetStart() + i;
  2173. int y = pSegment->GetHeight();
  2174. int bseValue = fieldImg->GetBSEValue(x,y);
  2175. onePartImg->SetBSEValue(x, y,bseValue);
  2176. }
  2177. }
  2178. /*ImshowImage(onePartImg);
  2179. ImshowChartData(onePartImg);*/
  2180. std::vector<CIntRangePtr> rngs = CalcuGrayLevelRange(onePartImg);
  2181. COTSFieldDataPtr partData = COTSFieldDataPtr(new COTSFieldData());
  2182. std::map<int, std::vector<COTSParticlePtr>> partAreaMap;
  2183. for (int i = 0; i < rngs.size(); i++)
  2184. {
  2185. partAreaMap.clear();
  2186. GetParticlesBySpecialGrayRange(onePartImg, rngs[i], CDoubleRangePtr(new CDoubleRange(0, 2000)), a_PixelSize, partData);
  2187. for (auto p : partData->GetParticleList())//sorting and filtering
  2188. {
  2189. /*if (p->GetActualArea() > 50)
  2190. {*/
  2191. partAreaMap[p->GetPixelArea()].push_back(p);
  2192. //}
  2193. }
  2194. if(partAreaMap.size()>0)
  2195. {
  2196. auto theBiggestPart = partAreaMap.rbegin()->second[0];
  2197. theBiggestPart->CalXRayPos();
  2198. std::map<int, std::vector<COTSParticlePtr>>::reverse_iterator it;
  2199. auto partsegs = theBiggestPart->GetFeature()->GetSegmentsList();
  2200. it = partAreaMap.rbegin()++;
  2201. for (; it != partAreaMap.rend(); it++)
  2202. {
  2203. for (auto sameAreaP : it->second)
  2204. {
  2205. auto segs = sameAreaP->GetFeature()->GetSegmentsList();
  2206. for (auto s : segs)
  2207. {
  2208. partsegs.push_back(s);
  2209. }
  2210. }
  2211. }
  2212. theBiggestPart->GetFeature()->SetSegmentsList(partsegs, true);
  2213. theBiggestPart->SetFieldId(a_pOTSPart->GetFieldId());
  2214. theBiggestPart->SetAnalysisId(a_pOTSPart->GetAnalysisId());
  2215. a_pOTSPart->AddSubParticle(theBiggestPart);
  2216. }
  2217. /*for (auto p : partData->GetParticleList())
  2218. {
  2219. a_pOTSPart->AddSubParticle(p);
  2220. }*/
  2221. }
  2222. return 0;
  2223. }
  2224. void COTSImageProcess::ImshowImage(CBSEImgPtr img)
  2225. {
  2226. BYTE* data = img->GetImageDataPointer();
  2227. //Mat cvImg;
  2228. cv::Size s;
  2229. s.width = img->GetImageSize().cx;
  2230. s.height = img->GetImageSize().cy;
  2231. Mat cvImg=Mat::zeros(s, CV_8U);
  2232. cvImg.data = data;
  2233. cv::imshow("dd", cvImg);
  2234. cv::waitKey();
  2235. }
  2236. void COTSImageProcess::ImshowChartData(CBSEImgPtr img)
  2237. {
  2238. img->SetChartData();
  2239. WORD* data = img->GetBSEChart();
  2240. //Mat cvImg;
  2241. cv::Size s;
  2242. s.width = 255;
  2243. s.height = 100;
  2244. Mat cvImg = Mat::zeros(s, CV_8U);
  2245. //cvImg.data = data;
  2246. WORD nBSEChart[MAXBYTE];
  2247. //1. get chart data
  2248. linearSmooth5(data, nBSEChart, MAXBYTE);
  2249. for (int i=1;i<255;i++)
  2250. {
  2251. line(cvImg, Point(i, 100-nBSEChart[i]), Point(i+1, 100-nBSEChart[i+1]), Scalar(nBlackColor), 1, 8);
  2252. }
  2253. cv::imshow("chart", cvImg);
  2254. cv::waitKey();
  2255. }
  2256. BOOL COTSImageProcess::MergeBigBoundaryParticles(COTSFieldDataList allFields,double pixelSize,int scanFieldSize, CSize ResolutionSize, COTSParticleList& mergedParts)
  2257. {
  2258. COTSSegmentsList boarderSegs;
  2259. auto FldMgr = new CFieldMgr(scanFieldSize, ResolutionSize);
  2260. std::map<COTSParticle*, COTSParticleList> mapMergeParticles;//hold up all the boundary connected particles. the pair's first is also the member of these particles.
  2261. std::map<COTSParticle*, COTSSegmentsList> mapMergedSegments;//hold up all the segment's corresponding clone in the connected particles.
  2262. for (auto centerfld : allFields)
  2263. {
  2264. // find neighbor field on the left.
  2265. auto leftFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::LEFT);
  2266. if (leftFld != nullptr)
  2267. {
  2268. auto leftParts = centerfld->GetLeftBorderedBigParticles();
  2269. auto rightParts = leftFld->GetRightBorderedBigParticles();
  2270. for (auto leftp : leftParts)
  2271. {
  2272. for (auto rightp : rightParts)
  2273. {
  2274. if (leftp->IsConnected(rightp.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::LEFT))
  2275. {
  2276. if (leftp->headerParticle != NULL)
  2277. {
  2278. if (rightp->headerParticle == NULL)
  2279. {
  2280. rightp->headerParticle = leftp->headerParticle;
  2281. mapMergeParticles[leftp->headerParticle].push_back(rightp);
  2282. }
  2283. }
  2284. else
  2285. {
  2286. if (rightp->headerParticle != NULL)
  2287. {
  2288. leftp->headerParticle = rightp.get();
  2289. mapMergeParticles[rightp.get()].push_back(leftp);
  2290. }
  2291. else
  2292. {
  2293. leftp->headerParticle = leftp.get();
  2294. rightp->headerParticle = leftp.get();
  2295. mapMergeParticles[leftp.get()].push_back(rightp);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. //find neighbor field on the upward
  2303. auto upFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::UP);
  2304. if (upFld != nullptr)
  2305. {
  2306. auto upParts = centerfld->GetTopBorderedBigParticles();
  2307. auto downParts = upFld->GetBottomBorderedBigParticles();
  2308. for (auto upprt : upParts)
  2309. {
  2310. for (auto downprt : downParts)
  2311. {
  2312. if (upprt->IsConnected(downprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::UP))
  2313. {
  2314. if (upprt->headerParticle != NULL)
  2315. {
  2316. if (downprt->headerParticle == NULL)
  2317. {
  2318. downprt->headerParticle = upprt->headerParticle;
  2319. mapMergeParticles[upprt->headerParticle].push_back(downprt);
  2320. }
  2321. }
  2322. else
  2323. {
  2324. if (downprt->headerParticle != NULL)
  2325. {
  2326. upprt->headerParticle = downprt->headerParticle;
  2327. mapMergeParticles[downprt.get()].push_back(upprt);
  2328. }
  2329. else
  2330. {
  2331. upprt->headerParticle = upprt.get();
  2332. downprt->headerParticle = upprt.get();
  2333. mapMergeParticles[upprt.get()].push_back(downprt);
  2334. }
  2335. }
  2336. }
  2337. }
  2338. }
  2339. }
  2340. //find neighbor field on the downward.
  2341. auto downFld = FldMgr->FindNeighborField(allFields, centerfld,SORTING_DIRECTION::DOWN);
  2342. if (downFld != nullptr)
  2343. {
  2344. auto downParts = centerfld->GetBottomBorderedBigParticles();
  2345. auto upParts = downFld->GetTopBorderedBigParticles();
  2346. for (auto downprt : downParts)
  2347. {
  2348. for (auto upprt : upParts)
  2349. {
  2350. if (downprt->IsConnected(upprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::DOWN))
  2351. {
  2352. if (downprt->headerParticle != NULL)
  2353. {
  2354. if (upprt->headerParticle == NULL)
  2355. {
  2356. upprt->headerParticle = downprt->headerParticle;
  2357. mapMergeParticles[downprt->headerParticle].push_back(upprt);
  2358. }
  2359. }
  2360. else
  2361. {
  2362. if (upprt->headerParticle != NULL)
  2363. {
  2364. downprt->headerParticle = upprt->headerParticle;
  2365. mapMergeParticles[upprt->headerParticle].push_back(downprt);
  2366. }
  2367. else
  2368. {
  2369. downprt->headerParticle = downprt.get();
  2370. upprt->headerParticle = downprt.get();
  2371. mapMergeParticles[downprt.get()].push_back(upprt);
  2372. }
  2373. }
  2374. }
  2375. }
  2376. }
  2377. }
  2378. //find neighbor field on the right.
  2379. auto rightFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::RIGHT);
  2380. if (rightFld != nullptr)
  2381. {
  2382. auto rightParts = centerfld->GetRightBorderedBigParticles();
  2383. auto leftParts = rightFld->GetLeftBorderedBigParticles();
  2384. for (auto rightprt : rightParts)
  2385. {
  2386. for (auto leftprt : leftParts)
  2387. {
  2388. if (rightprt->IsConnected(leftprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::RIGHT))
  2389. {
  2390. if (rightprt->headerParticle != NULL)
  2391. {
  2392. if (leftprt->headerParticle == NULL)
  2393. {
  2394. leftprt->headerParticle = rightprt->headerParticle;
  2395. mapMergeParticles[rightprt->headerParticle].push_back(leftprt);
  2396. }
  2397. }
  2398. else
  2399. {
  2400. if (leftprt->headerParticle != NULL)
  2401. {
  2402. rightprt->headerParticle = leftprt->headerParticle;
  2403. mapMergeParticles[leftprt->headerParticle].push_back(rightprt);
  2404. }
  2405. else
  2406. {
  2407. rightprt->headerParticle = rightprt.get();
  2408. leftprt->headerParticle = rightprt.get();
  2409. mapMergeParticles[rightprt.get()].push_back(leftprt);
  2410. }
  2411. }
  2412. }
  2413. }
  2414. }
  2415. }
  2416. }
  2417. static int partTagId;
  2418. for (auto pair : mapMergeParticles)
  2419. {
  2420. struct EleAreaPercentage
  2421. {
  2422. EleAreaPercentage(double p, CElementChemistryPtr e)
  2423. {
  2424. areaPercentage = p;
  2425. eleData = e;
  2426. }
  2427. double areaPercentage;
  2428. CElementChemistryPtr eleData;
  2429. };
  2430. auto newPart = COTSParticlePtr(new COTSParticle());
  2431. COTSSegmentsList newSegs;
  2432. auto p = pair.first;
  2433. newPart->SetAbsolutePos(p->GetAbsolutPos());
  2434. //firstly,we sum up all the merged particles's area and get the represent string.
  2435. std::string partsStr = std::to_string(p->GetFieldId()) + ":" + std::to_string(p->GetAnalysisId());
  2436. double allPartArea = p->GetActualArea();//Get the first particle's area.
  2437. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  2438. {
  2439. partsStr += "," + std::to_string(other->GetFieldId()) + ":" + std::to_string(other->GetAnalysisId());//Get the subparticles string such as "1:1,2:1" etc.
  2440. allPartArea += other->GetActualArea();//Get other particle's area
  2441. }
  2442. // calculate all the new segment's position.
  2443. std::vector <COTSParticle*> allSubParts;
  2444. allSubParts.push_back(p);
  2445. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  2446. {
  2447. allSubParts.push_back(other.get());
  2448. }
  2449. for (auto subp : allSubParts)
  2450. {
  2451. int fid = subp->GetFieldId();
  2452. CPoint myFldPos;
  2453. for (auto f : allFields)//find this particle's filed.
  2454. {
  2455. if (f->GetId() == fid)
  2456. {
  2457. myFldPos = f->GetPosition();
  2458. }
  2459. }
  2460. int fldWidth = allFields[0]->Width;
  2461. int fldHeight = allFields[0]->Height;
  2462. CPoint fldLeftUpPos = CPoint(myFldPos.x + fldWidth / 2 , myFldPos.y + fldHeight / 2 );
  2463. for (auto s : subp->GetFeature()->GetSegmentsList())
  2464. {
  2465. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  2466. newseg->SetStart(s->GetStart() + fldLeftUpPos.x);
  2467. newseg->SetHeight((0 - s->GetHeight()) + fldLeftUpPos.y);//the coordinate system of segment in a field is different with the OTS coordinate system.OTS system's y axis is upward positive ,yet the field is downward positive.
  2468. newseg->SetLength(s->GetLength());
  2469. newSegs.push_back(newseg);
  2470. }
  2471. }
  2472. COTSFeaturePtr newFeature = COTSFeaturePtr(new COTSFeature());
  2473. newFeature->SetSegmentsList(newSegs);
  2474. newPart->SetFeature(newFeature);
  2475. newPart->CalCoverRect();
  2476. //second, we get all the element data and their area percentage .
  2477. std::map<std::string, std::vector<EleAreaPercentage>> mapEleData;
  2478. CPosXrayPtr pXray1 = p->GetXrayInfo();
  2479. if (pXray1 != nullptr)
  2480. {
  2481. for (auto ele : pXray1->GetElementQuantifyData())
  2482. {
  2483. mapEleData[ele->GetName().GetBuffer()].push_back(EleAreaPercentage(p->GetActualArea() / allPartArea, ele));
  2484. }
  2485. }
  2486. for (auto other : pair.second)
  2487. {
  2488. auto otherXray = other->GetXrayInfo();
  2489. if (otherXray != nullptr)
  2490. {
  2491. for (auto eledata : otherXray->GetElementQuantifyData())
  2492. {
  2493. mapEleData[eledata->GetName().GetBuffer()].push_back(EleAreaPercentage(other->GetActualArea() / allPartArea, eledata));
  2494. }
  2495. }
  2496. }
  2497. // third,we calculate all the element's new percentage data and get a new element chemistry list.
  2498. CElementChemistriesList newCheList;
  2499. for (auto eledata : mapEleData)
  2500. {
  2501. CElementChemistryPtr newEleche = CElementChemistryPtr(new CElementChemistry());
  2502. newEleche->SetName(CString(eledata.first.c_str()));
  2503. double newPercentage = 0;
  2504. for (auto d : eledata.second)
  2505. {
  2506. newPercentage += d.areaPercentage * d.eleData->GetPercentage();
  2507. }
  2508. newEleche->SetPercentage(newPercentage);
  2509. newCheList.push_back(newEleche);
  2510. }
  2511. CPosXrayPtr xray(new CPosXray());
  2512. xray->SetElementQuantifyData(newCheList);
  2513. newPart->SetXrayInfo(xray);
  2514. newPart->SetSubParticlesName(partsStr);
  2515. newPart->SetActualArea(allPartArea);
  2516. partTagId++;
  2517. newPart->SetParticleId(partTagId);
  2518. newPart->SetAnalysisId(partTagId);
  2519. std::string name = p->TypeName();
  2520. newPart->TypeName(name);
  2521. newPart->TypeColor(p->TypeColor());
  2522. mergedParts.push_back(newPart);
  2523. }
  2524. return true;
  2525. }
  2526. }