OTSImageProcess.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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. if (eigenPixelNum > 5)
  128. {
  129. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  130. pParticle->SetAveGray(nAveGray);
  131. auto fieldOTSRect = m_pFieldData->GetOTSRect();
  132. CPoint leftTop = fieldOTSRect.GetTopLeft();
  133. CRect rectInSinglefld = pParticle->GetParticleRect();
  134. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_pixelSize, leftTop.y - rectInSinglefld.top * a_pixelSize);
  135. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_pixelSize, leftTop.y - rectInSinglefld.bottom * a_pixelSize);
  136. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  137. pParticle->SetOTSRect(recInOTSCord);
  138. listParticleSearched.push_back(pParticle);
  139. }
  140. }
  141. m_pFieldData->SetParticleList(listParticleSearched);
  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. }