OTSImageProcess.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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. #include "BaseFunction.h"
  13. namespace OTSIMGPROC
  14. {
  15. using namespace cv;
  16. using namespace std;
  17. const int nBlackColor = 255;
  18. COTSImageProcess::COTSImageProcess(COTSImageProcessParamPtr a_pImageProcessParam)
  19. {
  20. m_imageProcessParam = a_pImageProcessParam;
  21. }
  22. COTSImageProcess::~COTSImageProcess()
  23. {
  24. }
  25. BOOL COTSImageProcess::RemoveBGByCVconnectivities(CBSEImgPtr inBSEImg, double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  26. {
  27. ASSERT(m_pFieldData);
  28. ASSERT(inBSEImg);
  29. ASSERT(m_imageProcessParam);
  30. int nWidthImg = inBSEImg->GetWidth();
  31. int nHeightImg = inBSEImg->GetHeight();
  32. m_pFieldData->Width = nWidthImg;
  33. m_pFieldData->Height = nHeightImg;
  34. long nImgSize = nWidthImg * nHeightImg;
  35. BYTE* pSrcImg = inBSEImg->GetImageDataPointer();
  36. BYTE* pTempImg = new BYTE[nImgSize];
  37. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  38. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  39. //long nNumParticle = 0;
  40. RemoveBackGround(inBSEImg, m_imageProcessParam, imgNoBGBinary/*, nNumParticle*/);
  41. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  42. long nPtStart = m_imageProcessParam->GetParticleGray().GetStart();
  43. long nPtEnd = m_imageProcessParam->GetParticleGray().GetEnd();
  44. /*if (nNumParticle == 0)
  45. {
  46. COTSParticleList listParticleEmpty;
  47. listParticleEmpty.clear();
  48. m_pFieldData->SetParticleList(listParticleEmpty);
  49. }
  50. else
  51. {*/
  52. // get the area image
  53. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  54. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  55. Mat stats, centroids;
  56. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  57. double rMin = m_imageProcessParam->GetIncArea().GetStart()/2.0;
  58. double rMax = m_imageProcessParam->GetIncArea().GetEnd()/2.0;
  59. double partAreaMin = rMin * rMin * 3.14159;
  60. double partAreaMax = rMax * rMax * 3.14159;
  61. COTSParticleList listParticleOut;
  62. for (size_t i = 1; i < number; i++)
  63. {
  64. int center_x = centroids.at<double>(i, 0);
  65. int center_y = centroids.at<double>(i, 1);
  66. //앤近긋움
  67. int x = stats.at<int>(i, CC_STAT_LEFT);
  68. int y = stats.at<int>(i, CC_STAT_TOP);
  69. int w = stats.at<int>(i, CC_STAT_WIDTH);
  70. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  71. int area = stats.at<int>(i, CC_STAT_AREA);
  72. double actualArea = area * a_pixelSize * a_pixelSize;
  73. if (actualArea >= partAreaMin && actualArea < partAreaMax)
  74. {
  75. Rect rectMax = Rect(x, y, w, h);
  76. Mat rectROI = labels(rectMax).clone();
  77. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  78. //exclude the point which intersect into this bounding box but is not in this group.
  79. int label = i;
  80. for (int row = 0; row < rectROI.rows; row++)
  81. {
  82. for (int col = 0; col < rectROI.cols; col++)
  83. {
  84. int v = rectROI.at<int>(row, col);
  85. if (v == label)
  86. {
  87. 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.
  88. }
  89. }
  90. }
  91. COTSParticleList roiParts;
  92. if (GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  93. {
  94. if (roiParts.size() > 0)
  95. {
  96. COTSParticlePtr roiPart = roiParts[0];//we will find only one part in the roi.
  97. roiPart->SetXRayPos(CPoint(center_x, center_y));
  98. CRect r = CRect(x, y, x + w, y + h);
  99. roiPart->SetParticleRect(r);
  100. roiPart->SetActualArea(actualArea);
  101. roiPart->SetPixelArea(area);
  102. listParticleOut.push_back(roiPart);
  103. }
  104. }
  105. }
  106. }
  107. int nTagId;
  108. for (auto pParticle : listParticleOut)
  109. {
  110. COTSFeaturePtr pFeature = pParticle->GetFeature();
  111. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  112. long nPixelNum = 0;
  113. long nPixelAll = 0;
  114. int nStartS = 0;
  115. int nHeightS = 0;
  116. int nLengthS = 0;
  117. for (auto pSegment : listSegment)
  118. {
  119. // get particle average gray
  120. nStartS = pSegment->GetStart();
  121. nHeightS = pSegment->GetHeight();
  122. nLengthS = pSegment->GetLength();
  123. nPixelNum += (long)nLengthS;
  124. for (unsigned int i = 0; i < nLengthS; i++)
  125. {
  126. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  127. nPixelAll += nValueTemp;
  128. }
  129. }
  130. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  131. pParticle->SetAveGray(nAveGray);
  132. auto fieldOTSRect = m_pFieldData->GetOTSRect();
  133. CPoint leftTop = fieldOTSRect.GetTopLeft();
  134. CRect rectInSinglefld = pParticle->GetParticleRect();
  135. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_pixelSize, leftTop.y - rectInSinglefld.top * a_pixelSize);
  136. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_pixelSize, leftTop.y - rectInSinglefld.bottom * a_pixelSize);
  137. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  138. pParticle->SetOTSRect(recInOTSCord);
  139. }
  140. m_pFieldData->SetParticleList(listParticleOut);
  141. //}
  142. delete[]pTempImg;
  143. return TRUE;
  144. }
  145. BOOL COTSImageProcess::GetParticlesBySpecialGrayRange(CBSEImgPtr a_pBSEImg, CIntRangePtr a_grayRange,CDoubleRangePtr a_diameterRange,double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  146. {
  147. ASSERT(m_pFieldData);
  148. ASSERT(a_pBSEImg);
  149. ASSERT(a_grayRange);
  150. int nWidthImg = a_pBSEImg->GetWidth();
  151. int nHeightImg = a_pBSEImg->GetHeight();
  152. m_pFieldData->Width = nWidthImg;
  153. m_pFieldData->Height = nHeightImg;
  154. long nImgSize = nWidthImg * nHeightImg;
  155. BYTE* pSrcImg = a_pBSEImg->GetImageDataPointer();
  156. BYTE* pTempImg = new BYTE[nImgSize];
  157. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  158. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  159. long nNumParticle = 0;
  160. GetSpecialGrayRangeImage(a_pBSEImg, a_grayRange, imgNoBGBinary, nNumParticle);
  161. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  162. if (nNumParticle == 0)
  163. {
  164. COTSParticleList listParticleEmpty;
  165. listParticleEmpty.clear();
  166. m_pFieldData->SetParticleList(listParticleEmpty);
  167. }
  168. else
  169. {
  170. // get the area image
  171. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  172. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  173. Mat stats, centroids;
  174. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  175. double rStart = a_diameterRange->GetStart() / 2.0;
  176. double rEnd = a_diameterRange->GetEnd() / 2.0;
  177. double areaStart = rStart * rStart * 3.14159;
  178. double areaEnd = rEnd * rEnd * 3.14159;
  179. COTSParticleList listParticleOut;
  180. for (size_t i = 1; i < number; i++)
  181. {
  182. int center_x = centroids.at<double>(i, 0);
  183. int center_y = centroids.at<double>(i, 1);
  184. //앤近긋움
  185. int x = stats.at<int>(i, CC_STAT_LEFT);
  186. int y = stats.at<int>(i, CC_STAT_TOP);
  187. int w = stats.at<int>(i, CC_STAT_WIDTH);
  188. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  189. int area = stats.at<int>(i, CC_STAT_AREA);
  190. double actualArea = area * a_pixelSize * a_pixelSize;
  191. if (actualArea >= areaStart && actualArea < areaEnd)
  192. {
  193. Rect rectMax = Rect(x, y, w, h);
  194. Mat rectROI = labels(rectMax).clone();
  195. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  196. //exclude the point which intersect into this bounding box but is not in this group.
  197. int label = i;
  198. for (int row = 0; row < rectROI.rows; row++)
  199. {
  200. for (int col = 0; col < rectROI.cols; col++)
  201. {
  202. int v = rectROI.at<int>(row, col);
  203. if (v == label)
  204. {
  205. imageROI.at<uchar>(row, col) = 255;
  206. }
  207. }
  208. }
  209. COTSParticleList roiParts;
  210. if (!GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  211. {
  212. continue;
  213. }
  214. if (roiParts.size() > 0)
  215. {
  216. COTSParticlePtr roiPart = roiParts[0];
  217. roiPart->SetXRayPos(CPoint(center_x, center_y));
  218. CRect r = CRect(x, y, x + w, y + h);
  219. roiPart->SetParticleRect(r);
  220. roiPart->SetActualArea(actualArea);
  221. roiPart->SetPixelArea(area);
  222. listParticleOut.push_back(roiPart);
  223. }
  224. }
  225. }
  226. // form a image only have particles on
  227. //COTSSegmentsList listImage;
  228. for (auto pParticle : listParticleOut)
  229. {
  230. int area = pParticle->GetActualArea();
  231. double pActualArea = area ;
  232. COTSFeaturePtr pFeature = pParticle->GetFeature();
  233. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  234. long nPixelNum = 0;
  235. long nPixelAll = 0;
  236. int nStartS = 0;
  237. int nHeightS = 0;
  238. int nLengthS = 0;
  239. for (auto pSegment : listSegment)
  240. {
  241. // get particle average gray
  242. nStartS = pSegment->GetStart();
  243. nHeightS = pSegment->GetHeight();
  244. nLengthS = pSegment->GetLength();
  245. nPixelNum += (long)nLengthS;
  246. for (unsigned int i = 0; i < nLengthS; i++)
  247. {
  248. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  249. nPixelAll += nValueTemp;
  250. }
  251. }
  252. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  253. pParticle->SetAveGray(nAveGray);
  254. auto fieldOTSRect = m_pFieldData->GetOTSRect();
  255. CPoint leftTop = fieldOTSRect.GetTopLeft();
  256. CRect rectInSinglefld = pParticle->GetParticleRect();
  257. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_pixelSize, leftTop.y - rectInSinglefld.top * a_pixelSize);
  258. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_pixelSize, leftTop.y - rectInSinglefld.bottom * a_pixelSize);
  259. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  260. pParticle->SetOTSRect(recInOTSCord);
  261. }
  262. m_pFieldData->SetParticleList(listParticleOut);
  263. }
  264. delete[]pTempImg;
  265. return TRUE;
  266. }
  267. CIntRangePtr COTSImageProcess::CalBackground(CBSEImgPtr m_pBSEImg)
  268. {
  269. auto ranges = CalcuGrayLevelRange(m_pBSEImg);
  270. return ranges[0];
  271. }
  272. std::vector<CIntRangePtr> COTSImageProcess::CalcuGrayLevelRange(CBSEImgPtr m_pBSEImg)
  273. {
  274. CIntRangePtr pBackground = CIntRangePtr(new CIntRange());
  275. WORD originChartData[MAXBYTE];
  276. WORD firstSmoothChart[MAXBYTE];
  277. WORD secondSmooth[MAXBYTE];
  278. //1. get chart data
  279. m_pBSEImg->SetChartData();
  280. memcpy(originChartData, m_pBSEImg->GetBSEChart(), sizeof(WORD) * MAXBYTE);
  281. originChartData[0] = 0;
  282. originChartData[254] = 0;
  283. linearSmooth5(originChartData, firstSmoothChart, MAXBYTE);
  284. linearSmooth5(firstSmoothChart, secondSmooth, MAXBYTE);
  285. //2. get down edge
  286. int nLengthEdge = MAXBYTE + 2;
  287. WORD n_aBSEChart[MAXBYTE + 2];
  288. memset(n_aBSEChart, 0, sizeof(WORD) * nLengthEdge);
  289. std::map<long, std::vector<int>> peakMap;// hold all the peaks in this spectrum which are sorted by there area.
  290. std::vector<int> currentUpSeries;
  291. std::vector<int> currentPeakSeries;
  292. // make sure the wave begin with up edge and end with down edge
  293. n_aBSEChart[0] = 0;
  294. n_aBSEChart[nLengthEdge - 1] = 0;
  295. memcpy(&n_aBSEChart[1], &secondSmooth, sizeof(WORD) * MAXBYTE);
  296. int nLengthCom = MAXBYTE + 1;
  297. // up edge
  298. for (int i = 0; i < nLengthCom; i++)
  299. {
  300. if (n_aBSEChart[i] <= n_aBSEChart[i + 1])//this is a upward edge
  301. {
  302. if (currentPeakSeries.size() > 0)
  303. {
  304. int seriesSize = currentPeakSeries.size();
  305. long area = 0;
  306. for (int i = 0; i < seriesSize; i++)
  307. {
  308. area = area + n_aBSEChart[currentPeakSeries[i]];
  309. }
  310. peakMap[area] = currentPeakSeries;
  311. currentPeakSeries.clear();
  312. }
  313. currentUpSeries.push_back(i + 1);// save all the continuous up edge
  314. }
  315. else//this is a downward edge
  316. {
  317. // encounter a downward edge means upward edge series end,
  318. if (currentUpSeries.size() > 0)
  319. {
  320. currentPeakSeries = currentUpSeries;
  321. currentUpSeries.clear();
  322. }
  323. currentPeakSeries.push_back(i + 1);
  324. }
  325. }
  326. if (currentPeakSeries.size() > 0)
  327. {
  328. int seriesSize = currentPeakSeries.size();
  329. long area = 0;
  330. for (int i = 0; i < seriesSize; i++)
  331. {
  332. area = area + n_aBSEChart[currentPeakSeries[i]];
  333. }
  334. peakMap[area] = currentPeakSeries;
  335. currentPeakSeries.clear();
  336. }
  337. std::vector<CIntRangePtr> ranges;
  338. std::map<long, std::vector<int>>::reverse_iterator it;
  339. for (it=peakMap.rbegin();it!=peakMap.rend();it++)
  340. {
  341. CIntRangePtr pRange = CIntRangePtr(new CIntRange());
  342. pRange->SetStart(it->second[0]);
  343. pRange->SetEnd(it->second[it->second.size()-1]);
  344. ranges.push_back(pRange);
  345. }
  346. return ranges;
  347. }
  348. void COTSImageProcess::GetSpecialGrayRangeImage(CBSEImgPtr a_pImgIn, CIntRangePtr a_SpecialGrayRange, CBSEImgPtr a_pBinImgOut, long& foundedPixelNum)
  349. {
  350. // the background pixel will be 0,and the other part will be 255.
  351. ASSERT(a_pImgIn);
  352. int nWidthImg = a_pImgIn->GetWidth();
  353. int nHeightImg = a_pImgIn->GetHeight();
  354. long nImgSize = nWidthImg * nHeightImg;
  355. BYTE* pTempImg = new BYTE[nImgSize];
  356. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  357. BYTE* pPixel = new byte[nImgSize];
  358. long nBGStart;
  359. long nBGEnd;
  360. long nNumParticle = 0;
  361. nBGStart = a_SpecialGrayRange->GetStart();
  362. nBGEnd = a_SpecialGrayRange->GetEnd();
  363. // delete background
  364. for (unsigned int i = 0; i < nImgSize; i++)
  365. {
  366. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  367. {
  368. pPixel[i] = 255;
  369. nNumParticle++;
  370. }
  371. else
  372. {
  373. pPixel[i] = 0;
  374. }
  375. }
  376. BErode3(pPixel, pTempImg, 5, nHeightImg, nWidthImg);
  377. BDilate3(pTempImg, pPixel, 5, nHeightImg, nWidthImg);
  378. a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);
  379. foundedPixelNum = nNumParticle;
  380. delete[] pTempImg;
  381. return;
  382. }
  383. void COTSImageProcess::RemoveBackGround(CBSEImgPtr a_pImgIn, COTSImageProcessParamPtr a_pImageProcessParam, CBSEImgPtr a_pBinImgOut/*,long& foundedPixelNum*/)
  384. {
  385. // the background pixel will be 0,and the other part will be 255.
  386. ASSERT(a_pImgIn);
  387. ASSERT(a_pImageProcessParam);
  388. int nWidthImg = a_pImgIn->GetWidth();
  389. int nHeightImg = a_pImgIn->GetHeight();
  390. long nImgSize = nWidthImg * nHeightImg;
  391. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  392. BYTE* pPixel= new BYTE[nImgSize];
  393. Mat srcImgMat = GetMatDataFromBseImg(a_pImgIn);
  394. Mat rstMat;
  395. long nBGStart;
  396. long nBGEnd;
  397. long nPartStart;
  398. long nPartEnd;
  399. //long nNumParticle = 0;
  400. if (a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL)
  401. {
  402. nBGStart = a_pImageProcessParam->GetBGGray().GetStart();
  403. nBGEnd = a_pImageProcessParam->GetBGGray().GetEnd();
  404. nPartStart = a_pImageProcessParam->GetParticleGray().GetStart();
  405. nPartEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  406. CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd);
  407. //RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  408. pPixel = rstMat.data;
  409. }
  410. else
  411. {
  412. /*auto range = CalBackground(a_pImgIn);
  413. nBGStart = range->GetStart();
  414. nBGEnd = range->GetEnd();*/
  415. switch (a_pImageProcessParam->GetAutoBGRemoveType())
  416. {
  417. case OTS_AUTOBGREMOVE_TYPE::DOWNWARD:
  418. //RemoveBG_old(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  419. //CVRemoveBG(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  420. AutoRemove_background_OTS(srcImgMat, rstMat, 1);
  421. break;
  422. case OTS_AUTOBGREMOVE_TYPE::UPWARD:
  423. //RemoveBG_old(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  424. //CVRemoveBG(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  425. AutoRemove_background_OTS(srcImgMat, rstMat, 0);
  426. break;
  427. case OTS_AUTOBGREMOVE_TYPE::MIDDLE:
  428. //RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  429. //CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  430. AutoRemove_background_OTS(srcImgMat, rstMat, 2);
  431. break;
  432. default:
  433. break;
  434. }
  435. pPixel = rstMat.data;
  436. }
  437. a_pBinImgOut->SetImageData(pPixel,nWidthImg,nHeightImg);
  438. //foundedPixelNum = nNumParticle;
  439. //foundedPixelNum = 100;
  440. return ;
  441. }
  442. BOOL COTSImageProcess::GetParticles(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  443. {
  444. ASSERT(a_pPixel);
  445. if (!a_pPixel)
  446. {
  447. return FALSE;
  448. }
  449. //a_listParticles.clear();
  450. COTSParticleList findedParts;
  451. COTSSegmentsList listSegment;
  452. listSegment.clear();
  453. //1. get segment line by line
  454. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  455. {
  456. return FALSE;
  457. }
  458. if ((int)listSegment.size() == 0)
  459. {
  460. return FALSE;
  461. }
  462. //2. save the temp feature
  463. COTSFeatureList listFeature;
  464. listFeature.clear();
  465. if (!GetFeatureList(listSegment, listFeature))//get every feature for all the particle,the complete feature.
  466. {
  467. return FALSE;
  468. }
  469. if ((int)listFeature.size() == 0)
  470. {
  471. return FALSE;
  472. }
  473. /*COTSParticleList listParticles;
  474. listParticles.clear();*/
  475. if (!ChangeFeaturelist(listFeature, findedParts))
  476. {
  477. return FALSE;
  478. }
  479. for (auto f : findedParts)
  480. {
  481. a_listParticles.push_back(f);
  482. }
  483. return TRUE;
  484. }
  485. BOOL COTSImageProcess::GetOneParticleFromROI(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  486. {
  487. ASSERT(a_pPixel);
  488. if (!a_pPixel)
  489. {
  490. return FALSE;
  491. }
  492. //a_listParticles.clear();
  493. COTSParticleList findedParts;
  494. COTSSegmentsList listSegment;
  495. listSegment.clear();
  496. //1. get segment line by line
  497. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  498. {
  499. return FALSE;
  500. }
  501. if ((int)listSegment.size() == 0)
  502. {
  503. return FALSE;
  504. }
  505. //2. save the temp feature
  506. COTSFeatureList listFeature;
  507. listFeature.clear();
  508. COTSFeaturePtr fea = COTSFeaturePtr(new COTSFeature());
  509. fea->SetSegmentsList(listSegment);
  510. listFeature.push_back(fea);
  511. if ((int)listFeature.size() == 0)
  512. {
  513. return FALSE;
  514. }
  515. if (!ChangeFeaturelist(listFeature, findedParts))
  516. {
  517. return FALSE;
  518. }
  519. for (auto f : findedParts)
  520. {
  521. a_listParticles.push_back(f);
  522. }
  523. return TRUE;
  524. }
  525. BOOL COTSImageProcess::GetSegmentList(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSSegmentsList& a_listSegments)
  526. {
  527. ASSERT(a_pPixel);
  528. long nImgSize = a_nWidth * a_nHeight;
  529. a_listSegments.clear();
  530. //1. get segment line by line
  531. long nLine, nm, nn;
  532. long nStart = 0, nLength = 0;
  533. for (nLine = 0; nLine < a_nHeight; nLine++)
  534. {
  535. for (nm = 0; nm < a_nWidth; nm += (nLength + 1))
  536. {
  537. nLength = 0;
  538. // get start
  539. if (*(a_pPixel + nLine * a_nWidth + nm) != 0)
  540. {
  541. nStart = nm;
  542. nLength++;
  543. //get length
  544. for (nn = nm + 1; nn < a_nWidth; nn++)
  545. {
  546. // check if segment is over, break
  547. if (nLength != 0)
  548. {
  549. if (*(a_pPixel + nLine * a_nWidth + nn) == 0)
  550. break;
  551. }
  552. if (*(a_pPixel + nLine * a_nWidth + nn) != 0)
  553. {
  554. nLength++;
  555. }
  556. }
  557. // generate segment
  558. COTSSegmentPtr pSegment = COTSSegmentPtr(new COTSSegment(nLine + top, nStart + left, nLength));
  559. a_listSegments.push_back(pSegment);
  560. }
  561. else
  562. {
  563. continue;
  564. }
  565. }
  566. }
  567. if ((int)a_listSegments.size() == 0)
  568. {
  569. //LogErrorTrace(__FILE__, __LINE__, _T("no particle is found."));
  570. return FALSE;
  571. }
  572. return TRUE;
  573. }
  574. BOOL COTSImageProcess::GetFeatureList(COTSSegmentsList& a_listSegments, COTSFeatureList& a_listFeatures)
  575. {
  576. COTSSegmentsList listSegmentNew;
  577. std::map<long, COTSSegmentsList > mapOneLineSegments;
  578. for each (auto s in a_listSegments)
  579. {
  580. mapOneLineSegments[s->GetHeight()].push_back(s);//sorting all the segments base on the line number.
  581. }
  582. std::map<long, COTSSegmentsList >::iterator lineItr = mapOneLineSegments.begin();//find the highest line
  583. while (lineItr != mapOneLineSegments.end())
  584. {
  585. for (auto s = lineItr->second.begin(); s < lineItr->second.end(); )//find one segment of this line.
  586. {
  587. COTSSegmentPtr bottomSeg = *s;
  588. listSegmentNew.clear();
  589. listSegmentNew.push_back(*s);
  590. s = lineItr->second.erase(s);
  591. std::map<long, COTSSegmentsList >::iterator tempItr = lineItr;
  592. tempItr++;
  593. for (; tempItr != mapOneLineSegments.end(); tempItr++)//find all other lines of segments
  594. {
  595. if (tempItr->first - bottomSeg->GetHeight() > 1)
  596. {
  597. break;
  598. }
  599. for (auto nextLineSegment = tempItr->second.begin(); nextLineSegment < tempItr->second.end();)//find next line's all segments
  600. {
  601. if (((*nextLineSegment)->GetStart() - (bottomSeg->GetStart() + bottomSeg->GetLength())) > 1)
  602. {
  603. break;
  604. }
  605. if (bottomSeg->UpDownConection(**nextLineSegment))
  606. {
  607. listSegmentNew.push_back(*nextLineSegment);
  608. bottomSeg = *nextLineSegment;
  609. nextLineSegment = tempItr->second.erase(nextLineSegment);
  610. break;
  611. }
  612. if (tempItr->second.size() > 0)
  613. {
  614. nextLineSegment++;
  615. }
  616. else
  617. {
  618. break;
  619. }
  620. }
  621. }
  622. COTSFeaturePtr pFeature = COTSFeaturePtr(new COTSFeature());
  623. pFeature->SetSegmentsList(listSegmentNew);
  624. //check if this new feature is connected with other found feature.
  625. COTSSegmentPtr topSeg = listSegmentNew[0];//find the toppest segment of this new feature.
  626. COTSSegmentPtr bottomSegment = listSegmentNew[listSegmentNew.size() - 1];//find the lowest segment of this new feature.
  627. bool haveMerged = false;
  628. for each (auto f in a_listFeatures)
  629. {
  630. for (auto seg : f->GetSegmentsList())
  631. {
  632. if (bottomSegment->UpDownConection(*seg) || topSeg->UpDownConection(*seg))
  633. {
  634. COTSSegmentsList segs = f->GetSegmentsList();
  635. for (auto s : listSegmentNew)
  636. {
  637. segs.push_back(s);
  638. }
  639. f->SetSegmentsList(segs);
  640. haveMerged = true;
  641. break;
  642. }
  643. }
  644. if (haveMerged)
  645. {
  646. break;
  647. }
  648. }
  649. if (!haveMerged)
  650. {
  651. a_listFeatures.push_back(pFeature);
  652. }
  653. if (lineItr->second.size() == 0)
  654. {
  655. break;
  656. }
  657. }
  658. lineItr++;
  659. }
  660. return true;
  661. }
  662. BOOL COTSImageProcess::ChangeFeaturelist(COTSFeatureList& a_listFeatures, COTSParticleList& a_listParticle)
  663. {
  664. for (auto pFeature : a_listFeatures)
  665. {
  666. COTSParticlePtr pParticle = COTSParticlePtr(new COTSParticle());
  667. pParticle->SetFeature(pFeature);
  668. a_listParticle.push_back(pParticle);
  669. }
  670. if ((int)a_listParticle.size() == 0)
  671. {
  672. return FALSE;
  673. }
  674. return TRUE;
  675. }
  676. BOOL COTSImageProcess::CalcuParticleImagePropertes(COTSParticlePtr a_pOTSPart, double a_PixelSize)
  677. {
  678. //--------- convert this particle data to image data,construct an image only with this particle.------
  679. const int nExpand_Size = 3;
  680. const int nWhiteColor = 0;
  681. const int nThickness = 1;
  682. // lineType Type of the line
  683. const int nLineType = 8;
  684. // get rectangle of the particle
  685. CRect rect = a_pOTSPart->GetParticleRect();
  686. 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.
  687. {
  688. double w = 0, h = 0;
  689. w = (double)rect.Width()*a_PixelSize;
  690. h = (double)rect.Height()*a_PixelSize;
  691. a_pOTSPart->SetDMax(MAX(w, h));
  692. a_pOTSPart->SetDMin(MIN(w, h));
  693. a_pOTSPart->SetDMean((w + h) / 2);
  694. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  695. a_pOTSPart->SetDElong(MAX(w, h));
  696. a_pOTSPart->SetPerimeter((w+h)*2);
  697. a_pOTSPart->SetDPerp(MIN(w, h));
  698. a_pOTSPart->SetDInscr(MIN(w, h));
  699. a_pOTSPart->SetMinWidth(w);
  700. a_pOTSPart->SetMinHeight(h);
  701. return true;
  702. }
  703. // calculate the particle image data size, expand 3 pixel at the edge
  704. Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size , rect.Width() + nExpand_Size , CV_8U);
  705. // get the segment list
  706. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  707. for (auto pSegment : listSegment)
  708. {
  709. int nStart = pSegment->GetStart() - rect.left + nExpand_Size;
  710. int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;
  711. int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;
  712. line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);
  713. }
  714. //--------abstract the contour of the particle.
  715. vector<vector<Point>>contours;
  716. findContours(particleImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  717. 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.
  718. {
  719. double w = 0, h = 0;
  720. w = (double)rect.Width()*a_PixelSize;
  721. h = (double)rect.Height()*a_PixelSize;
  722. a_pOTSPart->SetDMax(MAX(w, h));
  723. a_pOTSPart->SetDMin(MIN(w, h));
  724. a_pOTSPart->SetDMean((w + h) / 2);
  725. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  726. a_pOTSPart->SetDElong(MAX(w, h));
  727. a_pOTSPart->SetPerimeter((w + h) * 2);
  728. a_pOTSPart->SetDPerp(MIN(w, h));
  729. a_pOTSPart->SetDInscr(MIN(w, h));
  730. a_pOTSPart->SetMinWidth(w);
  731. a_pOTSPart->SetMinHeight(h);
  732. return true;
  733. }
  734. int imaxcontour = 0, imax = 0;
  735. for (unsigned int i = 0; i < contours.size(); i++) {
  736. int itmp = contourArea(contours[i]);
  737. if (imaxcontour < itmp) {
  738. imax = i;
  739. imaxcontour = itmp;
  740. }
  741. }
  742. vector<Point > listEdge = contours[imax];
  743. vector<vector<Point>>Outcontours;
  744. Outcontours.push_back(listEdge);
  745. //---------calculate the minimium rectangle
  746. auto rRect = cv::minAreaRect(listEdge);
  747. Point2f p[4];
  748. rRect.points(p);
  749. int D_MIN =getDistance(p[0], p[1]);
  750. int D_MinRecLen = 0;//minareaRect's length(the longger side).
  751. for (int j = 0; j <= 2; j++)
  752. {
  753. //line(cvContourImg, p[j], p[(j + 1) % 4], Scalar(100, 100, 0), 2);
  754. int d = getDistance(p[j], p[j + 1]);
  755. if (d < D_MIN)
  756. {
  757. D_MIN = d;
  758. }
  759. if (d > D_MinRecLen)
  760. {
  761. D_MinRecLen = d;
  762. }
  763. }
  764. a_pOTSPart->SetDMin(D_MIN*a_PixelSize);
  765. a_pOTSPart->SetMinWidth(rRect.size.width);
  766. a_pOTSPart->SetMinHeight(rRect.size.height);
  767. //----------calculate the perimeter
  768. double d = arcLength(listEdge, true);
  769. a_pOTSPart->SetPerimeter(d*a_PixelSize);
  770. //-----------calculate the Max Diameter. Find the min enclosing circle first ,then find the two farthest circle connected point.
  771. Point2f center; float radius;
  772. minEnclosingCircle(listEdge, center, radius);
  773. //circle(cvContourImg, center, radius, Scalar(100), 2);
  774. std::vector <Point> outContour = listEdge;
  775. std::vector <Point> rst;
  776. for (unsigned int k = 0; k < outContour.size(); k++)
  777. {
  778. Point p = outContour[k];
  779. double d = sqrt(pow((p.x - center.x), 2) + pow((p.y - center.y), 2));
  780. if (fabs(d - radius) < 0.01)
  781. {
  782. rst.push_back(p);
  783. }
  784. }
  785. double D_MAX = 0;
  786. Point lineDmax[2];
  787. for (unsigned int m = 0; m < rst.size(); m++)
  788. {
  789. Point p = rst[m];
  790. for (unsigned int n = m + 1; n < rst.size(); n++)
  791. {
  792. Point p1 = rst[n];
  793. double d = sqrt(powf((p.x - p1.x), 2) + powf((p.y - p1.y), 2));
  794. if (d > D_MAX)
  795. {
  796. D_MAX = d;
  797. lineDmax[0] = p;
  798. lineDmax[1] = p1;
  799. }
  800. }
  801. }
  802. a_pOTSPart->SetDMax(D_MAX*a_PixelSize);
  803. //--------calculate the D_PERP property using the D_MAX's two endpoints.
  804. std::vector<Point> curve1;
  805. std::vector<Point> curve2;
  806. for (unsigned int i = 0; i < outContour.size(); i++)
  807. {
  808. Point pt = outContour[i];
  809. bool start = false;
  810. int clockwise = Side(lineDmax[0], lineDmax[1], pt);// devide these points into two group ,separate into the two sides.
  811. if (clockwise > 0)
  812. {
  813. curve1.push_back(pt);
  814. }
  815. else
  816. {
  817. curve2.push_back(pt);
  818. }
  819. }
  820. double d_perp1 = 0, d_perp2 = 0;
  821. for (unsigned int i = 0; i < curve1.size(); i++)
  822. {
  823. double d = getDist_P2L(curve1[i], lineDmax[0], lineDmax[1]);
  824. if (d > d_perp1)
  825. {
  826. d_perp1 = d;
  827. }
  828. }
  829. for (unsigned int i = 0; i < curve2.size(); i++)
  830. {
  831. double d = getDist_P2L(curve2[i], lineDmax[0], lineDmax[1]);
  832. if (d > d_perp2)
  833. {
  834. d_perp2 = d;
  835. }
  836. }
  837. a_pOTSPart->SetDPerp((d_perp1 + d_perp2)*a_PixelSize);
  838. //----------find the diameter of max inscribed circle
  839. int r;
  840. Point inscribeCirclecenter;
  841. FindInnerCircleInContour(outContour, inscribeCirclecenter, r);
  842. //--------------------------------------------------------calculate the xraypos !
  843. CRect rec = a_pOTSPart->GetParticleRect();
  844. a_pOTSPart->SetXRayPos(CPoint(inscribeCirclecenter.x - nExpand_Size + rec.left - 1, inscribeCirclecenter.y - nExpand_Size + rec.top - 1));
  845. a_pOTSPart->SetDInscr(r * 2 * a_PixelSize);
  846. //---------------calculate the image other caracater: length/width realArea/minRectangeArea etc. we can use these propertes to do forward process.
  847. double minRectArea = D_MIN * D_MinRecLen*a_PixelSize*a_PixelSize;//離鬼棍쌈앤近충생
  848. double fillRatio = a_pOTSPart->GetActualArea() / minRectArea;//茄셥충생宅離鬼棍쌈앤近충생궐,that's the fill rate.
  849. double lengthWidthRatio;
  850. lengthWidthRatio = (double)D_MinRecLen / D_MIN;//낀욱궐
  851. //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.
  852. bool isStripShape = false;
  853. double curveLength = 0;
  854. double D_MEAN=0;
  855. Moments mu;
  856. mu = moments(listEdge, false);
  857. int nx = mu.m10 / mu.m00;
  858. int ny = mu.m01 / mu.m00;
  859. //circle(cvcopyImg, Point(nx, ny), 1, (255), 1);
  860. Point ptCenter = Point((int)nx, (int)ny);
  861. if (pointPolygonTest(listEdge, ptCenter, false) != 1)// the center point doesn't contain in the contour, we think it as curve shape.
  862. {
  863. isStripShape = true;
  864. }
  865. /*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.
  866. {
  867. isStripShape = true;
  868. }*/
  869. 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.
  870. {
  871. isStripShape = true;
  872. }
  873. if (isStripShape)
  874. {
  875. 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.
  876. if (curveLength < D_MAX)
  877. {
  878. curveLength = D_MAX;
  879. }
  880. if (curveLength < MIN_DOUBLE_VALUE || a_pOTSPart->GetActualArea()<MIN_DOUBLE_VALUE)
  881. {
  882. D_MEAN = 0;
  883. }
  884. else
  885. {
  886. D_MEAN = a_pOTSPart->GetActualArea() / curveLength;
  887. }
  888. a_pOTSPart->SetDMean(D_MEAN*a_PixelSize);
  889. a_pOTSPart->SetFeretDiameter(D_MEAN*a_PixelSize);
  890. a_pOTSPart->SetDElong (curveLength*a_PixelSize);
  891. }
  892. else//it's a ball shape particle
  893. {
  894. curveLength = D_MAX;
  895. double ftd = 0, maxD = 0, minD = 0, dratio = 0;
  896. GetParticleAverageChord(outContour, a_PixelSize, ftd);
  897. a_pOTSPart->SetDMean(ftd);
  898. a_pOTSPart->SetFeretDiameter(ftd);
  899. a_pOTSPart->SetDElong(curveLength*a_PixelSize);
  900. }
  901. if (a_pOTSPart->GetAspectRatio() > 2)
  902. {
  903. double angle;
  904. if (rRect.size.width > rRect.size.height) // w > h
  905. {
  906. angle = abs(rRect.angle);
  907. }
  908. else
  909. {
  910. angle = 90.0 + abs(rRect.angle);
  911. }
  912. a_pOTSPart->SetOrientation(angle);
  913. }
  914. else
  915. {
  916. a_pOTSPart->SetOrientation(0);
  917. }
  918. return true;
  919. }
  920. void COTSImageProcess::ImshowImage(CBSEImgPtr img)
  921. {
  922. BYTE* data = img->GetImageDataPointer();
  923. //Mat cvImg;
  924. cv::Size s;
  925. s.width = img->GetImageSize().cx;
  926. s.height = img->GetImageSize().cy;
  927. Mat cvImg=Mat::zeros(s, CV_8U);
  928. cvImg.data = data;
  929. cv::imshow("dd", cvImg);
  930. cv::waitKey();
  931. }
  932. void COTSImageProcess::ImshowChartData(CBSEImgPtr img)
  933. {
  934. img->SetChartData();
  935. WORD* data = img->GetBSEChart();
  936. //Mat cvImg;
  937. cv::Size s;
  938. s.width = 255;
  939. s.height = 100;
  940. Mat cvImg = Mat::zeros(s, CV_8U);
  941. //cvImg.data = data;
  942. WORD nBSEChart[MAXBYTE];
  943. //1. get chart data
  944. linearSmooth5(data, nBSEChart, MAXBYTE);
  945. for (int i=1;i<255;i++)
  946. {
  947. line(cvImg, Point(i, 100-nBSEChart[i]), Point(i+1, 100-nBSEChart[i+1]), Scalar(nBlackColor), 1, 8);
  948. }
  949. cv::imshow("chart", cvImg);
  950. cv::waitKey();
  951. }
  952. BOOL COTSImageProcess::MergeBigBoundaryParticles(COTSFieldDataList allFields,double pixelSize,int scanFieldSize, CSize ResolutionSize, COTSParticleList& mergedParts)
  953. {
  954. class BorderPart
  955. {
  956. typedef std::shared_ptr<BorderPart> CBorderPartPtr;
  957. BorderPart(COTSParticlePtr p)
  958. {
  959. myPart = p;
  960. headerParticle = NULL;
  961. }
  962. public:
  963. COTSParticlePtr myPart;
  964. 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.
  965. static std::vector<CBorderPartPtr> ConvertPartToBorderPart(COTSParticleList parts)
  966. {
  967. static std::map<COTSParticle*, CBorderPartPtr> allborderPart;
  968. std::vector<CBorderPartPtr> borderParts;
  969. for (auto p : parts)
  970. {
  971. if (allborderPart.find(p.get()) == allborderPart.end())
  972. {
  973. auto borderp = CBorderPartPtr(new BorderPart(p));
  974. borderParts.push_back(borderp);
  975. allborderPart[p.get()] = borderp;
  976. }
  977. else
  978. {
  979. borderParts.push_back(allborderPart[p.get()]);
  980. }
  981. }
  982. return borderParts;
  983. }
  984. };
  985. auto FldMgr = new CFieldMgr(scanFieldSize, ResolutionSize);
  986. std::map<COTSParticle*, COTSParticleList> mapMergeParticles;//hold up all the boundary connected particles. the pair's first is also the member of these particles.
  987. std::map<COTSParticle*, COTSSegmentsList> mapMergedSegments;//hold up all the segment's corresponding clone in the connected particles.
  988. for (auto centerfld : allFields)
  989. {
  990. // find neighbor field on the left.
  991. auto leftFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::LEFT);
  992. if (leftFld != nullptr)
  993. {
  994. auto lParts = centerfld->GetLeftBorderedBigParticles();
  995. auto rParts = leftFld->GetRightBorderedBigParticles();
  996. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  997. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  998. for (auto leftp : leftParts)
  999. {
  1000. for (auto rightp : rightParts)
  1001. {
  1002. if (leftp->myPart->IsConnected(rightp->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::LEFT))
  1003. {
  1004. if (leftp->headerParticle != NULL)
  1005. {
  1006. if (rightp->headerParticle == NULL)
  1007. {
  1008. rightp->headerParticle = leftp->headerParticle;
  1009. mapMergeParticles[leftp->headerParticle].push_back(rightp->myPart);
  1010. }
  1011. }
  1012. else
  1013. {
  1014. if (rightp->headerParticle != NULL)
  1015. {
  1016. leftp->headerParticle = rightp->myPart.get();
  1017. mapMergeParticles[rightp->myPart.get()].push_back(leftp->myPart);
  1018. }
  1019. else
  1020. {
  1021. leftp->headerParticle = leftp->myPart.get();
  1022. rightp->headerParticle = leftp->myPart.get();
  1023. mapMergeParticles[leftp->myPart.get()].push_back(rightp->myPart);
  1024. }
  1025. }
  1026. }
  1027. }
  1028. }
  1029. }
  1030. //find neighbor field on the upward
  1031. auto upFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::UP);
  1032. if (upFld != nullptr)
  1033. {
  1034. auto topBorderParts = centerfld->GetTopBorderedBigParticles();
  1035. auto bottomBorderParts = upFld->GetBottomBorderedBigParticles();
  1036. auto upParts = BorderPart::ConvertPartToBorderPart(topBorderParts);
  1037. auto downParts = BorderPart::ConvertPartToBorderPart(bottomBorderParts);
  1038. for (auto upprt : upParts)
  1039. {
  1040. for (auto downprt : downParts)
  1041. {
  1042. if (upprt->myPart->IsConnected(downprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::UP))
  1043. {
  1044. if (upprt->headerParticle != NULL)
  1045. {
  1046. if (downprt->headerParticle == NULL)
  1047. {
  1048. downprt->headerParticle = upprt->headerParticle;
  1049. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1050. }
  1051. }
  1052. else
  1053. {
  1054. if (downprt->headerParticle != NULL)
  1055. {
  1056. upprt->headerParticle = downprt->headerParticle;
  1057. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1058. }
  1059. else
  1060. {
  1061. upprt->headerParticle = upprt->myPart.get();
  1062. downprt->headerParticle = upprt->myPart.get();
  1063. mapMergeParticles[upprt->myPart.get()].push_back(downprt->myPart);
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }
  1070. //find neighbor field on the downward.
  1071. auto downFld = FldMgr->FindNeighborField(allFields, centerfld,SORTING_DIRECTION::DOWN);
  1072. if (downFld != nullptr)
  1073. {
  1074. auto bottomParts = centerfld->GetBottomBorderedBigParticles();
  1075. auto topParts = downFld->GetTopBorderedBigParticles();
  1076. auto downParts = BorderPart::ConvertPartToBorderPart(bottomParts);
  1077. auto upParts= BorderPart::ConvertPartToBorderPart(topParts);
  1078. for (auto downprt : downParts)
  1079. {
  1080. for (auto upprt : upParts)
  1081. {
  1082. if (downprt->myPart->IsConnected(upprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::DOWN))
  1083. {
  1084. if (downprt->headerParticle != NULL)
  1085. {
  1086. if (upprt->headerParticle == NULL)
  1087. {
  1088. upprt->headerParticle = downprt->headerParticle;
  1089. mapMergeParticles[downprt->headerParticle].push_back(upprt->myPart);
  1090. }
  1091. }
  1092. else
  1093. {
  1094. if (upprt->headerParticle != NULL)
  1095. {
  1096. downprt->headerParticle = upprt->headerParticle;
  1097. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1098. }
  1099. else
  1100. {
  1101. downprt->headerParticle = downprt->myPart.get();
  1102. upprt->headerParticle = downprt->myPart.get();
  1103. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. }
  1110. //find neighbor field on the right.
  1111. auto rightFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::RIGHT);
  1112. if (rightFld != nullptr)
  1113. {
  1114. auto rParts = centerfld->GetRightBorderedBigParticles();
  1115. auto lParts = rightFld->GetLeftBorderedBigParticles();
  1116. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  1117. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  1118. for (auto rightprt : rightParts)
  1119. {
  1120. for (auto leftprt : leftParts)
  1121. {
  1122. if (rightprt->myPart->IsConnected(leftprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::RIGHT))
  1123. {
  1124. if (rightprt->headerParticle != NULL)
  1125. {
  1126. if (leftprt->headerParticle == NULL)
  1127. {
  1128. leftprt->headerParticle = rightprt->headerParticle;
  1129. mapMergeParticles[rightprt->headerParticle].push_back(leftprt->myPart);
  1130. }
  1131. }
  1132. else
  1133. {
  1134. if (leftprt->headerParticle != NULL)
  1135. {
  1136. rightprt->headerParticle = leftprt->headerParticle;
  1137. mapMergeParticles[leftprt->headerParticle].push_back(rightprt->myPart);
  1138. }
  1139. else
  1140. {
  1141. rightprt->headerParticle = rightprt->myPart.get();
  1142. leftprt->headerParticle = rightprt->myPart.get();
  1143. mapMergeParticles[rightprt->myPart.get()].push_back(leftprt->myPart);
  1144. }
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. /*for (auto particle : mapMergeParticles)
  1152. {
  1153. }*/
  1154. static int partTagId;
  1155. for (auto pair : mapMergeParticles)
  1156. {
  1157. struct EleAreaPercentage
  1158. {
  1159. EleAreaPercentage(double p, CElementChemistryPtr e)
  1160. {
  1161. areaPercentage = p;
  1162. eleData = e;
  1163. }
  1164. double areaPercentage;
  1165. CElementChemistryPtr eleData;
  1166. };
  1167. auto newPart = COTSParticlePtr(new COTSParticle());
  1168. COTSSegmentsList newSegs;
  1169. auto p = pair.first;
  1170. newPart->SetSEMPos(p->GetSEMPos());
  1171. //firstly,we sum up all the merged particles's area and get the represent string.
  1172. std::string partsStr = std::to_string(p->GetFieldId()) + ":" + std::to_string(p->GetAnalysisId());
  1173. double allPartArea = p->GetActualArea();//Get the first particle's area.
  1174. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1175. {
  1176. partsStr += "," + std::to_string(other->GetFieldId()) + ":" + std::to_string(other->GetAnalysisId());//Get the subparticles string such as "1:1,2:1" etc.
  1177. allPartArea += other->GetActualArea();//Get other particle's area
  1178. }
  1179. // calculate all the new segment's position.
  1180. std::vector <COTSParticle*> allSubParts;
  1181. allSubParts.push_back(p);
  1182. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1183. {
  1184. allSubParts.push_back(other.get());
  1185. }
  1186. for (auto subp : allSubParts)
  1187. {
  1188. int fid = subp->GetFieldId();
  1189. CPoint myFldPos;
  1190. for (auto f : allFields)//find this particle's filed.
  1191. {
  1192. if (f->GetId() == fid)
  1193. {
  1194. myFldPos = f->GetPosition();
  1195. }
  1196. }
  1197. int fldWidth = allFields[0]->Width;
  1198. int fldHeight = allFields[0]->Height;
  1199. CPoint fldLeftUpPos = CPoint(myFldPos.x + fldWidth / 2 , myFldPos.y + fldHeight / 2 );
  1200. for (auto s : subp->GetFeature()->GetSegmentsList())
  1201. {
  1202. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  1203. newseg->SetStart(s->GetStart() + fldLeftUpPos.x);
  1204. 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.
  1205. newseg->SetLength(s->GetLength());
  1206. newSegs.push_back(newseg);
  1207. }
  1208. }
  1209. COTSFeaturePtr newFeature = COTSFeaturePtr(new COTSFeature());
  1210. newFeature->SetSegmentsList(newSegs);
  1211. newPart->SetFeature(newFeature);
  1212. newPart->CalCoverRectFromSegment();
  1213. //second, we get all the element data and their area percentage .
  1214. std::map<std::string, std::vector<EleAreaPercentage>> mapEleData;
  1215. CPosXrayPtr pXray1 = p->GetXrayInfo();
  1216. if (pXray1 != nullptr)
  1217. {
  1218. for (auto ele : pXray1->GetElementQuantifyData())
  1219. {
  1220. mapEleData[ele->GetName().GetBuffer()].push_back(EleAreaPercentage(p->GetActualArea() / allPartArea, ele));
  1221. }
  1222. }
  1223. for (auto other : pair.second)
  1224. {
  1225. auto otherXray = other->GetXrayInfo();
  1226. if (otherXray != nullptr)
  1227. {
  1228. for (auto eledata : otherXray->GetElementQuantifyData())
  1229. {
  1230. mapEleData[eledata->GetName().GetBuffer()].push_back(EleAreaPercentage(other->GetActualArea() / allPartArea, eledata));
  1231. }
  1232. }
  1233. }
  1234. // third,we calculate all the element's new percentage data and get a new element chemistry list.
  1235. CElementChemistriesList newCheList;
  1236. for (auto eledata : mapEleData)
  1237. {
  1238. CElementChemistryPtr newEleche = CElementChemistryPtr(new CElementChemistry());
  1239. newEleche->SetName(CString(eledata.first.c_str()));
  1240. double newPercentage = 0;
  1241. for (auto d : eledata.second)
  1242. {
  1243. newPercentage += d.areaPercentage * d.eleData->GetPercentage();
  1244. }
  1245. newEleche->SetPercentage(newPercentage);
  1246. newCheList.push_back(newEleche);
  1247. }
  1248. CPosXrayPtr xray(new CPosXray());
  1249. xray->SetElementQuantifyData(newCheList);
  1250. newPart->SetXrayInfo(xray);
  1251. newPart->SetConnectedParticlesSequentialString(partsStr);
  1252. newPart->SetActualArea(allPartArea);
  1253. partTagId++;
  1254. newPart->SetParticleId(partTagId);
  1255. newPart->SetAnalysisId(partTagId);
  1256. std::string name = p->GetClassifyName();
  1257. newPart->SetClassifyName(name);
  1258. newPart->SetColor(p->GetColor());
  1259. mergedParts.push_back(newPart);
  1260. }
  1261. return true;
  1262. }
  1263. }