OTSImageProcess.cpp 60 KB

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