OTSImageProcess.cpp 43 KB

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