OTSImageProcess.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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. BOOL COTSImageProcess::SplitFieldImageIntoMatricsParticle(CBSEImgPtr fieldImg, double a_PixelSize, COTSFieldDataPtr outFldData)
  270. {
  271. int nWidthImg = fieldImg->GetWidth();
  272. int nHeightImg = fieldImg->GetHeight();
  273. outFldData->Width = nWidthImg;
  274. outFldData->Height = nHeightImg;
  275. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  276. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  277. double xrayStep = m_imageProcessParam->GetXrayStep();
  278. xrayStep = xrayStep / a_PixelSize;
  279. auto rect = fieldImg->GetImageRect();
  280. std::vector<CPoint> matrixPs;
  281. int colnum = ceil((double)rect.Width() / xrayStep + 0.5);
  282. if (colnum % 2 == 0) colnum += 1;//let the number to be an odd number.Then we can make the middle point in the center of the particle exactly.
  283. int rownum = ceil((double)rect.Height() / xrayStep + 0.5);
  284. if (rownum % 2 == 0) rownum += 1;
  285. CPoint theFirst = CPoint(rect.left - (colnum * xrayStep - rect.Width()) / 2 + xrayStep / 2, rect.top - (rownum * xrayStep - rect.Height()) / 2 + xrayStep / 2);
  286. for (int i = 0; i < rownum; i++)
  287. {
  288. for (int j = 0; j < colnum; j++)
  289. {
  290. double x = (double)theFirst.x + (double)j * xrayStep;
  291. double y = (double)theFirst.y + (double)i * xrayStep;
  292. CPoint thePoint = CPoint(x, y);
  293. matrixPs.push_back(thePoint);
  294. }
  295. }
  296. int i = 0;
  297. COTSParticleList matrixParts;
  298. for (auto point : matrixPs)
  299. {
  300. COTSParticlePtr part = COTSParticlePtr(new COTSParticle());
  301. COTSSegmentsList segs;
  302. for (int i = 0; i < xrayStep; i++)
  303. {
  304. COTSSegmentPtr seg = COTSSegmentPtr(new COTSSegment());
  305. seg->SetStart(point.x - xrayStep / 2);
  306. seg->SetLength(xrayStep);
  307. seg->SetHeight(point.y - xrayStep / 2 + i);
  308. //auto originalSegs = segsOnTheSameHeight[seg->GetHeight()];
  309. int currentH = seg->GetHeight();
  310. int segStart = seg->GetStart();
  311. int segEnd = seg->GetEnd();
  312. if (segStart < 0) segStart = 0;
  313. if (segEnd >= rect.Width()) segEnd = rect.Width()-1;
  314. if (currentH >= rect.Height()) continue;
  315. if (currentH < 0) continue;
  316. seg->SetStart(segStart);
  317. seg->SetEnd(segEnd);
  318. segs.push_back(seg);
  319. }
  320. if (segs.size() > 0)
  321. {
  322. part->GetFeature()->SetSegmentsList(segs);
  323. part->SetActualArea(xrayStep * xrayStep);
  324. part->CalXRayPos();
  325. part->SetFieldId(outFldData->GetId());
  326. part->SetAnalysisId(i);
  327. matrixParts.push_back(part);
  328. i++;
  329. }
  330. }
  331. outFldData->SetParticleList(matrixParts);
  332. return true;
  333. //-----------
  334. }
  335. CIntRangePtr COTSImageProcess::CalBackground(CBSEImgPtr m_pBSEImg)
  336. {
  337. auto ranges = CalcuGrayLevelRange(m_pBSEImg);
  338. return ranges[0];
  339. }
  340. std::vector<CIntRangePtr> COTSImageProcess::CalcuGrayLevelRange(CBSEImgPtr m_pBSEImg)
  341. {
  342. CIntRangePtr pBackground = CIntRangePtr(new CIntRange());
  343. WORD originChartData[MAXBYTE];
  344. WORD firstSmoothChart[MAXBYTE];
  345. WORD secondSmooth[MAXBYTE];
  346. //1. get chart data
  347. m_pBSEImg->SetChartData();
  348. memcpy(originChartData, m_pBSEImg->GetBSEChart(), sizeof(WORD) * MAXBYTE);
  349. originChartData[0] = 0;
  350. originChartData[254] = 0;
  351. linearSmooth5(originChartData, firstSmoothChart, MAXBYTE);
  352. linearSmooth5(firstSmoothChart, secondSmooth, MAXBYTE);
  353. //2. get down edge
  354. int nLengthEdge = MAXBYTE + 2;
  355. WORD n_aBSEChart[MAXBYTE + 2];
  356. memset(n_aBSEChart, 0, sizeof(WORD) * nLengthEdge);
  357. std::map<long, std::vector<int>> peakMap;// hold all the peaks in this spectrum which are sorted by there area.
  358. std::vector<int> currentUpSeries;
  359. std::vector<int> currentPeakSeries;
  360. // make sure the wave begin with up edge and end with down edge
  361. n_aBSEChart[0] = 0;
  362. n_aBSEChart[nLengthEdge - 1] = 0;
  363. memcpy(&n_aBSEChart[1], &secondSmooth, sizeof(WORD) * MAXBYTE);
  364. int nLengthCom = MAXBYTE + 1;
  365. // up edge
  366. for (int i = 0; i < nLengthCom; i++)
  367. {
  368. if (n_aBSEChart[i] <= n_aBSEChart[i + 1])//this is a upward edge
  369. {
  370. if (currentPeakSeries.size() > 0)
  371. {
  372. int seriesSize = currentPeakSeries.size();
  373. long area = 0;
  374. for (int i = 0; i < seriesSize; i++)
  375. {
  376. area = area + n_aBSEChart[currentPeakSeries[i]];
  377. }
  378. peakMap[area] = currentPeakSeries;
  379. currentPeakSeries.clear();
  380. }
  381. currentUpSeries.push_back(i + 1);// save all the continuous up edge
  382. }
  383. else//this is a downward edge
  384. {
  385. // encounter a downward edge means upward edge series end,
  386. if (currentUpSeries.size() > 0)
  387. {
  388. currentPeakSeries = currentUpSeries;
  389. currentUpSeries.clear();
  390. }
  391. currentPeakSeries.push_back(i + 1);
  392. }
  393. }
  394. if (currentPeakSeries.size() > 0)
  395. {
  396. int seriesSize = currentPeakSeries.size();
  397. long area = 0;
  398. for (int i = 0; i < seriesSize; i++)
  399. {
  400. area = area + n_aBSEChart[currentPeakSeries[i]];
  401. }
  402. peakMap[area] = currentPeakSeries;
  403. currentPeakSeries.clear();
  404. }
  405. std::vector<CIntRangePtr> ranges;
  406. std::map<long, std::vector<int>>::reverse_iterator it;
  407. for (it=peakMap.rbegin();it!=peakMap.rend();it++)
  408. {
  409. CIntRangePtr pRange = CIntRangePtr(new CIntRange());
  410. pRange->SetStart(it->second[0]);
  411. pRange->SetEnd(it->second[it->second.size()-1]);
  412. ranges.push_back(pRange);
  413. }
  414. return ranges;
  415. }
  416. void COTSImageProcess::GetSpecialGrayRangeImage(CBSEImgPtr a_pImgIn, CIntRangePtr a_SpecialGrayRange, CBSEImgPtr a_pBinImgOut, long& foundedPixelNum)
  417. {
  418. // the background pixel will be 0,and the other part will be 255.
  419. ASSERT(a_pImgIn);
  420. int nWidthImg = a_pImgIn->GetWidth();
  421. int nHeightImg = a_pImgIn->GetHeight();
  422. long nImgSize = nWidthImg * nHeightImg;
  423. BYTE* pTempImg = new BYTE[nImgSize];
  424. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  425. BYTE* pPixel = new byte[nImgSize];
  426. long nBGStart;
  427. long nBGEnd;
  428. long nNumParticle = 0;
  429. nBGStart = a_SpecialGrayRange->GetStart();
  430. nBGEnd = a_SpecialGrayRange->GetEnd();
  431. // delete background
  432. for (unsigned int i = 0; i < nImgSize; i++)
  433. {
  434. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  435. {
  436. pPixel[i] = 255;
  437. nNumParticle++;
  438. }
  439. else
  440. {
  441. pPixel[i] = 0;
  442. }
  443. }
  444. BErode3(pPixel, pTempImg, 5, nHeightImg, nWidthImg);
  445. BDilate3(pTempImg, pPixel, 5, nHeightImg, nWidthImg);
  446. a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);
  447. foundedPixelNum = nNumParticle;
  448. delete[] pTempImg;
  449. return;
  450. }
  451. void COTSImageProcess::RemoveBackGround(CBSEImgPtr a_pImgIn, COTSImageProcessParamPtr a_pImageProcessParam, CBSEImgPtr a_pBinImgOut/*,long& foundedPixelNum*/)
  452. {
  453. // the background pixel will be 0,and the other part will be 255.
  454. ASSERT(a_pImgIn);
  455. ASSERT(a_pImageProcessParam);
  456. int nWidthImg = a_pImgIn->GetWidth();
  457. int nHeightImg = a_pImgIn->GetHeight();
  458. long nImgSize = nWidthImg * nHeightImg;
  459. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  460. BYTE* pPixel= new BYTE[nImgSize];
  461. Mat srcImgMat = GetMatDataFromBseImg(a_pImgIn);
  462. Mat rstMat;
  463. long nBGStart;
  464. long nBGEnd;
  465. long nPartStart;
  466. long nPartEnd;
  467. long nNumParticle = 0;
  468. if (a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL)
  469. {
  470. nBGStart = a_pImageProcessParam->GetBGGray().GetStart();
  471. nBGEnd = a_pImageProcessParam->GetBGGray().GetEnd();
  472. nPartStart = a_pImageProcessParam->GetParticleGray().GetStart();
  473. nPartEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  474. //CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd);
  475. RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  476. pPixel = rstMat.data;
  477. }
  478. else
  479. {
  480. /*auto range = CalBackground(a_pImgIn);
  481. nBGStart = range->GetStart();
  482. nBGEnd = range->GetEnd();*/
  483. switch (a_pImageProcessParam->GetAutoBGRemoveType())
  484. {
  485. case OTS_AUTOBGREMOVE_TYPE::DOWNWARD:
  486. //RemoveBG_old(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  487. //CVRemoveBG(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  488. AutoRemove_background_OTS(srcImgMat, rstMat, 1);
  489. break;
  490. case OTS_AUTOBGREMOVE_TYPE::UPWARD:
  491. //RemoveBG_old(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  492. //CVRemoveBG(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  493. AutoRemove_background_OTS(srcImgMat, rstMat, 0);
  494. break;
  495. case OTS_AUTOBGREMOVE_TYPE::MIDDLE:
  496. //RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  497. //CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  498. AutoRemove_background_OTS(srcImgMat, rstMat, 2);
  499. break;
  500. default:
  501. break;
  502. }
  503. pPixel = rstMat.data;
  504. }
  505. a_pBinImgOut->SetImageData(pPixel,nWidthImg,nHeightImg);
  506. //foundedPixelNum = nNumParticle;
  507. //foundedPixelNum = 100;
  508. return ;
  509. }
  510. BOOL COTSImageProcess::GetParticles(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  511. {
  512. ASSERT(a_pPixel);
  513. if (!a_pPixel)
  514. {
  515. return FALSE;
  516. }
  517. //a_listParticles.clear();
  518. COTSParticleList findedParts;
  519. COTSSegmentsList listSegment;
  520. listSegment.clear();
  521. //1. get segment line by line
  522. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  523. {
  524. return FALSE;
  525. }
  526. if ((int)listSegment.size() == 0)
  527. {
  528. return FALSE;
  529. }
  530. //2. save the temp feature
  531. COTSFeatureList listFeature;
  532. listFeature.clear();
  533. if (!GetFeatureList(listSegment, listFeature))//get every feature for all the particle,the complete feature.
  534. {
  535. return FALSE;
  536. }
  537. if ((int)listFeature.size() == 0)
  538. {
  539. return FALSE;
  540. }
  541. /*COTSParticleList listParticles;
  542. listParticles.clear();*/
  543. if (!ChangeFeaturelist(listFeature, findedParts))
  544. {
  545. return FALSE;
  546. }
  547. for (auto f : findedParts)
  548. {
  549. a_listParticles.push_back(f);
  550. }
  551. return TRUE;
  552. }
  553. BOOL COTSImageProcess::GetOneParticleFromROI(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  554. {
  555. ASSERT(a_pPixel);
  556. if (!a_pPixel)
  557. {
  558. return FALSE;
  559. }
  560. //a_listParticles.clear();
  561. COTSParticleList findedParts;
  562. COTSSegmentsList listSegment;
  563. listSegment.clear();
  564. //1. get segment line by line
  565. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  566. {
  567. return FALSE;
  568. }
  569. if ((int)listSegment.size() == 0)
  570. {
  571. return FALSE;
  572. }
  573. //2. save the temp feature
  574. COTSFeatureList listFeature;
  575. listFeature.clear();
  576. COTSFeaturePtr fea = COTSFeaturePtr(new COTSFeature());
  577. fea->SetSegmentsList(listSegment);
  578. listFeature.push_back(fea);
  579. if ((int)listFeature.size() == 0)
  580. {
  581. return FALSE;
  582. }
  583. if (!ChangeFeaturelist(listFeature, findedParts))
  584. {
  585. return FALSE;
  586. }
  587. for (auto f : findedParts)
  588. {
  589. a_listParticles.push_back(f);
  590. }
  591. return TRUE;
  592. }
  593. BOOL COTSImageProcess::GetSegmentList(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSSegmentsList& a_listSegments)
  594. {
  595. ASSERT(a_pPixel);
  596. long nImgSize = a_nWidth * a_nHeight;
  597. a_listSegments.clear();
  598. //1. get segment line by line
  599. long nLine, nm, nn;
  600. long nStart = 0, nLength = 0;
  601. for (nLine = 0; nLine < a_nHeight; nLine++)
  602. {
  603. for (nm = 0; nm < a_nWidth; nm += (nLength + 1))
  604. {
  605. nLength = 0;
  606. // get start
  607. if (*(a_pPixel + nLine * a_nWidth + nm) != 0)
  608. {
  609. nStart = nm;
  610. nLength++;
  611. //get length
  612. for (nn = nm + 1; nn < a_nWidth; nn++)
  613. {
  614. // check if segment is over, break
  615. if (nLength != 0)
  616. {
  617. if (*(a_pPixel + nLine * a_nWidth + nn) == 0)
  618. break;
  619. }
  620. if (*(a_pPixel + nLine * a_nWidth + nn) != 0)
  621. {
  622. nLength++;
  623. }
  624. }
  625. // generate segment
  626. COTSSegmentPtr pSegment = COTSSegmentPtr(new COTSSegment(nLine + top, nStart + left, nLength));
  627. a_listSegments.push_back(pSegment);
  628. }
  629. else
  630. {
  631. continue;
  632. }
  633. }
  634. }
  635. if ((int)a_listSegments.size() == 0)
  636. {
  637. //LogErrorTrace(__FILE__, __LINE__, _T("no particle is found."));
  638. return FALSE;
  639. }
  640. return TRUE;
  641. }
  642. BOOL COTSImageProcess::GetFeatureList(COTSSegmentsList& a_listSegments, COTSFeatureList& a_listFeatures)
  643. {
  644. COTSSegmentsList listSegmentNew;
  645. std::map<long, COTSSegmentsList > mapOneLineSegments;
  646. for each (auto s in a_listSegments)
  647. {
  648. mapOneLineSegments[s->GetHeight()].push_back(s);//sorting all the segments base on the line number.
  649. }
  650. std::map<long, COTSSegmentsList >::iterator lineItr = mapOneLineSegments.begin();//find the highest line
  651. while (lineItr != mapOneLineSegments.end())
  652. {
  653. for (auto s = lineItr->second.begin(); s < lineItr->second.end(); )//find one segment of this line.
  654. {
  655. COTSSegmentPtr bottomSeg = *s;
  656. listSegmentNew.clear();
  657. listSegmentNew.push_back(*s);
  658. s = lineItr->second.erase(s);
  659. std::map<long, COTSSegmentsList >::iterator tempItr = lineItr;
  660. tempItr++;
  661. for (; tempItr != mapOneLineSegments.end(); tempItr++)//find all other lines of segments
  662. {
  663. if (tempItr->first - bottomSeg->GetHeight() > 1)
  664. {
  665. break;
  666. }
  667. for (auto nextLineSegment = tempItr->second.begin(); nextLineSegment < tempItr->second.end();)//find next line's all segments
  668. {
  669. if (((*nextLineSegment)->GetStart() - (bottomSeg->GetStart() + bottomSeg->GetLength())) > 1)
  670. {
  671. break;
  672. }
  673. if (bottomSeg->UpDownConection(**nextLineSegment))
  674. {
  675. listSegmentNew.push_back(*nextLineSegment);
  676. bottomSeg = *nextLineSegment;
  677. nextLineSegment = tempItr->second.erase(nextLineSegment);
  678. break;
  679. }
  680. if (tempItr->second.size() > 0)
  681. {
  682. nextLineSegment++;
  683. }
  684. else
  685. {
  686. break;
  687. }
  688. }
  689. }
  690. COTSFeaturePtr pFeature = COTSFeaturePtr(new COTSFeature());
  691. pFeature->SetSegmentsList(listSegmentNew);
  692. //check if this new feature is connected with other found feature.
  693. COTSSegmentPtr topSeg = listSegmentNew[0];//find the toppest segment of this new feature.
  694. COTSSegmentPtr bottomSegment = listSegmentNew[listSegmentNew.size() - 1];//find the lowest segment of this new feature.
  695. bool haveMerged = false;
  696. for each (auto f in a_listFeatures)
  697. {
  698. for (auto seg : f->GetSegmentsList())
  699. {
  700. if (bottomSegment->UpDownConection(*seg) || topSeg->UpDownConection(*seg))
  701. {
  702. COTSSegmentsList segs = f->GetSegmentsList();
  703. for (auto s : listSegmentNew)
  704. {
  705. segs.push_back(s);
  706. }
  707. f->SetSegmentsList(segs);
  708. haveMerged = true;
  709. break;
  710. }
  711. }
  712. if (haveMerged)
  713. {
  714. break;
  715. }
  716. }
  717. if (!haveMerged)
  718. {
  719. a_listFeatures.push_back(pFeature);
  720. }
  721. if (lineItr->second.size() == 0)
  722. {
  723. break;
  724. }
  725. }
  726. lineItr++;
  727. }
  728. return true;
  729. }
  730. BOOL COTSImageProcess::ChangeFeaturelist(COTSFeatureList& a_listFeatures, COTSParticleList& a_listParticle)
  731. {
  732. for (auto pFeature : a_listFeatures)
  733. {
  734. COTSParticlePtr pParticle = COTSParticlePtr(new COTSParticle());
  735. pParticle->SetFeature(pFeature);
  736. a_listParticle.push_back(pParticle);
  737. }
  738. if ((int)a_listParticle.size() == 0)
  739. {
  740. return FALSE;
  741. }
  742. return TRUE;
  743. }
  744. BOOL COTSImageProcess::CalcuParticleImagePropertes(COTSParticlePtr a_pOTSPart, double a_PixelSize)
  745. {
  746. //--------- convert this particle data to image data,construct an image only with this particle.------
  747. const int nExpand_Size = 3;
  748. const int nWhiteColor = 0;
  749. const int nThickness = 1;
  750. // lineType Type of the line
  751. const int nLineType = 8;
  752. // get rectangle of the particle
  753. CRect rect = a_pOTSPart->GetParticleRect();
  754. 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.
  755. {
  756. double w = 0, h = 0;
  757. w = (double)rect.Width()*a_PixelSize;
  758. h = (double)rect.Height()*a_PixelSize;
  759. a_pOTSPart->SetDMax(MAX(w, h));
  760. a_pOTSPart->SetDMin(MIN(w, h));
  761. a_pOTSPart->SetDMean((w + h) / 2);
  762. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  763. a_pOTSPart->SetDElong(MAX(w, h));
  764. a_pOTSPart->SetPerimeter((w+h)*2);
  765. a_pOTSPart->SetDPerp(MIN(w, h));
  766. a_pOTSPart->SetDInscr(MIN(w, h));
  767. a_pOTSPart->SetMinWidth(w);
  768. a_pOTSPart->SetMinHeight(h);
  769. return true;
  770. }
  771. // calculate the particle image data size, expand 3 pixel at the edge
  772. Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size , rect.Width() + nExpand_Size , CV_8U);
  773. // get the segment list
  774. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  775. for (auto pSegment : listSegment)
  776. {
  777. int nStart = pSegment->GetStart() - rect.left + nExpand_Size;
  778. int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;
  779. int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;
  780. line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);
  781. }
  782. //--------abstract the contour of the particle.
  783. vector<vector<Point>>contours;
  784. findContours(particleImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  785. 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.
  786. {
  787. double w = 0, h = 0;
  788. w = (double)rect.Width()*a_PixelSize;
  789. h = (double)rect.Height()*a_PixelSize;
  790. a_pOTSPart->SetDMax(MAX(w, h));
  791. a_pOTSPart->SetDMin(MIN(w, h));
  792. a_pOTSPart->SetDMean((w + h) / 2);
  793. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  794. a_pOTSPart->SetDElong(MAX(w, h));
  795. a_pOTSPart->SetPerimeter((w + h) * 2);
  796. a_pOTSPart->SetDPerp(MIN(w, h));
  797. a_pOTSPart->SetDInscr(MIN(w, h));
  798. a_pOTSPart->SetMinWidth(w);
  799. a_pOTSPart->SetMinHeight(h);
  800. return true;
  801. }
  802. int imaxcontour = 0, imax = 0;
  803. for (unsigned int i = 0; i < contours.size(); i++) {
  804. int itmp = contourArea(contours[i]);
  805. if (imaxcontour < itmp) {
  806. imax = i;
  807. imaxcontour = itmp;
  808. }
  809. }
  810. vector<Point > listEdge = contours[imax];
  811. vector<vector<Point>>Outcontours;
  812. Outcontours.push_back(listEdge);
  813. //---------calculate the minimium rectangle
  814. auto rRect = cv::minAreaRect(listEdge);
  815. Point2f p[4];
  816. rRect.points(p);
  817. int D_MIN =getDistance(p[0], p[1]);
  818. int D_MinRecLen = 0;//minareaRect's length(the longger side).
  819. for (int j = 0; j <= 2; j++)
  820. {
  821. //line(cvContourImg, p[j], p[(j + 1) % 4], Scalar(100, 100, 0), 2);
  822. int d = getDistance(p[j], p[j + 1]);
  823. if (d < D_MIN)
  824. {
  825. D_MIN = d;
  826. }
  827. if (d > D_MinRecLen)
  828. {
  829. D_MinRecLen = d;
  830. }
  831. }
  832. a_pOTSPart->SetDMin(D_MIN*a_PixelSize);
  833. a_pOTSPart->SetMinWidth(rRect.size.width);
  834. a_pOTSPart->SetMinHeight(rRect.size.height);
  835. //----------calculate the perimeter
  836. double d = arcLength(listEdge, true);
  837. a_pOTSPart->SetPerimeter(d*a_PixelSize);
  838. //-----------calculate the Max Diameter. Find the min enclosing circle first ,then find the two farthest circle connected point.
  839. Point2f center; float radius;
  840. minEnclosingCircle(listEdge, center, radius);
  841. //circle(cvContourImg, center, radius, Scalar(100), 2);
  842. std::vector <Point> outContour = listEdge;
  843. std::vector <Point> rst;
  844. for (unsigned int k = 0; k < outContour.size(); k++)
  845. {
  846. Point p = outContour[k];
  847. double d = sqrt(pow((p.x - center.x), 2) + pow((p.y - center.y), 2));
  848. if (fabs(d - radius) < 0.01)
  849. {
  850. rst.push_back(p);
  851. }
  852. }
  853. double D_MAX = 0;
  854. Point lineDmax[2];
  855. for (unsigned int m = 0; m < rst.size(); m++)
  856. {
  857. Point p = rst[m];
  858. for (unsigned int n = m + 1; n < rst.size(); n++)
  859. {
  860. Point p1 = rst[n];
  861. double d = sqrt(powf((p.x - p1.x), 2) + powf((p.y - p1.y), 2));
  862. if (d > D_MAX)
  863. {
  864. D_MAX = d;
  865. lineDmax[0] = p;
  866. lineDmax[1] = p1;
  867. }
  868. }
  869. }
  870. a_pOTSPart->SetDMax(D_MAX*a_PixelSize);
  871. //--------calculate the D_PERP property using the D_MAX's two endpoints.
  872. std::vector<Point> curve1;
  873. std::vector<Point> curve2;
  874. for (unsigned int i = 0; i < outContour.size(); i++)
  875. {
  876. Point pt = outContour[i];
  877. bool start = false;
  878. int clockwise = Side(lineDmax[0], lineDmax[1], pt);// devide these points into two group ,separate into the two sides.
  879. if (clockwise > 0)
  880. {
  881. curve1.push_back(pt);
  882. }
  883. else
  884. {
  885. curve2.push_back(pt);
  886. }
  887. }
  888. double d_perp1 = 0, d_perp2 = 0;
  889. for (unsigned int i = 0; i < curve1.size(); i++)
  890. {
  891. double d = getDist_P2L(curve1[i], lineDmax[0], lineDmax[1]);
  892. if (d > d_perp1)
  893. {
  894. d_perp1 = d;
  895. }
  896. }
  897. for (unsigned int i = 0; i < curve2.size(); i++)
  898. {
  899. double d = getDist_P2L(curve2[i], lineDmax[0], lineDmax[1]);
  900. if (d > d_perp2)
  901. {
  902. d_perp2 = d;
  903. }
  904. }
  905. a_pOTSPart->SetDPerp((d_perp1 + d_perp2)*a_PixelSize);
  906. //----------find the diameter of max inscribed circle
  907. int r;
  908. Point inscribeCirclecenter;
  909. FindInnerCircleInContour(outContour, inscribeCirclecenter, r);
  910. //--------------------------------------------------------calculate the xraypos !
  911. CRect rec = a_pOTSPart->GetParticleRect();
  912. a_pOTSPart->SetXRayPos(CPoint(inscribeCirclecenter.x - nExpand_Size + rec.left - 1, inscribeCirclecenter.y - nExpand_Size + rec.top - 1));
  913. a_pOTSPart->SetDInscr(r * 2 * a_PixelSize);
  914. //---------------calculate the image other caracater: length/width realArea/minRectangeArea etc. we can use these propertes to do forward process.
  915. double minRectArea = D_MIN * D_MinRecLen*a_PixelSize*a_PixelSize;//離鬼棍쌈앤近충생
  916. double fillRatio = a_pOTSPart->GetActualArea() / minRectArea;//茄셥충생宅離鬼棍쌈앤近충생궐,that's the fill rate.
  917. double lengthWidthRatio;
  918. lengthWidthRatio = (double)D_MinRecLen / D_MIN;//낀욱궐
  919. //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.
  920. bool isStripShape = false;
  921. double curveLength = 0;
  922. double D_MEAN=0;
  923. Moments mu;
  924. mu = moments(listEdge, false);
  925. int nx = mu.m10 / mu.m00;
  926. int ny = mu.m01 / mu.m00;
  927. //circle(cvcopyImg, Point(nx, ny), 1, (255), 1);
  928. Point ptCenter = Point((int)nx, (int)ny);
  929. if (pointPolygonTest(listEdge, ptCenter, false) != 1)// the center point doesn't contain in the contour, we think it as curve shape.
  930. {
  931. isStripShape = true;
  932. }
  933. /*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.
  934. {
  935. isStripShape = true;
  936. }*/
  937. 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.
  938. {
  939. isStripShape = true;
  940. }
  941. if (isStripShape)
  942. {
  943. 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.
  944. if (curveLength < D_MAX)
  945. {
  946. curveLength = D_MAX;
  947. }
  948. if (curveLength < MIN_DOUBLE_VALUE || a_pOTSPart->GetActualArea()<MIN_DOUBLE_VALUE)
  949. {
  950. D_MEAN = 0;
  951. }
  952. else
  953. {
  954. D_MEAN = a_pOTSPart->GetActualArea() / curveLength;
  955. }
  956. a_pOTSPart->SetDMean(D_MEAN*a_PixelSize);
  957. a_pOTSPart->SetFeretDiameter(D_MEAN*a_PixelSize);
  958. a_pOTSPart->SetDElong (curveLength*a_PixelSize);
  959. }
  960. else//it's a ball shape particle
  961. {
  962. curveLength = D_MAX;
  963. double ftd = 0, maxD = 0, minD = 0, dratio = 0;
  964. GetParticleAverageChord(outContour, a_PixelSize, ftd);
  965. a_pOTSPart->SetDMean(ftd);
  966. a_pOTSPart->SetFeretDiameter(ftd);
  967. a_pOTSPart->SetDElong(curveLength*a_PixelSize);
  968. }
  969. if (a_pOTSPart->GetAspectRatio() > 2)
  970. {
  971. double angle;
  972. if (rRect.size.width > rRect.size.height) // w > h
  973. {
  974. angle = abs(rRect.angle);
  975. }
  976. else
  977. {
  978. angle = 90.0 + abs(rRect.angle);
  979. }
  980. a_pOTSPart->SetOrientation(angle);
  981. }
  982. else
  983. {
  984. a_pOTSPart->SetOrientation(0);
  985. }
  986. return true;
  987. }
  988. void COTSImageProcess::ImshowImage(CBSEImgPtr img)
  989. {
  990. BYTE* data = img->GetImageDataPointer();
  991. //Mat cvImg;
  992. cv::Size s;
  993. s.width = img->GetImageSize().cx;
  994. s.height = img->GetImageSize().cy;
  995. Mat cvImg=Mat::zeros(s, CV_8U);
  996. cvImg.data = data;
  997. cv::imshow("dd", cvImg);
  998. cv::waitKey();
  999. }
  1000. void COTSImageProcess::ImshowChartData(CBSEImgPtr img)
  1001. {
  1002. img->SetChartData();
  1003. WORD* data = img->GetBSEChart();
  1004. //Mat cvImg;
  1005. cv::Size s;
  1006. s.width = 255;
  1007. s.height = 100;
  1008. Mat cvImg = Mat::zeros(s, CV_8U);
  1009. //cvImg.data = data;
  1010. WORD nBSEChart[MAXBYTE];
  1011. //1. get chart data
  1012. linearSmooth5(data, nBSEChart, MAXBYTE);
  1013. for (int i=1;i<255;i++)
  1014. {
  1015. line(cvImg, Point(i, 100-nBSEChart[i]), Point(i+1, 100-nBSEChart[i+1]), Scalar(nBlackColor), 1, 8);
  1016. }
  1017. cv::imshow("chart", cvImg);
  1018. cv::waitKey();
  1019. }
  1020. BOOL COTSImageProcess::MergeBigBoundaryParticles(COTSFieldDataList allFields,double pixelSize,int scanFieldSize, CSize ResolutionSize, COTSParticleList& mergedParts)
  1021. {
  1022. class BorderPart
  1023. {
  1024. typedef std::shared_ptr<BorderPart> CBorderPartPtr;
  1025. BorderPart(COTSParticlePtr p)
  1026. {
  1027. myPart = p;
  1028. headerParticle = NULL;
  1029. }
  1030. public:
  1031. COTSParticlePtr myPart;
  1032. 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.
  1033. static std::vector<CBorderPartPtr> ConvertPartToBorderPart(COTSParticleList parts)
  1034. {
  1035. static std::map<COTSParticle*, CBorderPartPtr> allborderPart;
  1036. std::vector<CBorderPartPtr> borderParts;
  1037. for (auto p : parts)
  1038. {
  1039. if (allborderPart.find(p.get()) == allborderPart.end())
  1040. {
  1041. auto borderp = CBorderPartPtr(new BorderPart(p));
  1042. borderParts.push_back(borderp);
  1043. allborderPart[p.get()] = borderp;
  1044. }
  1045. else
  1046. {
  1047. borderParts.push_back(allborderPart[p.get()]);
  1048. }
  1049. }
  1050. return borderParts;
  1051. }
  1052. };
  1053. auto FldMgr = new CFieldMgr(scanFieldSize, ResolutionSize);
  1054. std::map<COTSParticle*, COTSParticleList> mapMergeParticles;//hold up all the boundary connected particles. the pair's first is also the member of these particles.
  1055. std::map<COTSParticle*, COTSSegmentsList> mapMergedSegments;//hold up all the segment's corresponding clone in the connected particles.
  1056. for (auto centerfld : allFields)
  1057. {
  1058. // find neighbor field on the left.
  1059. auto leftFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::LEFT);
  1060. if (leftFld != nullptr)
  1061. {
  1062. auto lParts = centerfld->GetLeftBorderedBigParticles();
  1063. auto rParts = leftFld->GetRightBorderedBigParticles();
  1064. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  1065. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  1066. for (auto leftp : leftParts)
  1067. {
  1068. for (auto rightp : rightParts)
  1069. {
  1070. if (leftp->myPart->IsConnected(rightp->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::LEFT))
  1071. {
  1072. if (leftp->headerParticle != NULL)
  1073. {
  1074. if (rightp->headerParticle == NULL)
  1075. {
  1076. rightp->headerParticle = leftp->headerParticle;
  1077. mapMergeParticles[leftp->headerParticle].push_back(rightp->myPart);
  1078. }
  1079. }
  1080. else
  1081. {
  1082. if (rightp->headerParticle != NULL)
  1083. {
  1084. leftp->headerParticle = rightp->myPart.get();
  1085. mapMergeParticles[rightp->myPart.get()].push_back(leftp->myPart);
  1086. }
  1087. else
  1088. {
  1089. leftp->headerParticle = leftp->myPart.get();
  1090. rightp->headerParticle = leftp->myPart.get();
  1091. mapMergeParticles[leftp->myPart.get()].push_back(rightp->myPart);
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. }
  1098. //find neighbor field on the upward
  1099. auto upFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::UP);
  1100. if (upFld != nullptr)
  1101. {
  1102. auto topBorderParts = centerfld->GetTopBorderedBigParticles();
  1103. auto bottomBorderParts = upFld->GetBottomBorderedBigParticles();
  1104. auto upParts = BorderPart::ConvertPartToBorderPart(topBorderParts);
  1105. auto downParts = BorderPart::ConvertPartToBorderPart(bottomBorderParts);
  1106. for (auto upprt : upParts)
  1107. {
  1108. for (auto downprt : downParts)
  1109. {
  1110. if (upprt->myPart->IsConnected(downprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::UP))
  1111. {
  1112. if (upprt->headerParticle != NULL)
  1113. {
  1114. if (downprt->headerParticle == NULL)
  1115. {
  1116. downprt->headerParticle = upprt->headerParticle;
  1117. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1118. }
  1119. }
  1120. else
  1121. {
  1122. if (downprt->headerParticle != NULL)
  1123. {
  1124. upprt->headerParticle = downprt->headerParticle;
  1125. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1126. }
  1127. else
  1128. {
  1129. upprt->headerParticle = upprt->myPart.get();
  1130. downprt->headerParticle = upprt->myPart.get();
  1131. mapMergeParticles[upprt->myPart.get()].push_back(downprt->myPart);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. //find neighbor field on the downward.
  1139. auto downFld = FldMgr->FindNeighborField(allFields, centerfld,SORTING_DIRECTION::DOWN);
  1140. if (downFld != nullptr)
  1141. {
  1142. auto bottomParts = centerfld->GetBottomBorderedBigParticles();
  1143. auto topParts = downFld->GetTopBorderedBigParticles();
  1144. auto downParts = BorderPart::ConvertPartToBorderPart(bottomParts);
  1145. auto upParts= BorderPart::ConvertPartToBorderPart(topParts);
  1146. for (auto downprt : downParts)
  1147. {
  1148. for (auto upprt : upParts)
  1149. {
  1150. if (downprt->myPart->IsConnected(upprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::DOWN))
  1151. {
  1152. if (downprt->headerParticle != NULL)
  1153. {
  1154. if (upprt->headerParticle == NULL)
  1155. {
  1156. upprt->headerParticle = downprt->headerParticle;
  1157. mapMergeParticles[downprt->headerParticle].push_back(upprt->myPart);
  1158. }
  1159. }
  1160. else
  1161. {
  1162. if (upprt->headerParticle != NULL)
  1163. {
  1164. downprt->headerParticle = upprt->headerParticle;
  1165. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1166. }
  1167. else
  1168. {
  1169. downprt->headerParticle = downprt->myPart.get();
  1170. upprt->headerParticle = downprt->myPart.get();
  1171. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. //find neighbor field on the right.
  1179. auto rightFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::RIGHT);
  1180. if (rightFld != nullptr)
  1181. {
  1182. auto rParts = centerfld->GetRightBorderedBigParticles();
  1183. auto lParts = rightFld->GetLeftBorderedBigParticles();
  1184. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  1185. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  1186. for (auto rightprt : rightParts)
  1187. {
  1188. for (auto leftprt : leftParts)
  1189. {
  1190. if (rightprt->myPart->IsConnected(leftprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::RIGHT))
  1191. {
  1192. if (rightprt->headerParticle != NULL)
  1193. {
  1194. if (leftprt->headerParticle == NULL)
  1195. {
  1196. leftprt->headerParticle = rightprt->headerParticle;
  1197. mapMergeParticles[rightprt->headerParticle].push_back(leftprt->myPart);
  1198. }
  1199. }
  1200. else
  1201. {
  1202. if (leftprt->headerParticle != NULL)
  1203. {
  1204. rightprt->headerParticle = leftprt->headerParticle;
  1205. mapMergeParticles[leftprt->headerParticle].push_back(rightprt->myPart);
  1206. }
  1207. else
  1208. {
  1209. rightprt->headerParticle = rightprt->myPart.get();
  1210. leftprt->headerParticle = rightprt->myPart.get();
  1211. mapMergeParticles[rightprt->myPart.get()].push_back(leftprt->myPart);
  1212. }
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. }
  1219. /*for (auto particle : mapMergeParticles)
  1220. {
  1221. }*/
  1222. static int partTagId;
  1223. for (auto pair : mapMergeParticles)
  1224. {
  1225. struct EleAreaPercentage
  1226. {
  1227. EleAreaPercentage(double p, CElementChemistryPtr e)
  1228. {
  1229. areaPercentage = p;
  1230. eleData = e;
  1231. }
  1232. double areaPercentage;
  1233. CElementChemistryPtr eleData;
  1234. };
  1235. auto newPart = COTSParticlePtr(new COTSParticle());
  1236. COTSSegmentsList newSegs;
  1237. auto p = pair.first;
  1238. newPart->SetSEMPos(p->GetSEMPos());
  1239. //firstly,we sum up all the merged particles's area and get the represent string.
  1240. std::string partsStr = std::to_string(p->GetFieldId()) + ":" + std::to_string(p->GetAnalysisId());
  1241. double allPartArea = p->GetActualArea();//Get the first particle's area.
  1242. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1243. {
  1244. partsStr += "," + std::to_string(other->GetFieldId()) + ":" + std::to_string(other->GetAnalysisId());//Get the subparticles string such as "1:1,2:1" etc.
  1245. allPartArea += other->GetActualArea();//Get other particle's area
  1246. }
  1247. // calculate all the new segment's position.
  1248. std::vector <COTSParticle*> allSubParts;
  1249. allSubParts.push_back(p);
  1250. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1251. {
  1252. allSubParts.push_back(other.get());
  1253. }
  1254. for (auto subp : allSubParts)
  1255. {
  1256. int fid = subp->GetFieldId();
  1257. CPoint myFldPos;
  1258. for (auto f : allFields)//find this particle's filed.
  1259. {
  1260. if (f->GetId() == fid)
  1261. {
  1262. myFldPos = f->GetPosition();
  1263. }
  1264. }
  1265. int fldWidth = allFields[0]->Width;
  1266. int fldHeight = allFields[0]->Height;
  1267. CPoint fldLeftUpPos = CPoint(myFldPos.x + fldWidth / 2 , myFldPos.y + fldHeight / 2 );
  1268. for (auto s : subp->GetFeature()->GetSegmentsList())
  1269. {
  1270. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  1271. newseg->SetStart(s->GetStart() + fldLeftUpPos.x);
  1272. 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.
  1273. newseg->SetLength(s->GetLength());
  1274. newSegs.push_back(newseg);
  1275. }
  1276. }
  1277. COTSFeaturePtr newFeature = COTSFeaturePtr(new COTSFeature());
  1278. newFeature->SetSegmentsList(newSegs);
  1279. newPart->SetFeature(newFeature);
  1280. newPart->CalCoverRectFromSegment();
  1281. //second, we get all the element data and their area percentage .
  1282. std::map<std::string, std::vector<EleAreaPercentage>> mapEleData;
  1283. CPosXrayPtr pXray1 = p->GetXrayInfo();
  1284. if (pXray1 != nullptr)
  1285. {
  1286. for (auto ele : pXray1->GetElementQuantifyData())
  1287. {
  1288. mapEleData[ele->GetName().GetBuffer()].push_back(EleAreaPercentage(p->GetActualArea() / allPartArea, ele));
  1289. }
  1290. }
  1291. for (auto other : pair.second)
  1292. {
  1293. auto otherXray = other->GetXrayInfo();
  1294. if (otherXray != nullptr)
  1295. {
  1296. for (auto eledata : otherXray->GetElementQuantifyData())
  1297. {
  1298. mapEleData[eledata->GetName().GetBuffer()].push_back(EleAreaPercentage(other->GetActualArea() / allPartArea, eledata));
  1299. }
  1300. }
  1301. }
  1302. // third,we calculate all the element's new percentage data and get a new element chemistry list.
  1303. CElementChemistriesList newCheList;
  1304. for (auto eledata : mapEleData)
  1305. {
  1306. CElementChemistryPtr newEleche = CElementChemistryPtr(new CElementChemistry());
  1307. newEleche->SetName(CString(eledata.first.c_str()));
  1308. double newPercentage = 0;
  1309. for (auto d : eledata.second)
  1310. {
  1311. newPercentage += d.areaPercentage * d.eleData->GetPercentage();
  1312. }
  1313. newEleche->SetPercentage(newPercentage);
  1314. newCheList.push_back(newEleche);
  1315. }
  1316. CPosXrayPtr xray(new CPosXray());
  1317. xray->SetElementQuantifyData(newCheList);
  1318. newPart->SetXrayInfo(xray);
  1319. newPart->SetConnectedParticlesSequentialString(partsStr);
  1320. newPart->SetActualArea(allPartArea);
  1321. partTagId++;
  1322. newPart->SetParticleId(partTagId);
  1323. newPart->SetAnalysisId(partTagId);
  1324. std::string name = p->GetClassifyName();
  1325. newPart->SetClassifyName(name);
  1326. newPart->SetColor(p->GetColor());
  1327. mergedParts.push_back(newPart);
  1328. }
  1329. return true;
  1330. }
  1331. }