OTSImageProcess.cpp 45 KB

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