OTSImageProcess.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336
  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. #include "GreyPeak.h"
  14. namespace OTSIMGPROC
  15. {
  16. using namespace cv;
  17. using namespace std;
  18. const int nBlackColor = 255;
  19. namespace
  20. {
  21. cv::Mat GetMatDataFromParticles(COTSParticleList parts, int width, int height)
  22. {
  23. int rows, cols;
  24. cols = width;
  25. rows = height;
  26. BYTE* pPixel = new BYTE[width * height];
  27. Mat cvcopyImg = Mat(rows, cols, CV_8UC1, pPixel);
  28. cvcopyImg = Scalar::all(0);
  29. for (auto p : parts)
  30. {
  31. auto area = p->GetPixelArea();
  32. if (area > 100)
  33. {
  34. auto fea = p->GetFeature();
  35. auto segs = fea->GetSegmentsList();
  36. for (auto seg : segs)
  37. {
  38. auto row = seg->GetHeight();
  39. for (int i = 0; i < seg->GetLength(); i++)
  40. {
  41. auto col = seg->GetStart() + i;
  42. cvcopyImg.at<char>(row, col) = 255;
  43. }
  44. }
  45. }
  46. }
  47. return cvcopyImg;
  48. }
  49. }
  50. COTSImageProcess::COTSImageProcess(COTSImageProcessParamPtr a_pImageProcessParam)
  51. {
  52. m_imageProcessParam = a_pImageProcessParam;
  53. }
  54. COTSImageProcess::~COTSImageProcess()
  55. {
  56. }
  57. BOOL COTSImageProcess::RemoveBGByCVconnectivities(CBSEImgPtr inBSEImg, double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  58. {
  59. ASSERT(m_pFieldData);
  60. ASSERT(inBSEImg);
  61. ASSERT(m_imageProcessParam);
  62. int nWidthImg = inBSEImg->GetWidth();
  63. int nHeightImg = inBSEImg->GetHeight();
  64. m_pFieldData->Width = nWidthImg;
  65. m_pFieldData->Height = nHeightImg;
  66. long nImgSize = nWidthImg * nHeightImg;
  67. BYTE* pSrcImg = inBSEImg->GetImageDataPointer();
  68. BYTE* pTempImg = new BYTE[nImgSize];
  69. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  70. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  71. BinaryProcess(inBSEImg, m_imageProcessParam, imgNoBGBinary/*, nNumParticle*/);
  72. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  73. long nEigenGrayStart = m_imageProcessParam->GetParticleGray().GetStart();
  74. long nEigenGrayEnd = m_imageProcessParam->GetParticleGray().GetEnd();
  75. // get the area image
  76. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  77. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  78. Mat stats, centroids;
  79. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  80. double rMin = m_imageProcessParam->GetIncArea().GetStart()/2.0;
  81. double rMax = m_imageProcessParam->GetIncArea().GetEnd()/2.0;
  82. double partAreaMin = rMin * rMin * 3.14159;
  83. double partAreaMax = rMax * rMax * 3.14159;
  84. COTSParticleList listParticleOut;
  85. for (size_t i = 1; i < number; i++)
  86. {
  87. int center_x = centroids.at<double>(i, 0);
  88. int center_y = centroids.at<double>(i, 1);
  89. //矩形边框
  90. int x = stats.at<int>(i, CC_STAT_LEFT);
  91. int y = stats.at<int>(i, CC_STAT_TOP);
  92. int w = stats.at<int>(i, CC_STAT_WIDTH);
  93. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  94. int area = stats.at<int>(i, CC_STAT_AREA);
  95. double actualArea = area * a_pixelSize * a_pixelSize;
  96. if (actualArea >= partAreaMin && actualArea < partAreaMax)
  97. {
  98. Rect rectMax = Rect(x, y, w, h);
  99. Mat rectROI = labels(rectMax).clone();
  100. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  101. //exclude the point which intersect into this bounding box but is not in this group.
  102. int label = i;
  103. for (int row = 0; row < rectROI.rows; row++)
  104. {
  105. for (int col = 0; col < rectROI.cols; col++)
  106. {
  107. int v = rectROI.at<int>(row, col);
  108. if (v == label)
  109. {
  110. 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.
  111. }
  112. }
  113. }
  114. COTSParticleList roiParts;
  115. if (GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  116. {
  117. if (roiParts.size() > 0)
  118. {
  119. COTSParticlePtr roiPart = roiParts[0];//we will find only one part in the roi.
  120. roiPart->SetXRayPos(CPoint(center_x, center_y));
  121. CRect r = CRect(x, y, x + w, y + h);
  122. roiPart->SetParticleRect(r);
  123. roiPart->SetActualArea(actualArea);
  124. roiPart->SetPixelArea(area);
  125. listParticleOut.push_back(roiPart);
  126. }
  127. }
  128. }
  129. }
  130. int nTagId;
  131. COTSParticleList listParticleSearched;
  132. for (auto pParticle : listParticleOut)
  133. {
  134. COTSFeaturePtr pFeature = pParticle->GetFeature();
  135. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  136. long nPixelNum = 0;
  137. long eigenPixelNum = 0;
  138. long nPixelAll = 0;
  139. int nStartS = 0;
  140. int nHeightS = 0;
  141. int nLengthS = 0;
  142. for (auto pSegment : listSegment)
  143. {
  144. // get particle average gray
  145. nStartS = pSegment->GetStart();
  146. nHeightS = pSegment->GetHeight();
  147. nLengthS = pSegment->GetLength();
  148. nPixelNum += (long)nLengthS;
  149. for (unsigned int i = 0; i < nLengthS; i++)
  150. {
  151. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  152. nPixelAll += nValueTemp;
  153. if (nValueTemp >= nEigenGrayStart && nValueTemp <= nEigenGrayEnd)
  154. {
  155. eigenPixelNum += 1;
  156. }
  157. }
  158. }
  159. double r = m_imageProcessParam->GetIncArea().GetStart() / 2;
  160. double minPartArea = 3.14159 * r * r;
  161. if (eigenPixelNum* a_pixelSize*a_pixelSize > minPartArea)
  162. {
  163. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  164. pParticle->SetAveGray(nAveGray);
  165. auto fieldOTSRect = m_pFieldData->GetOTSRect();
  166. CPoint leftTop = fieldOTSRect.GetTopLeft();
  167. CRect rectInSinglefld = pParticle->GetParticleRect();
  168. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_pixelSize, leftTop.y - rectInSinglefld.top * a_pixelSize);
  169. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_pixelSize, leftTop.y - rectInSinglefld.bottom * a_pixelSize);
  170. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  171. pParticle->SetOTSRect(recInOTSCord);
  172. listParticleSearched.push_back(pParticle);
  173. }
  174. }
  175. m_pFieldData->SetParticleList(listParticleSearched);
  176. delete[]pTempImg;
  177. return TRUE;
  178. }
  179. BOOL COTSImageProcess::GetParticlesBySpecialGrayRange(CBSEImgPtr a_pBSEImg, CIntRangePtr a_grayRange,CDoubleRangePtr a_diameterRange,double a_pixelSize, COTSFieldDataPtr m_pFieldData)
  180. {
  181. ASSERT(m_pFieldData);
  182. ASSERT(a_pBSEImg);
  183. ASSERT(a_grayRange);
  184. int nWidthImg = a_pBSEImg->GetWidth();
  185. int nHeightImg = a_pBSEImg->GetHeight();
  186. m_pFieldData->Width = nWidthImg;
  187. m_pFieldData->Height = nHeightImg;
  188. long nImgSize = nWidthImg * nHeightImg;
  189. BYTE* pSrcImg = a_pBSEImg->GetImageDataPointer();
  190. BYTE* pTempImg = new BYTE[nImgSize];
  191. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  192. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  193. long nNumParticle = 0;
  194. GetSpecialGrayRangeImage(a_pBSEImg, *a_grayRange, imgNoBGBinary, nNumParticle);
  195. BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();
  196. if (nNumParticle == 0)
  197. {
  198. COTSParticleList listParticleEmpty;
  199. listParticleEmpty.clear();
  200. m_pFieldData->SetParticleList(listParticleEmpty);
  201. }
  202. else
  203. {
  204. // get the area image
  205. Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);
  206. Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);
  207. Mat stats, centroids;
  208. int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);
  209. double rStart = a_diameterRange->GetStart() / 2.0;
  210. double rEnd = a_diameterRange->GetEnd() / 2.0;
  211. double areaStart = rStart * rStart * 3.14159;
  212. double areaEnd = rEnd * rEnd * 3.14159;
  213. COTSParticleList listParticleOut;
  214. for (size_t i = 1; i < number; i++)
  215. {
  216. int center_x = centroids.at<double>(i, 0);
  217. int center_y = centroids.at<double>(i, 1);
  218. //矩形边框
  219. int x = stats.at<int>(i, CC_STAT_LEFT);
  220. int y = stats.at<int>(i, CC_STAT_TOP);
  221. int w = stats.at<int>(i, CC_STAT_WIDTH);
  222. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  223. int area = stats.at<int>(i, CC_STAT_AREA);
  224. double actualArea = area * a_pixelSize * a_pixelSize;
  225. if (actualArea >= areaStart && actualArea < areaEnd)
  226. {
  227. Rect rectMax = Rect(x, y, w, h);
  228. Mat rectROI = labels(rectMax).clone();
  229. Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());
  230. //exclude the point which intersect into this bounding box but is not in this group.
  231. int label = i;
  232. for (int row = 0; row < rectROI.rows; row++)
  233. {
  234. for (int col = 0; col < rectROI.cols; col++)
  235. {
  236. int v = rectROI.at<int>(row, col);
  237. if (v == label)
  238. {
  239. imageROI.at<uchar>(row, col) = 255;
  240. }
  241. }
  242. }
  243. COTSParticleList roiParts;
  244. if (!GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  245. {
  246. continue;
  247. }
  248. if (roiParts.size() > 0)
  249. {
  250. COTSParticlePtr roiPart = roiParts[0];
  251. roiPart->SetXRayPos(CPoint(center_x, center_y));
  252. CRect r = CRect(x, y, x + w, y + h);
  253. roiPart->SetParticleRect(r);
  254. roiPart->SetActualArea(actualArea);
  255. roiPart->SetPixelArea(area);
  256. listParticleOut.push_back(roiPart);
  257. }
  258. }
  259. }
  260. // form a image only have particles on
  261. //COTSSegmentsList listImage;
  262. for (auto pParticle : listParticleOut)
  263. {
  264. int area = pParticle->GetActualArea();
  265. double pActualArea = area ;
  266. COTSFeaturePtr pFeature = pParticle->GetFeature();
  267. COTSSegmentsList listSegment = pFeature->GetSegmentsList();
  268. long nPixelNum = 0;
  269. long nPixelAll = 0;
  270. int nStartS = 0;
  271. int nHeightS = 0;
  272. int nLengthS = 0;
  273. for (auto pSegment : listSegment)
  274. {
  275. // get particle average gray
  276. nStartS = pSegment->GetStart();
  277. nHeightS = pSegment->GetHeight();
  278. nLengthS = pSegment->GetLength();
  279. nPixelNum += (long)nLengthS;
  280. for (unsigned int i = 0; i < nLengthS; i++)
  281. {
  282. long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);
  283. nPixelAll += nValueTemp;
  284. }
  285. }
  286. BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);
  287. pParticle->SetAveGray(nAveGray);
  288. auto fieldOTSRect = m_pFieldData->GetOTSRect();
  289. CPoint leftTop = fieldOTSRect.GetTopLeft();
  290. CRect rectInSinglefld = pParticle->GetParticleRect();
  291. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_pixelSize, leftTop.y - rectInSinglefld.top * a_pixelSize);
  292. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_pixelSize, leftTop.y - rectInSinglefld.bottom * a_pixelSize);
  293. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  294. pParticle->SetOTSRect(recInOTSCord);
  295. }
  296. m_pFieldData->SetParticleList(listParticleOut);
  297. }
  298. delete[]pTempImg;
  299. return TRUE;
  300. }
  301. BOOL COTSImageProcess::SplitFieldImageIntoMatricsParticle(CBSEImgPtr fieldImg, double a_PixelSize, COTSFieldDataPtr outFldData)
  302. {
  303. int nWidthImg = fieldImg->GetWidth();
  304. int nHeightImg = fieldImg->GetHeight();
  305. outFldData->Width = nWidthImg;
  306. outFldData->Height = nHeightImg;
  307. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  308. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  309. double xrayStep = m_imageProcessParam->GetXrayStep();
  310. xrayStep = xrayStep / a_PixelSize;
  311. auto rect = fieldImg->GetImageRect();
  312. std::vector<CPoint> matrixPs;
  313. int colnum = ceil((double)rect.Width() / xrayStep + 0.5);
  314. if (colnum % 2 == 0) colnum += 1;//let the number to be an odd number.Then we can make the middle point in the center of the particle exactly.
  315. int rownum = ceil((double)rect.Height() / xrayStep + 0.5);
  316. if (rownum % 2 == 0) rownum += 1;
  317. CPoint theFirst = CPoint(rect.left - (colnum * xrayStep - rect.Width()) / 2 + xrayStep / 2, rect.top - (rownum * xrayStep - rect.Height()) / 2 + xrayStep / 2);
  318. for (int i = 0; i < rownum; i++)
  319. {
  320. for (int j = 0; j < colnum; j++)
  321. {
  322. double x = (double)theFirst.x + (double)j * xrayStep;
  323. double y = (double)theFirst.y + (double)i * xrayStep;
  324. CPoint thePoint = CPoint(x, y);
  325. matrixPs.push_back(thePoint);
  326. }
  327. }
  328. int i = 0;
  329. COTSParticleList matrixParts;
  330. for (auto point : matrixPs)
  331. {
  332. COTSParticlePtr part = COTSParticlePtr(new COTSParticle());
  333. COTSSegmentsList segs;
  334. for (int i = 0; i < xrayStep; i++)
  335. {
  336. COTSSegmentPtr seg = COTSSegmentPtr(new COTSSegment());
  337. seg->SetStart(point.x - xrayStep / 2);
  338. seg->SetLength(xrayStep);
  339. seg->SetHeight(point.y - xrayStep / 2 + i);
  340. //auto originalSegs = segsOnTheSameHeight[seg->GetHeight()];
  341. int currentH = seg->GetHeight();
  342. int segStart = seg->GetStart();
  343. int segEnd = seg->GetEnd();
  344. if (segStart < 0) segStart = 0;
  345. if (segEnd >= rect.Width()) segEnd = rect.Width()-1;
  346. if (currentH >= rect.Height()) continue;
  347. if (currentH < 0) continue;
  348. seg->SetStart(segStart);
  349. seg->SetEnd(segEnd);
  350. segs.push_back(seg);
  351. }
  352. if (segs.size() > 0)
  353. {
  354. part->GetFeature()->SetSegmentsList(segs);
  355. part->SetActualArea(xrayStep * xrayStep);
  356. part->CalXRayPos();
  357. part->SetFieldId(outFldData->GetId());
  358. part->SetAnalysisId(i);
  359. matrixParts.push_back(part);
  360. i++;
  361. }
  362. }
  363. outFldData->SetParticleList(matrixParts);
  364. return true;
  365. //-----------
  366. }
  367. BOOL COTSImageProcess::SplitRawImageIntoParticlesByWaterShed(CBSEImgPtr fieldImg, double a_PixelSize, COTSFieldDataPtr outFldData)
  368. {
  369. int nWidthImg = fieldImg->GetWidth();
  370. int nHeightImg = fieldImg->GetHeight();
  371. outFldData->Width = nWidthImg;
  372. outFldData->Height = nHeightImg;
  373. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  374. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  375. COTSParticleList listMainParticle;
  376. BinaryProcess(fieldImg, m_imageProcessParam, imgNoBGBinary);
  377. CDoubleRange areaRng = m_imageProcessParam->GetIncArea();
  378. GetParticlesFromBinaryImage(imgNoBGBinary, areaRng, a_PixelSize, listMainParticle);
  379. outFldData->SetParticleList(listMainParticle);
  380. CBSEImgPtr noBgImg = CBSEImgPtr(new CBSEImg(fieldImg->GetImageRect()));
  381. RemoveBackGround(fieldImg, noBgImg);
  382. BlurImage(noBgImg);
  383. std::vector<CPoint> seeds;
  384. seeds.clear();
  385. FindSeedsByGrayScale(noBgImg, a_PixelSize, seeds);
  386. Mat matImg = GetMatDataFromBseImg(noBgImg);
  387. Mat marks(matImg.size(), CV_32S);
  388. marks = Scalar::all(0);
  389. for (int index = 0; index < seeds.size(); index++)
  390. {
  391. auto p = seeds[index];
  392. marks.at<INT32>(p.y, p.x) = index + 10;
  393. }
  394. Mat imageGray3;
  395. cv::cvtColor(matImg, imageGray3, cv::COLOR_GRAY2RGB);//灰度转换 opencv4
  396. cv::watershed(imageGray3, marks);
  397. auto matBinNobg = GetMatDataFromParticles(listMainParticle, nWidthImg, nHeightImg);
  398. //the first "long" is the index of particle,the second "long" is the row number of the segment, the third "long" is the sequence of the pixel.
  399. std::map<long, std::map<long, std::set<long>>> pixelMap;
  400. for (int i = 0; i < marks.rows; i++)
  401. {
  402. for (int j = 0; j < marks.cols; j++)
  403. {
  404. if (matBinNobg.at<char>(i, j) == 0)
  405. {
  406. marks.at<int>(i, j) = 0;
  407. continue;
  408. }
  409. long index = marks.at<int>(i, j);
  410. if (index == -1)//if this pixel is on the border,then it will be absorbed by it's neighbor.
  411. {
  412. if (i + 1 < marks.rows && marks.at<int>(i + 1, j) != -1 && matBinNobg.at<char>(i + 1, j) != 0)
  413. {
  414. index = marks.at<int>(i + 1, j);
  415. }
  416. else if (j + 1 < marks.cols && marks.at<int>(i, j + 1) != -1 && matBinNobg.at<char>(i, j + 1) != 0)
  417. {
  418. index = marks.at<int>(i, j + 1);
  419. }
  420. else if (i > 0 && marks.at<int>(i - 1, j) != -1 && matBinNobg.at<char>(i - 1, j) != 0)
  421. {
  422. index = marks.at<int>(i - 1, j);
  423. }
  424. else if (j > 0 && marks.at<int>(i, j - 1) != -1 && matBinNobg.at<char>(i, j - 1) != 0)
  425. {
  426. index = marks.at<int>(i, j - 1);
  427. }
  428. marks.at<int>(i, j) = index;
  429. }
  430. pixelMap[index][i].insert(j);
  431. }
  432. }
  433. COTSParticleList listParticleOut;
  434. for (auto it = pixelMap.begin(); it != pixelMap.end(); it++)
  435. {
  436. if (it->first == -1) continue;
  437. if (it->first == 0) continue;
  438. auto pixelsegs = it->second;
  439. COTSParticlePtr newGrain = COTSParticlePtr(new COTSParticle());
  440. COTSFeaturePtr newFea = COTSFeaturePtr(new COTSFeature());
  441. for (auto pixelseg : pixelsegs)
  442. {
  443. auto start = (*pixelseg.second.begin());
  444. for (auto pix = pixelseg.second.begin(); pix != pixelseg.second.end(); pix++)
  445. {
  446. auto curNode = pix;
  447. ++curNode;
  448. if ((curNode) != pixelseg.second.end())
  449. {
  450. if (*curNode - *pix > 1)
  451. {
  452. COTSSegmentPtr seg = COTSSegmentPtr(new COTSSegment());
  453. seg->SetStart(start);
  454. seg->SetEnd(*pix);
  455. seg->SetHeight(pixelseg.first);
  456. newFea->AddSegment(seg);
  457. start = *curNode;
  458. }
  459. }
  460. else
  461. {
  462. COTSSegmentPtr seg = COTSSegmentPtr(new COTSSegment());
  463. seg->SetStart(start);
  464. seg->SetEnd(*pix);
  465. seg->SetHeight(pixelseg.first);
  466. newFea->AddSegment(seg);
  467. }
  468. }
  469. }
  470. newGrain->SetFeature(newFea);
  471. newGrain->CalXRayPos();
  472. CPoint pos = newGrain->GetXRayPos();
  473. for (auto mp : listMainParticle)
  474. {
  475. auto fieldOTSRect = outFldData->GetOTSRect();
  476. CPoint leftTop = fieldOTSRect.GetTopLeft();
  477. CRect rectInSinglefld = mp->GetParticleRect();
  478. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_PixelSize, leftTop.y - rectInSinglefld.top * a_PixelSize);
  479. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_PixelSize, leftTop.y - rectInSinglefld.bottom * a_PixelSize);
  480. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  481. mp->SetOTSRect(recInOTSCord);
  482. mp->SetFieldId(outFldData->GetId());
  483. if (mp->IfContain(pos))
  484. {
  485. CRect rectInSinglefld = newGrain->GetParticleRect();
  486. CPoint OTSLeftTop = CPoint(leftTop.x + rectInSinglefld.left * a_PixelSize, leftTop.y - rectInSinglefld.top * a_PixelSize);
  487. CPoint OTSRightBottom = CPoint(leftTop.x + rectInSinglefld.right * a_PixelSize, leftTop.y - rectInSinglefld.bottom * a_PixelSize);
  488. COTSRect recInOTSCord = COTSRect(OTSLeftTop, OTSRightBottom);
  489. newGrain->SetFieldId(mp->GetFieldId());
  490. newGrain->SetOTSRect(recInOTSCord);
  491. mp->AddSubParticle(newGrain);
  492. break;
  493. }
  494. }
  495. }
  496. return true;
  497. }
  498. CIntRangePtr COTSImageProcess::CalBackground(CBSEImgPtr m_pBSEImg)
  499. {
  500. auto ranges = CalcuGrayLevelRange(m_pBSEImg);
  501. return ranges[0];
  502. }
  503. std::vector<CIntRangePtr> COTSImageProcess::CalcuGrayLevelRange(CBSEImgPtr m_pBSEImg)
  504. {
  505. CIntRangePtr pBackground = CIntRangePtr(new CIntRange());
  506. WORD originChartData[MAXBYTE];
  507. WORD firstSmoothChart[MAXBYTE];
  508. WORD secondSmooth[MAXBYTE];
  509. //1. get chart data
  510. m_pBSEImg->SetChartData();
  511. memcpy(originChartData, m_pBSEImg->GetBSEChart(), sizeof(WORD) * MAXBYTE);
  512. originChartData[0] = 0;
  513. originChartData[254] = 0;
  514. linearSmooth5(originChartData, firstSmoothChart, MAXBYTE);
  515. linearSmooth5(firstSmoothChart, secondSmooth, MAXBYTE);
  516. //2. get down edge
  517. int nLengthEdge = MAXBYTE + 2;
  518. WORD n_aBSEChart[MAXBYTE + 2];
  519. memset(n_aBSEChart, 0, sizeof(WORD) * nLengthEdge);
  520. std::map<long, std::vector<int>> peakMap;// hold all the peaks in this spectrum which are sorted by there area.
  521. std::vector<int> currentUpSeries;
  522. std::vector<int> currentPeakSeries;
  523. // make sure the wave begin with up edge and end with down edge
  524. n_aBSEChart[0] = 0;
  525. n_aBSEChart[nLengthEdge - 1] = 0;
  526. memcpy(&n_aBSEChart[1], &secondSmooth, sizeof(WORD) * MAXBYTE);
  527. int nLengthCom = MAXBYTE + 1;
  528. // up edge
  529. for (int i = 0; i < nLengthCom; i++)
  530. {
  531. if (n_aBSEChart[i] <= n_aBSEChart[i + 1])//this is a upward edge
  532. {
  533. if (currentPeakSeries.size() > 0)
  534. {
  535. int seriesSize = currentPeakSeries.size();
  536. long area = 0;
  537. for (int i = 0; i < seriesSize; i++)
  538. {
  539. area = area + n_aBSEChart[currentPeakSeries[i]];
  540. }
  541. peakMap[area] = currentPeakSeries;
  542. currentPeakSeries.clear();
  543. }
  544. currentUpSeries.push_back(i + 1);// save all the continuous up edge
  545. }
  546. else//this is a downward edge
  547. {
  548. // encounter a downward edge means upward edge series end,
  549. if (currentUpSeries.size() > 0)
  550. {
  551. currentPeakSeries = currentUpSeries;
  552. currentUpSeries.clear();
  553. }
  554. currentPeakSeries.push_back(i + 1);
  555. }
  556. }
  557. if (currentPeakSeries.size() > 0)
  558. {
  559. int seriesSize = currentPeakSeries.size();
  560. long area = 0;
  561. for (int i = 0; i < seriesSize; i++)
  562. {
  563. area = area + n_aBSEChart[currentPeakSeries[i]];
  564. }
  565. peakMap[area] = currentPeakSeries;
  566. currentPeakSeries.clear();
  567. }
  568. std::vector<CIntRangePtr> ranges;
  569. std::map<long, std::vector<int>>::reverse_iterator it;
  570. for (it=peakMap.rbegin();it!=peakMap.rend();it++)
  571. {
  572. CIntRangePtr pRange = CIntRangePtr(new CIntRange());
  573. pRange->SetStart(it->second[0]);
  574. pRange->SetEnd(it->second[it->second.size()-1]);
  575. ranges.push_back(pRange);
  576. }
  577. return ranges;
  578. }
  579. void COTSImageProcess::GetSpecialGrayRangeImage(CBSEImgPtr a_pImgIn, CIntRange a_SpecialGrayRange, CBSEImgPtr a_pBinImgOut, long& foundedPixelNum)
  580. {
  581. // the background pixel will be 0,and the other part will be 255.
  582. ASSERT(a_pImgIn);
  583. int nWidthImg = a_pImgIn->GetWidth();
  584. int nHeightImg = a_pImgIn->GetHeight();
  585. long nImgSize = nWidthImg * nHeightImg;
  586. BYTE* pTempImg = new BYTE[nImgSize];
  587. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  588. BYTE* pPixel = new byte[nImgSize];
  589. long nBGStart;
  590. long nBGEnd;
  591. long nNumParticle = 0;
  592. nBGStart = a_SpecialGrayRange.GetStart();
  593. nBGEnd = a_SpecialGrayRange.GetEnd();
  594. // delete background
  595. for (unsigned int i = 0; i < nImgSize; i++)
  596. {
  597. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  598. {
  599. pPixel[i] = 255;
  600. nNumParticle++;
  601. }
  602. else
  603. {
  604. pPixel[i] = 0;
  605. }
  606. }
  607. BErode3(pPixel, pTempImg, 5, nHeightImg, nWidthImg);
  608. BDilate3(pTempImg, pPixel, 5, nHeightImg, nWidthImg);
  609. a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);
  610. foundedPixelNum = nNumParticle;
  611. delete[] pTempImg;
  612. return;
  613. }
  614. void COTSImageProcess::BinaryProcess(CBSEImgPtr a_pImgIn, COTSImageProcessParamPtr a_pImageProcessParam, CBSEImgPtr a_pBinImgOut/*,long& foundedPixelNum*/)
  615. {
  616. // the background pixel will be 0,and the other part will be 255.
  617. ASSERT(a_pImgIn);
  618. ASSERT(a_pImageProcessParam);
  619. int nWidthImg = a_pImgIn->GetWidth();
  620. int nHeightImg = a_pImgIn->GetHeight();
  621. long nImgSize = nWidthImg * nHeightImg;
  622. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  623. BYTE* pPixel= new BYTE[nImgSize];
  624. Mat srcImgMat = GetMatDataFromBseImg(a_pImgIn);
  625. Mat rstMat;
  626. long nBGStart;
  627. long nBGEnd;
  628. long nPartStart;
  629. long nPartEnd;
  630. long nNumParticle = 0;
  631. if (a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL || a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::WaterShed)
  632. {
  633. nBGStart = a_pImageProcessParam->GetBGGray().GetStart();
  634. nBGEnd = a_pImageProcessParam->GetBGGray().GetEnd();
  635. nPartStart = a_pImageProcessParam->GetParticleGray().GetStart();
  636. nPartEnd = a_pImageProcessParam->GetParticleGray().GetEnd();
  637. //CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd);
  638. RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  639. pPixel = rstMat.data;
  640. }
  641. else
  642. {
  643. switch (a_pImageProcessParam->GetAutoBGRemoveType())
  644. {
  645. case OTS_AUTOBGREMOVE_TYPE::DOWNWARD:
  646. //RemoveBG_old(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  647. //CVRemoveBG(srcImgMat, rstMat, 0, nBGEnd, nNumParticle);
  648. AutoRemove_background_OTS(srcImgMat, rstMat, 1);
  649. break;
  650. case OTS_AUTOBGREMOVE_TYPE::UPWARD:
  651. //RemoveBG_old(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  652. //CVRemoveBG(srcImgMat, rstMat, nBGStart, 255, nNumParticle);
  653. AutoRemove_background_OTS(srcImgMat, rstMat, 0);
  654. break;
  655. case OTS_AUTOBGREMOVE_TYPE::MIDDLE:
  656. //RemoveBG_old(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  657. //CVRemoveBG(srcImgMat, rstMat, nBGStart, nBGEnd, nNumParticle);
  658. AutoRemove_background_OTS(srcImgMat, rstMat, 2);
  659. break;
  660. default:
  661. break;
  662. }
  663. pPixel = rstMat.data;
  664. }
  665. a_pBinImgOut->SetImageData(pPixel,nWidthImg,nHeightImg);
  666. return ;
  667. }
  668. void COTSImageProcess::RemoveBackGround(CBSEImgPtr a_pImgIn, CBSEImgPtr a_pBinImgOut)
  669. {
  670. // the background pixel will be 0,and the other part will be 255.
  671. ASSERT(a_pImgIn);
  672. ASSERT(m_imageProcessParam);
  673. int nWidthImg = a_pImgIn->GetWidth();
  674. int nHeightImg = a_pImgIn->GetHeight();
  675. long nImgSize = nWidthImg * nHeightImg;
  676. BYTE* pTempImg = new BYTE[nImgSize];
  677. BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();
  678. BYTE* pPixel = new byte[nImgSize];
  679. long nBGStart;
  680. long nBGEnd;
  681. long nPartStart;
  682. long nPartEnd;
  683. long nNumParticle = 0;
  684. if (m_imageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL|| m_imageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::WaterShed)
  685. {
  686. nBGStart = m_imageProcessParam->GetBGGray().GetStart();
  687. nBGEnd = m_imageProcessParam->GetBGGray().GetEnd();
  688. nPartStart = m_imageProcessParam->GetParticleGray().GetStart();
  689. nPartEnd = m_imageProcessParam->GetParticleGray().GetEnd();
  690. // delete background
  691. for (unsigned int i = 0; i < nImgSize; i++)
  692. {
  693. if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)
  694. {
  695. pPixel[i] = 0;
  696. }
  697. else
  698. {
  699. pPixel[i] = pSrcImg[i];
  700. nNumParticle++;
  701. }
  702. if (pSrcImg[i]<nPartStart || pSrcImg[i]>nPartEnd)
  703. {
  704. pPixel[i] = 0;
  705. }
  706. }
  707. }
  708. a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);
  709. delete[] pTempImg;
  710. return;
  711. }
  712. BOOL COTSImageProcess::GetParticles(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  713. {
  714. ASSERT(a_pPixel);
  715. if (!a_pPixel)
  716. {
  717. return FALSE;
  718. }
  719. //a_listParticles.clear();
  720. COTSParticleList findedParts;
  721. COTSSegmentsList listSegment;
  722. listSegment.clear();
  723. //1. get segment line by line
  724. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  725. {
  726. return FALSE;
  727. }
  728. if ((int)listSegment.size() == 0)
  729. {
  730. return FALSE;
  731. }
  732. //2. save the temp feature
  733. COTSFeatureList listFeature;
  734. listFeature.clear();
  735. if (!GetFeatureList(listSegment, listFeature))//get every feature for all the particle,the complete feature.
  736. {
  737. return FALSE;
  738. }
  739. if ((int)listFeature.size() == 0)
  740. {
  741. return FALSE;
  742. }
  743. /*COTSParticleList listParticles;
  744. listParticles.clear();*/
  745. if (!ChangeFeaturelist(listFeature, findedParts))
  746. {
  747. return FALSE;
  748. }
  749. for (auto f : findedParts)
  750. {
  751. a_listParticles.push_back(f);
  752. }
  753. return TRUE;
  754. }
  755. BOOL COTSImageProcess::GetOneParticleFromROI(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)
  756. {
  757. ASSERT(a_pPixel);
  758. if (!a_pPixel)
  759. {
  760. return FALSE;
  761. }
  762. //a_listParticles.clear();
  763. COTSParticleList findedParts;
  764. COTSSegmentsList listSegment;
  765. listSegment.clear();
  766. //1. get segment line by line
  767. if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))
  768. {
  769. return FALSE;
  770. }
  771. if ((int)listSegment.size() == 0)
  772. {
  773. return FALSE;
  774. }
  775. //2. save the temp feature
  776. COTSFeatureList listFeature;
  777. listFeature.clear();
  778. COTSFeaturePtr fea = COTSFeaturePtr(new COTSFeature());
  779. fea->SetSegmentsList(listSegment);
  780. listFeature.push_back(fea);
  781. if ((int)listFeature.size() == 0)
  782. {
  783. return FALSE;
  784. }
  785. if (!ChangeFeaturelist(listFeature, findedParts))
  786. {
  787. return FALSE;
  788. }
  789. for (auto f : findedParts)
  790. {
  791. a_listParticles.push_back(f);
  792. }
  793. return TRUE;
  794. }
  795. BOOL COTSImageProcess::GetSegmentList(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSSegmentsList& a_listSegments)
  796. {
  797. ASSERT(a_pPixel);
  798. long nImgSize = a_nWidth * a_nHeight;
  799. a_listSegments.clear();
  800. //1. get segment line by line
  801. long nLine, nm, nn;
  802. long nStart = 0, nLength = 0;
  803. for (nLine = 0; nLine < a_nHeight; nLine++)
  804. {
  805. for (nm = 0; nm < a_nWidth; nm += (nLength + 1))
  806. {
  807. nLength = 0;
  808. // get start
  809. if (*(a_pPixel + nLine * a_nWidth + nm) != 0)
  810. {
  811. nStart = nm;
  812. nLength++;
  813. //get length
  814. for (nn = nm + 1; nn < a_nWidth; nn++)
  815. {
  816. // check if segment is over, break
  817. if (nLength != 0)
  818. {
  819. if (*(a_pPixel + nLine * a_nWidth + nn) == 0)
  820. break;
  821. }
  822. if (*(a_pPixel + nLine * a_nWidth + nn) != 0)
  823. {
  824. nLength++;
  825. }
  826. }
  827. // generate segment
  828. COTSSegmentPtr pSegment = COTSSegmentPtr(new COTSSegment(nLine + top, nStart + left, nLength));
  829. a_listSegments.push_back(pSegment);
  830. }
  831. else
  832. {
  833. continue;
  834. }
  835. }
  836. }
  837. if ((int)a_listSegments.size() == 0)
  838. {
  839. //LogErrorTrace(__FILE__, __LINE__, _T("no particle is found."));
  840. return FALSE;
  841. }
  842. return TRUE;
  843. }
  844. BOOL COTSImageProcess::GetFeatureList(COTSSegmentsList& a_listSegments, COTSFeatureList& a_listFeatures)
  845. {
  846. COTSSegmentsList listSegmentNew;
  847. std::map<long, COTSSegmentsList > mapOneLineSegments;
  848. for each (auto s in a_listSegments)
  849. {
  850. mapOneLineSegments[s->GetHeight()].push_back(s);//sorting all the segments base on the line number.
  851. }
  852. std::map<long, COTSSegmentsList >::iterator lineItr = mapOneLineSegments.begin();//find the highest line
  853. while (lineItr != mapOneLineSegments.end())
  854. {
  855. for (auto s = lineItr->second.begin(); s < lineItr->second.end(); )//find one segment of this line.
  856. {
  857. COTSSegmentPtr bottomSeg = *s;
  858. listSegmentNew.clear();
  859. listSegmentNew.push_back(*s);
  860. s = lineItr->second.erase(s);
  861. std::map<long, COTSSegmentsList >::iterator tempItr = lineItr;
  862. tempItr++;
  863. for (; tempItr != mapOneLineSegments.end(); tempItr++)//find all other lines of segments
  864. {
  865. if (tempItr->first - bottomSeg->GetHeight() > 1)
  866. {
  867. break;
  868. }
  869. for (auto nextLineSegment = tempItr->second.begin(); nextLineSegment < tempItr->second.end();)//find next line's all segments
  870. {
  871. if (((*nextLineSegment)->GetStart() - (bottomSeg->GetStart() + bottomSeg->GetLength())) > 1)
  872. {
  873. break;
  874. }
  875. if (bottomSeg->UpDownConection(**nextLineSegment))
  876. {
  877. listSegmentNew.push_back(*nextLineSegment);
  878. bottomSeg = *nextLineSegment;
  879. nextLineSegment = tempItr->second.erase(nextLineSegment);
  880. break;
  881. }
  882. if (tempItr->second.size() > 0)
  883. {
  884. nextLineSegment++;
  885. }
  886. else
  887. {
  888. break;
  889. }
  890. }
  891. }
  892. COTSFeaturePtr pFeature = COTSFeaturePtr(new COTSFeature());
  893. pFeature->SetSegmentsList(listSegmentNew);
  894. //check if this new feature is connected with other found feature.
  895. COTSSegmentPtr topSeg = listSegmentNew[0];//find the toppest segment of this new feature.
  896. COTSSegmentPtr bottomSegment = listSegmentNew[listSegmentNew.size() - 1];//find the lowest segment of this new feature.
  897. bool haveMerged = false;
  898. for each (auto f in a_listFeatures)
  899. {
  900. for (auto seg : f->GetSegmentsList())
  901. {
  902. if (bottomSegment->UpDownConection(*seg) || topSeg->UpDownConection(*seg))
  903. {
  904. COTSSegmentsList segs = f->GetSegmentsList();
  905. for (auto s : listSegmentNew)
  906. {
  907. segs.push_back(s);
  908. }
  909. f->SetSegmentsList(segs);
  910. haveMerged = true;
  911. break;
  912. }
  913. }
  914. if (haveMerged)
  915. {
  916. break;
  917. }
  918. }
  919. if (!haveMerged)
  920. {
  921. a_listFeatures.push_back(pFeature);
  922. }
  923. if (lineItr->second.size() == 0)
  924. {
  925. break;
  926. }
  927. }
  928. lineItr++;
  929. }
  930. return true;
  931. }
  932. BOOL COTSImageProcess::ChangeFeaturelist(COTSFeatureList& a_listFeatures, COTSParticleList& a_listParticle)
  933. {
  934. for (auto pFeature : a_listFeatures)
  935. {
  936. COTSParticlePtr pParticle = COTSParticlePtr(new COTSParticle());
  937. pParticle->SetFeature(pFeature);
  938. a_listParticle.push_back(pParticle);
  939. }
  940. if ((int)a_listParticle.size() == 0)
  941. {
  942. return FALSE;
  943. }
  944. return TRUE;
  945. }
  946. BOOL COTSImageProcess::GetParticlesFromBinaryImage(CBSEImgPtr m_pBSEImg, CDoubleRange a_diameterRange, double a_pixelSize, COTSParticleList& listParticleOut)
  947. {
  948. int height, width;
  949. height = m_pBSEImg->GetHeight();
  950. width = m_pBSEImg->GetWidth();
  951. BYTE* pPixel = m_pBSEImg->GetImageDataPointer();
  952. Mat nobgMat = Mat(height, width, CV_8UC1, pPixel);
  953. Mat labels = Mat::zeros(nobgMat.size(), CV_32S);
  954. Mat stats, centroids;
  955. int number = connectedComponentsWithStats(nobgMat, labels, stats, centroids, 8, CV_32S);
  956. double rStart = a_diameterRange.GetStart()/2.0;
  957. double rEnd = a_diameterRange.GetEnd()/2.0;
  958. double areaStart = rStart* rStart * 3.14159;
  959. double areaEnd = rEnd* rEnd * 3.14159;
  960. //COTSParticleList listParticleOut;
  961. for (size_t i = 1; i < number; i++)
  962. {
  963. int center_x = centroids.at<double>(i, 0);
  964. int center_y = centroids.at<double>(i, 1);
  965. //矩形边框
  966. int x = stats.at<int>(i, CC_STAT_LEFT);
  967. int y = stats.at<int>(i, CC_STAT_TOP);
  968. int w = stats.at<int>(i, CC_STAT_WIDTH);
  969. int h = stats.at<int>(i, CC_STAT_HEIGHT);
  970. int area = stats.at<int>(i, CC_STAT_AREA);
  971. double actualArea = area * a_pixelSize * a_pixelSize;
  972. if (actualArea >= areaStart && actualArea < areaEnd)
  973. {
  974. Rect rectMax = Rect(x, y, w, h);
  975. Mat rectROI = labels(rectMax).clone();
  976. Mat imageROI = Mat::zeros(rectMax.size(), nobgMat.type());
  977. //exclude the point which intersect into this bounding box but is not in this group.
  978. int label = i;
  979. for (int row = 0; row < rectROI.rows; row++)
  980. {
  981. for (int col = 0; col < rectROI.cols; col++)
  982. {
  983. int v = rectROI.at<int>(row, col);
  984. if (v == label)
  985. {
  986. imageROI.at<uchar>(row, col) = 255;
  987. }
  988. }
  989. }
  990. COTSParticleList roiParts;
  991. if (!GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))
  992. {
  993. continue;
  994. }
  995. if (roiParts.size() > 0)
  996. {
  997. COTSParticlePtr roiPart = roiParts[0];
  998. roiPart->SetXRayPos(CPoint(center_x, center_y));
  999. CRect r = CRect(x, y, x + w, y + h);
  1000. roiPart->SetParticleRect(r);
  1001. roiPart->SetActualArea(actualArea);
  1002. roiPart->SetPixelArea(area);
  1003. listParticleOut.push_back(roiPart);
  1004. }
  1005. }
  1006. }
  1007. return TRUE;
  1008. }
  1009. void COTSImageProcess::findPeakAndValley(const vector<int>& v, vector<int>& peakPositions, vector<int>& valleyPositions)
  1010. {
  1011. vector<int> diff_v(v.size() - 1, 0);
  1012. // 计算V的一阶差分和符号函数trend
  1013. for (vector<int>::size_type i = 0; i != diff_v.size(); i++)
  1014. {
  1015. if (v[i + 1] - v[i] > 0)
  1016. diff_v[i] = 1;
  1017. else if (v[i + 1] - v[i] < 0)
  1018. diff_v[i] = -1;
  1019. else
  1020. diff_v[i] = 0;
  1021. }
  1022. // 对Trend作了一个遍历
  1023. for (int i = diff_v.size() - 1; i >= 0; i--)
  1024. {
  1025. if (diff_v[i] == 0 && i == diff_v.size() - 1)
  1026. {
  1027. diff_v[i] = 1;
  1028. }
  1029. else if (diff_v[i] == 0)
  1030. {
  1031. if (diff_v[i + 1] >= 0)
  1032. diff_v[i] = 1;
  1033. else
  1034. diff_v[i] = -1;
  1035. }
  1036. }
  1037. for (vector<int>::size_type i = 0; i != diff_v.size() - 1; i++)
  1038. {
  1039. if (diff_v[i + 1] - diff_v[i] == -2)
  1040. peakPositions.push_back(i + 1);
  1041. if (diff_v[i + 1] - diff_v[i] == 2)
  1042. valleyPositions.push_back(i + 1);
  1043. }
  1044. }
  1045. std::vector<CIntRange> COTSImageProcess::GetValidGreyLevelRanges(CBSEImgPtr pBSEImg)
  1046. {
  1047. WORD originChartData[MAXBYTE];
  1048. //1. get chart data
  1049. pBSEImg->SetChartData();
  1050. memcpy(originChartData, pBSEImg->GetBSEChart(), sizeof(WORD) * MAXBYTE);
  1051. originChartData[0] = 0;
  1052. std::vector<int> greyChart;
  1053. for (int i = 0; i < MAXBYTE; i++)
  1054. {
  1055. greyChart.push_back((int)originChartData[i]);
  1056. }
  1057. std::vector<int> peaks;
  1058. std::vector<int> valleys;
  1059. findPeakAndValley(greyChart, peaks, valleys);
  1060. if ((peaks.size() - valleys.size()) == 1)
  1061. {
  1062. valleys.push_back(254);
  1063. }
  1064. std::map<int, MyGreyPeak*> peakMap;// hold all the peaks in this spectrum which are sorted by there area.
  1065. MyGreyPeak* lastRng = NULL;
  1066. MyGreyPeak* firstRng = NULL;
  1067. for (int i = 0; i < peaks.size(); i++)
  1068. {
  1069. MyGreyPeak* gr = new MyGreyPeak();
  1070. if (i == 0)
  1071. {
  1072. gr->start = 0;
  1073. }
  1074. else
  1075. {
  1076. gr->start = valleys[i - 1];
  1077. }
  1078. gr->end = valleys[i];
  1079. for (int j = gr->start; j < gr->end; j++)
  1080. {
  1081. gr->area += originChartData[j];
  1082. }
  1083. gr->peakPos = peaks[i];
  1084. gr->peakValue = originChartData[peaks[i]];
  1085. gr->valleyValue = valleys[i];
  1086. if (firstRng == NULL)
  1087. {
  1088. firstRng = gr;
  1089. lastRng = gr;
  1090. }
  1091. else
  1092. {
  1093. gr->preRng = lastRng;
  1094. lastRng->nextRng = gr;
  1095. }
  1096. lastRng = gr;
  1097. peakMap[gr->start] = gr;
  1098. }
  1099. int validGreyLevelNum = 0;//statistic the none zero grey level number
  1100. long partArea = 0;
  1101. for (int i = 0; i < 255; i++)
  1102. {
  1103. if (originChartData[i] != 0)
  1104. {
  1105. validGreyLevelNum += 1;
  1106. partArea += originChartData[i];
  1107. }
  1108. }
  1109. auto curRange = firstRng;
  1110. int maxPeakValue = curRange->peakValue;
  1111. while (curRange != NULL)
  1112. {
  1113. if (curRange->peakValue > maxPeakValue)
  1114. {
  1115. maxPeakValue = curRange->peakValue;
  1116. }
  1117. curRange = curRange->nextRng;
  1118. }
  1119. curRange = firstRng;
  1120. while (curRange != NULL)
  1121. {
  1122. curRange->maxPeakvalue = maxPeakValue;
  1123. curRange->allNoneZeroGreyLevelNum = validGreyLevelNum;
  1124. curRange = curRange->nextRng;
  1125. }
  1126. MyGreyPeak* firstRng1=NULL;
  1127. MyGreyPeak::MergeGreyPeaks(firstRng,firstRng1);
  1128. std::vector<CIntRange> ranges;
  1129. auto curRange1 = firstRng1;
  1130. while (curRange1 != NULL)
  1131. {
  1132. CIntRange pRange;
  1133. pRange.SetStart(curRange1->start);
  1134. pRange.SetEnd(curRange1->end);
  1135. ranges.push_back(pRange);
  1136. curRange1 = curRange1->nextRng;
  1137. }
  1138. return ranges;
  1139. }
  1140. BOOL COTSImageProcess::FindSeedsByGrayScale(CBSEImgPtr fieldImg, double a_PixelSize, std::vector<CPoint>& OutSeeds)
  1141. {
  1142. ASSERT(fieldImg);
  1143. ASSERT(m_imageProcessParam);
  1144. int nWidthImg = fieldImg->GetWidth();
  1145. int nHeightImg = fieldImg->GetHeight();
  1146. long nImgSize = nWidthImg * nHeightImg;
  1147. std::vector<CIntRange> validPeaks = GetValidGreyLevelRanges(fieldImg);
  1148. CRect r = CRect(0, 0, nWidthImg, nHeightImg);
  1149. CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));
  1150. for (int i = 0; i < validPeaks.size(); i++)
  1151. {
  1152. CIntRange pRange = validPeaks[i];
  1153. if (pRange.GetStart() == 0)//prevent the 0 grey pixels being recognized as particle.
  1154. {
  1155. pRange.SetStart(3);
  1156. }
  1157. long nNumParticle = 0;
  1158. GetSpecialGrayRangeImage(fieldImg, pRange, imgNoBGBinary, nNumParticle);
  1159. if (nNumParticle == 0)
  1160. {
  1161. continue;
  1162. }
  1163. else
  1164. {
  1165. // get the area image
  1166. Mat matImg = GetMatDataFromBseImg(imgNoBGBinary);
  1167. Mat labels = Mat::zeros(matImg.size(), CV_32S);
  1168. Mat stats, centroids;
  1169. int number = connectedComponentsWithStats(matImg, labels, stats, centroids, 8, CV_32S);
  1170. auto incsize = m_imageProcessParam->GetIncArea();
  1171. double rStart = incsize.GetStart() / 2.0;
  1172. double rEnd = incsize.GetEnd() / 2.0;
  1173. double pixelarea = a_PixelSize * a_PixelSize;
  1174. double areaStart = rStart* rStart * 3.14159*pixelarea;
  1175. double areaEnd = rEnd* rEnd * 3.14159*pixelarea;
  1176. /*double areaStart = 0;
  1177. double areaEnd = 1000;*/
  1178. for (size_t i = 1; i < number; i++)
  1179. {
  1180. int center_x = centroids.at<double>(i, 0);
  1181. int center_y = centroids.at<double>(i, 1);
  1182. int area = stats.at<int>(i, CC_STAT_AREA);
  1183. double actualArea = area * a_PixelSize * a_PixelSize;
  1184. if (actualArea >= areaStart && actualArea < areaEnd)
  1185. {
  1186. CPoint seed = CPoint(center_x, center_y);
  1187. OutSeeds.push_back(seed);
  1188. }
  1189. }
  1190. }
  1191. }
  1192. return true;
  1193. }
  1194. BOOL COTSImageProcess::CalcuParticleImagePropertes(COTSParticlePtr a_pOTSPart, double a_PixelSize)
  1195. {
  1196. //--------- convert this particle data to image data,construct an image only with this particle.------
  1197. const int nExpand_Size = 3;
  1198. const int nWhiteColor = 0;
  1199. const int nThickness = 1;
  1200. // lineType Type of the line
  1201. const int nLineType = 8;
  1202. // get rectangle of the particle
  1203. CRect rect = a_pOTSPart->GetParticleRect();
  1204. 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.
  1205. {
  1206. double w = 0, h = 0;
  1207. w = (double)rect.Width()*a_PixelSize;
  1208. h = (double)rect.Height()*a_PixelSize;
  1209. a_pOTSPart->SetDMax(MAX(w, h));
  1210. a_pOTSPart->SetDMin(MIN(w, h));
  1211. a_pOTSPart->SetDMean((w + h) / 2);
  1212. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  1213. a_pOTSPart->SetDElong(MAX(w, h));
  1214. a_pOTSPart->SetPerimeter((w+h)*2);
  1215. a_pOTSPart->SetDPerp(MIN(w, h));
  1216. a_pOTSPart->SetDInscr(MIN(w, h));
  1217. a_pOTSPart->SetMinWidth(w);
  1218. a_pOTSPart->SetMinHeight(h);
  1219. return true;
  1220. }
  1221. // calculate the particle image data size, expand 3 pixel at the edge
  1222. Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size , rect.Width() + nExpand_Size , CV_8U);
  1223. // get the segment list
  1224. COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();
  1225. for (auto pSegment : listSegment)
  1226. {
  1227. int nStart = pSegment->GetStart() - rect.left + nExpand_Size;
  1228. int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;
  1229. int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;
  1230. line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);
  1231. }
  1232. //--------abstract the contour of the particle.
  1233. vector<vector<Point>>contours;
  1234. findContours(particleImage, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
  1235. 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.
  1236. {
  1237. double w = 0, h = 0;
  1238. w = (double)rect.Width()*a_PixelSize;
  1239. h = (double)rect.Height()*a_PixelSize;
  1240. a_pOTSPart->SetDMax(MAX(w, h));
  1241. a_pOTSPart->SetDMin(MIN(w, h));
  1242. a_pOTSPart->SetDMean((w + h) / 2);
  1243. a_pOTSPart->SetFeretDiameter((w + h) / 2);
  1244. a_pOTSPart->SetDElong(MAX(w, h));
  1245. a_pOTSPart->SetPerimeter((w + h) * 2);
  1246. a_pOTSPart->SetDPerp(MIN(w, h));
  1247. a_pOTSPart->SetDInscr(MIN(w, h));
  1248. a_pOTSPart->SetMinWidth(w);
  1249. a_pOTSPart->SetMinHeight(h);
  1250. return true;
  1251. }
  1252. int imaxcontour = 0, imax = 0;
  1253. for (unsigned int i = 0; i < contours.size(); i++) {
  1254. int itmp = contourArea(contours[i]);
  1255. if (imaxcontour < itmp) {
  1256. imax = i;
  1257. imaxcontour = itmp;
  1258. }
  1259. }
  1260. vector<Point > listEdge = contours[imax];
  1261. vector<vector<Point>>Outcontours;
  1262. Outcontours.push_back(listEdge);
  1263. //---------calculate the minimium rectangle
  1264. auto rRect = cv::minAreaRect(listEdge);
  1265. Point2f p[4];
  1266. rRect.points(p);
  1267. int D_MIN =getDistance(p[0], p[1]);
  1268. int D_MinRecLen = 0;//minareaRect's length(the longger side).
  1269. for (int j = 0; j <= 2; j++)
  1270. {
  1271. //line(cvContourImg, p[j], p[(j + 1) % 4], Scalar(100, 100, 0), 2);
  1272. int d = getDistance(p[j], p[j + 1]);
  1273. if (d < D_MIN)
  1274. {
  1275. D_MIN = d;
  1276. }
  1277. if (d > D_MinRecLen)
  1278. {
  1279. D_MinRecLen = d;
  1280. }
  1281. }
  1282. a_pOTSPart->SetDMin(D_MIN*a_PixelSize);
  1283. a_pOTSPart->SetMinWidth(rRect.size.width);
  1284. a_pOTSPart->SetMinHeight(rRect.size.height);
  1285. //----------calculate the perimeter
  1286. double d = arcLength(listEdge, true);
  1287. a_pOTSPart->SetPerimeter(d*a_PixelSize);
  1288. //-----------calculate the Max Diameter. Find the min enclosing circle first ,then find the two farthest circle connected point.
  1289. Point2f center; float radius;
  1290. minEnclosingCircle(listEdge, center, radius);
  1291. //circle(cvContourImg, center, radius, Scalar(100), 2);
  1292. std::vector <Point> outContour = listEdge;
  1293. std::vector <Point> rst;
  1294. for (unsigned int k = 0; k < outContour.size(); k++)
  1295. {
  1296. Point p = outContour[k];
  1297. double d = sqrt(pow((p.x - center.x), 2) + pow((p.y - center.y), 2));
  1298. if (fabs(d - radius) < 0.01)
  1299. {
  1300. rst.push_back(p);
  1301. }
  1302. }
  1303. double D_MAX = 0;
  1304. Point lineDmax[2];
  1305. for (unsigned int m = 0; m < rst.size(); m++)
  1306. {
  1307. Point p = rst[m];
  1308. for (unsigned int n = m + 1; n < rst.size(); n++)
  1309. {
  1310. Point p1 = rst[n];
  1311. double d = sqrt(powf((p.x - p1.x), 2) + powf((p.y - p1.y), 2));
  1312. if (d > D_MAX)
  1313. {
  1314. D_MAX = d;
  1315. lineDmax[0] = p;
  1316. lineDmax[1] = p1;
  1317. }
  1318. }
  1319. }
  1320. a_pOTSPart->SetDMax(D_MAX*a_PixelSize);
  1321. //--------calculate the D_PERP property using the D_MAX's two endpoints.
  1322. std::vector<Point> curve1;
  1323. std::vector<Point> curve2;
  1324. for (unsigned int i = 0; i < outContour.size(); i++)
  1325. {
  1326. Point pt = outContour[i];
  1327. bool start = false;
  1328. int clockwise = Side(lineDmax[0], lineDmax[1], pt);// devide these points into two group ,separate into the two sides.
  1329. if (clockwise > 0)
  1330. {
  1331. curve1.push_back(pt);
  1332. }
  1333. else
  1334. {
  1335. curve2.push_back(pt);
  1336. }
  1337. }
  1338. double d_perp1 = 0, d_perp2 = 0;
  1339. for (unsigned int i = 0; i < curve1.size(); i++)
  1340. {
  1341. double d = getDist_P2L(curve1[i], lineDmax[0], lineDmax[1]);
  1342. if (d > d_perp1)
  1343. {
  1344. d_perp1 = d;
  1345. }
  1346. }
  1347. for (unsigned int i = 0; i < curve2.size(); i++)
  1348. {
  1349. double d = getDist_P2L(curve2[i], lineDmax[0], lineDmax[1]);
  1350. if (d > d_perp2)
  1351. {
  1352. d_perp2 = d;
  1353. }
  1354. }
  1355. a_pOTSPart->SetDPerp((d_perp1 + d_perp2)*a_PixelSize);
  1356. //----------find the diameter of max inscribed circle
  1357. int r;
  1358. Point inscribeCirclecenter;
  1359. FindInnerCircleInContour(outContour, inscribeCirclecenter, r);
  1360. //--------------------------------------------------------calculate the xraypos !
  1361. CRect rec = a_pOTSPart->GetParticleRect();
  1362. a_pOTSPart->SetXRayPos(CPoint(inscribeCirclecenter.x - nExpand_Size + rec.left - 1, inscribeCirclecenter.y - nExpand_Size + rec.top - 1));
  1363. a_pOTSPart->SetDInscr(r * 2 * a_PixelSize);
  1364. //---------------calculate the image other caracater: length/width realArea/minRectangeArea etc. we can use these propertes to do forward process.
  1365. double minRectArea = D_MIN * D_MinRecLen*a_PixelSize*a_PixelSize;//最小外接矩形面积
  1366. double fillRatio = a_pOTSPart->GetActualArea() / minRectArea;//实际面积与最小外接矩形面积比,that's the fill rate.
  1367. double lengthWidthRatio;
  1368. lengthWidthRatio = (double)D_MinRecLen / D_MIN;//长宽比
  1369. //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.
  1370. bool isStripShape = false;
  1371. double curveLength = 0;
  1372. double D_MEAN=0;
  1373. Moments mu;
  1374. mu = moments(listEdge, false);
  1375. int nx = mu.m10 / mu.m00;
  1376. int ny = mu.m01 / mu.m00;
  1377. //circle(cvcopyImg, Point(nx, ny), 1, (255), 1);
  1378. Point ptCenter = Point((int)nx, (int)ny);
  1379. if (pointPolygonTest(listEdge, ptCenter, false) != 1)// the center point doesn't contain in the contour, we think it as curve shape.
  1380. {
  1381. isStripShape = true;
  1382. }
  1383. /*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.
  1384. {
  1385. isStripShape = true;
  1386. }*/
  1387. 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.
  1388. {
  1389. isStripShape = true;
  1390. }
  1391. if (isStripShape)
  1392. {
  1393. 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.
  1394. if (curveLength < D_MAX)
  1395. {
  1396. curveLength = D_MAX;
  1397. }
  1398. if (curveLength < MIN_DOUBLE_VALUE || a_pOTSPart->GetActualArea()<MIN_DOUBLE_VALUE)
  1399. {
  1400. D_MEAN = 0;
  1401. }
  1402. else
  1403. {
  1404. D_MEAN = a_pOTSPart->GetActualArea() / curveLength;
  1405. }
  1406. a_pOTSPart->SetDMean(D_MEAN*a_PixelSize);
  1407. a_pOTSPart->SetFeretDiameter(D_MEAN*a_PixelSize);
  1408. a_pOTSPart->SetDElong (curveLength*a_PixelSize);
  1409. }
  1410. else//it's a ball shape particle
  1411. {
  1412. curveLength = D_MAX;
  1413. double ftd = 0, maxD = 0, minD = 0, dratio = 0;
  1414. GetParticleAverageChord(outContour, a_PixelSize, ftd);
  1415. a_pOTSPart->SetDMean(ftd);
  1416. a_pOTSPart->SetFeretDiameter(ftd);
  1417. a_pOTSPart->SetDElong(curveLength*a_PixelSize);
  1418. }
  1419. if (a_pOTSPart->GetAspectRatio() > 2)
  1420. {
  1421. double angle;
  1422. if (rRect.size.width > rRect.size.height) // w > h
  1423. {
  1424. angle = abs(rRect.angle);
  1425. }
  1426. else
  1427. {
  1428. angle = 90.0 + abs(rRect.angle);
  1429. }
  1430. a_pOTSPart->SetOrientation(angle);
  1431. }
  1432. else
  1433. {
  1434. a_pOTSPart->SetOrientation(0);
  1435. }
  1436. return true;
  1437. }
  1438. void COTSImageProcess::ImshowImage(CBSEImgPtr img)
  1439. {
  1440. BYTE* data = img->GetImageDataPointer();
  1441. //Mat cvImg;
  1442. cv::Size s;
  1443. s.width = img->GetImageSize().cx;
  1444. s.height = img->GetImageSize().cy;
  1445. Mat cvImg=Mat::zeros(s, CV_8U);
  1446. cvImg.data = data;
  1447. cv::imshow("dd", cvImg);
  1448. cv::waitKey();
  1449. }
  1450. void COTSImageProcess::ImshowChartData(CBSEImgPtr img)
  1451. {
  1452. img->SetChartData();
  1453. WORD* data = img->GetBSEChart();
  1454. //Mat cvImg;
  1455. cv::Size s;
  1456. s.width = 255;
  1457. s.height = 100;
  1458. Mat cvImg = Mat::zeros(s, CV_8U);
  1459. //cvImg.data = data;
  1460. WORD nBSEChart[MAXBYTE];
  1461. //1. get chart data
  1462. linearSmooth5(data, nBSEChart, MAXBYTE);
  1463. for (int i=1;i<255;i++)
  1464. {
  1465. line(cvImg, Point(i, 100-nBSEChart[i]), Point(i+1, 100-nBSEChart[i+1]), Scalar(nBlackColor), 1, 8);
  1466. }
  1467. cv::imshow("chart", cvImg);
  1468. cv::waitKey();
  1469. }
  1470. BOOL COTSImageProcess::MergeBigBoundaryParticles(COTSFieldDataList allFields,double pixelSize,int scanFieldSize, CSize ResolutionSize, COTSParticleList& mergedParts)
  1471. {
  1472. class BorderPart
  1473. {
  1474. typedef std::shared_ptr<BorderPart> CBorderPartPtr;
  1475. BorderPart(COTSParticlePtr p)
  1476. {
  1477. myPart = p;
  1478. headerParticle = NULL;
  1479. }
  1480. public:
  1481. COTSParticlePtr myPart;
  1482. 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.
  1483. static std::vector<CBorderPartPtr> ConvertPartToBorderPart(COTSParticleList parts)
  1484. {
  1485. static std::map<COTSParticle*, CBorderPartPtr> allborderPart;
  1486. std::vector<CBorderPartPtr> borderParts;
  1487. for (auto p : parts)
  1488. {
  1489. if (allborderPart.find(p.get()) == allborderPart.end())
  1490. {
  1491. auto borderp = CBorderPartPtr(new BorderPart(p));
  1492. borderParts.push_back(borderp);
  1493. allborderPart[p.get()] = borderp;
  1494. }
  1495. else
  1496. {
  1497. borderParts.push_back(allborderPart[p.get()]);
  1498. }
  1499. }
  1500. return borderParts;
  1501. }
  1502. };
  1503. auto FldMgr = new CFieldMgr(scanFieldSize, ResolutionSize);
  1504. std::map<COTSParticle*, COTSParticleList> mapMergeParticles;//hold up all the boundary connected particles. the pair's first is also the member of these particles.
  1505. std::map<COTSParticle*, COTSSegmentsList> mapMergedSegments;//hold up all the segment's corresponding clone in the connected particles.
  1506. for (auto centerfld : allFields)
  1507. {
  1508. // find neighbor field on the left.
  1509. auto leftFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::LEFT);
  1510. if (leftFld != nullptr)
  1511. {
  1512. auto lParts = centerfld->GetLeftBorderedBigParticles();
  1513. auto rParts = leftFld->GetRightBorderedBigParticles();
  1514. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  1515. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  1516. for (auto leftp : leftParts)
  1517. {
  1518. for (auto rightp : rightParts)
  1519. {
  1520. if (leftp->myPart->IsConnected(rightp->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::LEFT))
  1521. {
  1522. if (leftp->headerParticle != NULL)
  1523. {
  1524. if (rightp->headerParticle == NULL)
  1525. {
  1526. rightp->headerParticle = leftp->headerParticle;
  1527. mapMergeParticles[leftp->headerParticle].push_back(rightp->myPart);
  1528. }
  1529. }
  1530. else
  1531. {
  1532. if (rightp->headerParticle != NULL)
  1533. {
  1534. leftp->headerParticle = rightp->myPart.get();
  1535. mapMergeParticles[rightp->myPart.get()].push_back(leftp->myPart);
  1536. }
  1537. else
  1538. {
  1539. leftp->headerParticle = leftp->myPart.get();
  1540. rightp->headerParticle = leftp->myPart.get();
  1541. mapMergeParticles[leftp->myPart.get()].push_back(rightp->myPart);
  1542. }
  1543. }
  1544. }
  1545. }
  1546. }
  1547. }
  1548. //find neighbor field on the upward
  1549. auto upFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::UP);
  1550. if (upFld != nullptr)
  1551. {
  1552. auto topBorderParts = centerfld->GetTopBorderedBigParticles();
  1553. auto bottomBorderParts = upFld->GetBottomBorderedBigParticles();
  1554. auto upParts = BorderPart::ConvertPartToBorderPart(topBorderParts);
  1555. auto downParts = BorderPart::ConvertPartToBorderPart(bottomBorderParts);
  1556. for (auto upprt : upParts)
  1557. {
  1558. for (auto downprt : downParts)
  1559. {
  1560. if (upprt->myPart->IsConnected(downprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::UP))
  1561. {
  1562. if (upprt->headerParticle != NULL)
  1563. {
  1564. if (downprt->headerParticle == NULL)
  1565. {
  1566. downprt->headerParticle = upprt->headerParticle;
  1567. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1568. }
  1569. }
  1570. else
  1571. {
  1572. if (downprt->headerParticle != NULL)
  1573. {
  1574. upprt->headerParticle = downprt->headerParticle;
  1575. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1576. }
  1577. else
  1578. {
  1579. upprt->headerParticle = upprt->myPart.get();
  1580. downprt->headerParticle = upprt->myPart.get();
  1581. mapMergeParticles[upprt->myPart.get()].push_back(downprt->myPart);
  1582. }
  1583. }
  1584. }
  1585. }
  1586. }
  1587. }
  1588. //find neighbor field on the downward.
  1589. auto downFld = FldMgr->FindNeighborField(allFields, centerfld,SORTING_DIRECTION::DOWN);
  1590. if (downFld != nullptr)
  1591. {
  1592. auto bottomParts = centerfld->GetBottomBorderedBigParticles();
  1593. auto topParts = downFld->GetTopBorderedBigParticles();
  1594. auto downParts = BorderPart::ConvertPartToBorderPart(bottomParts);
  1595. auto upParts= BorderPart::ConvertPartToBorderPart(topParts);
  1596. for (auto downprt : downParts)
  1597. {
  1598. for (auto upprt : upParts)
  1599. {
  1600. if (downprt->myPart->IsConnected(upprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::DOWN))
  1601. {
  1602. if (downprt->headerParticle != NULL)
  1603. {
  1604. if (upprt->headerParticle == NULL)
  1605. {
  1606. upprt->headerParticle = downprt->headerParticle;
  1607. mapMergeParticles[downprt->headerParticle].push_back(upprt->myPart);
  1608. }
  1609. }
  1610. else
  1611. {
  1612. if (upprt->headerParticle != NULL)
  1613. {
  1614. downprt->headerParticle = upprt->headerParticle;
  1615. mapMergeParticles[upprt->headerParticle].push_back(downprt->myPart);
  1616. }
  1617. else
  1618. {
  1619. downprt->headerParticle = downprt->myPart.get();
  1620. upprt->headerParticle = downprt->myPart.get();
  1621. mapMergeParticles[downprt->myPart.get()].push_back(upprt->myPart);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. }
  1627. }
  1628. //find neighbor field on the right.
  1629. auto rightFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::RIGHT);
  1630. if (rightFld != nullptr)
  1631. {
  1632. auto rParts = centerfld->GetRightBorderedBigParticles();
  1633. auto lParts = rightFld->GetLeftBorderedBigParticles();
  1634. auto rightParts = BorderPart::ConvertPartToBorderPart(rParts);
  1635. auto leftParts = BorderPart::ConvertPartToBorderPart(lParts);
  1636. for (auto rightprt : rightParts)
  1637. {
  1638. for (auto leftprt : leftParts)
  1639. {
  1640. if (rightprt->myPart->IsConnected(leftprt->myPart.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::RIGHT))
  1641. {
  1642. if (rightprt->headerParticle != NULL)
  1643. {
  1644. if (leftprt->headerParticle == NULL)
  1645. {
  1646. leftprt->headerParticle = rightprt->headerParticle;
  1647. mapMergeParticles[rightprt->headerParticle].push_back(leftprt->myPart);
  1648. }
  1649. }
  1650. else
  1651. {
  1652. if (leftprt->headerParticle != NULL)
  1653. {
  1654. rightprt->headerParticle = leftprt->headerParticle;
  1655. mapMergeParticles[leftprt->headerParticle].push_back(rightprt->myPart);
  1656. }
  1657. else
  1658. {
  1659. rightprt->headerParticle = rightprt->myPart.get();
  1660. leftprt->headerParticle = rightprt->myPart.get();
  1661. mapMergeParticles[rightprt->myPart.get()].push_back(leftprt->myPart);
  1662. }
  1663. }
  1664. }
  1665. }
  1666. }
  1667. }
  1668. }
  1669. /*for (auto particle : mapMergeParticles)
  1670. {
  1671. }*/
  1672. static int partTagId;
  1673. for (auto pair : mapMergeParticles)
  1674. {
  1675. struct EleAreaPercentage
  1676. {
  1677. EleAreaPercentage(double p, CElementChemistryPtr e)
  1678. {
  1679. areaPercentage = p;
  1680. eleData = e;
  1681. }
  1682. double areaPercentage;
  1683. CElementChemistryPtr eleData;
  1684. };
  1685. auto newPart = COTSParticlePtr(new COTSParticle());
  1686. COTSSegmentsList newSegs;
  1687. auto p = pair.first;
  1688. newPart->SetSEMPos(p->GetSEMPos());
  1689. //firstly,we sum up all the merged particles's area and get the represent string.
  1690. std::string partsStr = std::to_string(p->GetFieldId()) + ":" + std::to_string(p->GetAnalysisId());
  1691. double allPartArea = p->GetActualArea();//Get the first particle's area.
  1692. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1693. {
  1694. partsStr += "," + std::to_string(other->GetFieldId()) + ":" + std::to_string(other->GetAnalysisId());//Get the subparticles string such as "1:1,2:1" etc.
  1695. allPartArea += other->GetActualArea();//Get other particle's area
  1696. }
  1697. // calculate all the new segment's position.
  1698. std::vector <COTSParticle*> allSubParts;
  1699. allSubParts.push_back(p);
  1700. for (auto other : pair.second)// Get the total area of all these particles for the use of ele calcu.
  1701. {
  1702. allSubParts.push_back(other.get());
  1703. }
  1704. for (auto subp : allSubParts)
  1705. {
  1706. int fid = subp->GetFieldId();
  1707. CPoint myFldPos;
  1708. for (auto f : allFields)//find this particle's filed.
  1709. {
  1710. if (f->GetId() == fid)
  1711. {
  1712. myFldPos = f->GetPosition();
  1713. }
  1714. }
  1715. int fldWidth = allFields[0]->Width;
  1716. int fldHeight = allFields[0]->Height;
  1717. CPoint fldLeftUpPos = CPoint(myFldPos.x + fldWidth / 2 , myFldPos.y + fldHeight / 2 );
  1718. for (auto s : subp->GetFeature()->GetSegmentsList())
  1719. {
  1720. COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());
  1721. newseg->SetStart(s->GetStart() + fldLeftUpPos.x);
  1722. 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.
  1723. newseg->SetLength(s->GetLength());
  1724. newSegs.push_back(newseg);
  1725. }
  1726. }
  1727. COTSFeaturePtr newFeature = COTSFeaturePtr(new COTSFeature());
  1728. newFeature->SetSegmentsList(newSegs);
  1729. newPart->SetFeature(newFeature);
  1730. newPart->CalCoverRectFromSegment();
  1731. //second, we get all the element data and their area percentage .
  1732. std::map<std::string, std::vector<EleAreaPercentage>> mapEleData;
  1733. CPosXrayPtr pXray1 = p->GetXrayInfo();
  1734. if (pXray1 != nullptr)
  1735. {
  1736. for (auto ele : pXray1->GetElementQuantifyData())
  1737. {
  1738. mapEleData[ele->GetName().GetBuffer()].push_back(EleAreaPercentage(p->GetActualArea() / allPartArea, ele));
  1739. }
  1740. }
  1741. for (auto other : pair.second)
  1742. {
  1743. auto otherXray = other->GetXrayInfo();
  1744. if (otherXray != nullptr)
  1745. {
  1746. for (auto eledata : otherXray->GetElementQuantifyData())
  1747. {
  1748. mapEleData[eledata->GetName().GetBuffer()].push_back(EleAreaPercentage(other->GetActualArea() / allPartArea, eledata));
  1749. }
  1750. }
  1751. }
  1752. // third,we calculate all the element's new percentage data and get a new element chemistry list.
  1753. CElementChemistriesList newCheList;
  1754. for (auto eledata : mapEleData)
  1755. {
  1756. CElementChemistryPtr newEleche = CElementChemistryPtr(new CElementChemistry());
  1757. newEleche->SetName(CString(eledata.first.c_str()));
  1758. double newPercentage = 0;
  1759. for (auto d : eledata.second)
  1760. {
  1761. newPercentage += d.areaPercentage * d.eleData->GetPercentage();
  1762. }
  1763. newEleche->SetPercentage(newPercentage);
  1764. newCheList.push_back(newEleche);
  1765. }
  1766. CPosXrayPtr xray(new CPosXray());
  1767. xray->SetElementQuantifyData(newCheList);
  1768. newPart->SetXrayInfo(xray);
  1769. newPart->SetConnectedParticlesSequentialString(partsStr);
  1770. newPart->SetActualArea(allPartArea);
  1771. partTagId++;
  1772. newPart->SetParticleId(partTagId);
  1773. newPart->SetAnalysisId(partTagId);
  1774. std::string name = p->GetClassifyName();
  1775. newPart->SetClassifyName(name);
  1776. newPart->SetColor(p->GetColor());
  1777. mergedParts.push_back(newPart);
  1778. }
  1779. return true;
  1780. }
  1781. }