OTSImageProcess.cpp 45 KB

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