OTSImageProcess.cpp 70 KB

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