OTSImageProcess.cpp 60 KB

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