OTSImageProcess.cpp 44 KB

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