OLDcellsegm_0916版本.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using OpenCvSharp;
  7. namespace ConsoleApplication1
  8. {
  9. /////
  10. /////
  11. class OUTsegmsurf
  12. {
  13. public Mat cellbw;
  14. public Mat wat;
  15. public Mat imsegm;
  16. public Mat minima;
  17. public Mat minimacell;
  18. //kkkkk public NEW_TYPE_SegInf info;
  19. }
  20. class In5segmsurf
  21. {
  22. public string smoothim_method;
  23. public int filterridges;
  24. public double gaussian_stdev;
  25. public string LEVEL;
  26. public double classifycells_convexarea;
  27. public double classifycells_convexperim;
  28. public Mat OrgImg;
  29. public In5segmsurf Clone()
  30. {
  31. return this.MemberwiseClone() as In5segmsurf;
  32. }
  33. }
  34. class In6segmsurf
  35. {
  36. public string prmfile;//Path to parameter file
  37. public Mat minima;//All markers, for instance from manual drawings
  38. public Mat minimacell;//; for cells, for instance from manual drawings
  39. public Mat imnucl;//Nucleus image for defining markers
  40. }
  41. class PMergefragments//区域合并
  42. {
  43. public int optlog;
  44. public int optint;
  45. public double intint;
  46. public double conv;
  47. public PMergefragments Clone()
  48. {
  49. return this.MemberwiseClone() as PMergefragments;
  50. }
  51. }
  52. class PSmoothim//平滑
  53. {
  54. public string method;
  55. public double[] h;
  56. public int gpu;
  57. public int dim;
  58. public int ced_maxniter;
  59. public PSmoothim Clone()
  60. {
  61. return this.MemberwiseClone() as PSmoothim;
  62. }
  63. }
  64. class PClassifycells//区域分类
  65. {
  66. public double convexarea;
  67. public double convexperim;
  68. public double[] h;
  69. public double minvolfull;
  70. public double maxvolfull;
  71. public string method;
  72. public PClassifycells Clone()
  73. {
  74. return this.MemberwiseClone() as PClassifycells;
  75. }
  76. }
  77. class In4smoothim
  78. {
  79. public int filterridges;
  80. public string LEVEL;
  81. public double gaussian_stdev;
  82. public double[] getminima_h;
  83. public double getminima_minvolfull;
  84. public double getminima_maxvolfull;
  85. public double getminima_level;
  86. //public string getminima_method;
  87. public PMergefragments mergefragments;
  88. public PSmoothim smoothim;
  89. public PClassifycells classifycells;
  90. public int[] dim;
  91. public double minvol;
  92. public double minvolvox;
  93. public double maxvol;
  94. public double maxvolvox;
  95. public double watminvolfull;
  96. public double watmaxvolfull;
  97. public double minvolfull;
  98. public double maxvolfull;
  99. public double[] h;
  100. public double just;
  101. public int gpu;
  102. public int illum;
  103. public double illumdiameter;
  104. public int merge;
  105. }
  106. class OUTgetminima
  107. {
  108. public Mat minimacell;
  109. public Mat minima;
  110. }
  111. class OUTclassifycells
  112. {
  113. public Mat cellbw;
  114. public PClassifycells classifycells;
  115. }
  116. class OUTmaxfilt3
  117. {
  118. public List<float>[,] maxim;
  119. public float[,] sumim;
  120. public int numpoints;
  121. }
  122. class MyFilter
  123. {
  124. public double[] x;
  125. public double[] y;
  126. public double[] z;
  127. }
  128. class OLDcellsegm
  129. {
  130. public const double m_PI = 3.1415926535897931;
  131. void mf_mergeinputpar(In4smoothim prm,In5segmsurf prmin)
  132. {
  133. prm.smoothim.method = prmin.smoothim_method;
  134. prm.filterridges = prmin.filterridges;
  135. prm.gaussian_stdev = prmin.gaussian_stdev;
  136. prm.LEVEL = (string)prmin.LEVEL.Clone();
  137. prm.classifycells.convexarea = prmin.classifycells_convexarea;
  138. prm.classifycells.convexperim = prmin.classifycells_convexperim;
  139. }
  140. void mf_cellsize(double minvol,double maxvol,In4smoothim prm,int ThreeDimNO)
  141. {
  142. if (0 == prm.h[0]*prm.h[1]*prm.h[2])
  143. {
  144. Console.WriteLine("There is zero voxel size");
  145. }
  146. double minr = Math.Pow((3*minvol)/(4*m_PI), 1/3);
  147. //maxr = ((3*maxvol)/(4*pi))^(1/3);
  148. //maxz = maxr/h(3);
  149. double minz = minr/prm.h[2];
  150. if (ThreeDimNO < minz)
  151. {
  152. //shrinink a sphere to a circle
  153. double r = Math.Pow((3*maxvol)/(4*m_PI), 1/3);
  154. maxvol = Math.Pow(ThreeDimNO, prm.just)*m_PI*r*r;
  155. r = Math.Pow((3*minvol)/(4*m_PI), 1/3);
  156. minvol = Math.Pow(ThreeDimNO, prm.just)*m_PI*r*r;
  157. }
  158. double voxelvol = prm.h[0]*prm.h[1]*prm.h[2];
  159. double minvolvox = Math.Round(minvol/voxelvol, MidpointRounding.AwayFromZero);
  160. double maxvolvox = Math.Round(maxvol/voxelvol, MidpointRounding.AwayFromZero);
  161. prm.minvol = minvol;
  162. prm.minvolvox = minvolvox;
  163. prm.maxvol = maxvol;
  164. prm.maxvolvox = maxvolvox;
  165. }
  166. public OUTsegmsurf mf_segmsurf(Mat GryImg, double minvol, double maxvol,
  167. string[] INnamehere, In5segmsurf IN5varhere,In6segmsurf IN6varhere)
  168. {
  169. OUTsegmsurf rtn = new OUTsegmsurf();
  170. string mfilename = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  171. Console.WriteLine("This is"+ mfilename + "for segmentation of cells");
  172. //image for segmentation
  173. Mat imsegm = GryImg.Clone();
  174. //cell volumes in cubic microns
  175. double minvolfull = 1000*minvol;
  176. double maxvolfull = 1000*maxvol;
  177. Mat imsegmini = imsegm.Clone();
  178. Mat minimacell = null;
  179. Mat minima = null;
  180. Mat imnucl = null;
  181. string prmfile = null;
  182. /*
  183. //for visualilzation
  184. int vis = 0;
  185. int visfinal = 0;
  186. */
  187. In4smoothim prm = new In4smoothim();
  188. prm.mergefragments = new PMergefragments();
  189. prm.smoothim = new PSmoothim();
  190. prm.classifycells = new PClassifycells();
  191. /*Standard parameters*/
  192. //voxel size
  193. prm.h = new double[3]{0.5,0.5,1.5};
  194. //adjust for not fully circular shape of 3D cells
  195. prm.just = 0.9;
  196. //filter ridges
  197. prm.filterridges = 0;
  198. //GPU, requires
  199. prm.gpu = 0;
  200. //correct illumination
  201. prm.illum = 0;
  202. prm.illumdiameter = 25;
  203. /*Minima parameters*/
  204. //level
  205. prm.getminima_level = 0.30;
  206. /*
  207. //method
  208. prm.getminima_method = "automated";
  209. */
  210. /*Smoothing parameters*/
  211. //directional coherence enhancing diffusion
  212. prm.smoothim.method = "dirced";
  213. //2D or 3D smoothing
  214. prm.smoothim.dim = 2;
  215. //number of iterations of smoothing in CED
  216. prm.smoothim.ced_maxniter = 100;
  217. //dimension image
  218. int[] dim = new int[3] { imsegm.Rows, imsegm.Cols, 1 };
  219. /*Classification parameters*/
  220. prm.classifycells.method = "threshold";
  221. /*Watershed parameters*/
  222. //To test intensity of wat lines; merging
  223. prm.merge = 0;
  224. //methods for merging
  225. prm.mergefragments.optlog = 2;
  226. prm.mergefragments.optint = 2;
  227. /* The signicance of watershed lines, stronger if larger, done on ridgeim!!
  228. if the raw image, then use much smaller, around 1
  229. set to 1.05-1.10
  230. prm.watthint = 1.06;*/
  231. prm.mergefragments.intint = 1.3;
  232. /* The conexity measure for the merging, we should not allow a very much
  233. smaller convexity after merging
  234. thconv = 1 if no change in convexity
  235. thconv > 1 if increase in convexity
  236. thconv < 1 if decrease in convexity */
  237. prm.mergefragments.conv = 1.0;
  238. if(maxvolfull < minvolfull)
  239. {
  240. Console.WriteLine(mfilename + ": The upper cell volume is lower than the lower, check the input");
  241. }
  242. /* 无用matlab代码
  243. % read from parameter file?
  244. for i = 4 : 2 : nargin
  245. namehere = varargin{4};
  246. varhere = varargin{5};
  247. switch(namehere)
  248. case('prmfile')
  249. prmfile = varhere;
  250. otherwise
  251. % nothing
  252. end;
  253. end;
  254. %
  255. % Load the parameter file if one is given
  256. %
  257. if ~isempty(prmfile)
  258. isfolder = ~isempty(strfind(prmfile,'/'));
  259. [a b c] = fileparts(prmfile);
  260. if isfolder
  261. A = pwd;
  262. cd(a);
  263. end;
  264. msg = sprintf('Reading from parameter file %s',prmfile);
  265. disp(msg);
  266. cmd = [b c];
  267. prmin = eval(cmd);
  268. if isfolder
  269. cd(A);
  270. end;
  271. % merge the structs by overriding the existing values
  272. prm = mergestruct(prm,prmin);
  273. end;
  274. */
  275. /*The command line has the highest priority, merge the variables here*/
  276. In5segmsurf prmin = null;
  277. for (int i = 0;i < INnamehere.GetLength(0);i++ )
  278. {
  279. //this variable
  280. string namehere = INnamehere[i];
  281. switch(namehere)
  282. {
  283. case "minima":
  284. minima = IN6varhere.minima;
  285. break;
  286. case "prm":
  287. prmin = IN5varhere.Clone();
  288. mf_mergeinputpar(prm,prmin);
  289. break;
  290. case "minimacell":
  291. minimacell = IN6varhere.minimacell;
  292. break;
  293. case "imnucleus":
  294. imnucl = IN6varhere.imnucl;
  295. break;
  296. default:
  297. Console.WriteLine("Wrong option " + namehere);
  298. break;
  299. }
  300. }
  301. prm.dim = new int[2] { imsegm.Rows, imsegm.Cols};
  302. /* 无用matlab代码
  303. % if you give in a nucleus image you want to use it!
  304. if ~isempty(imnucl)
  305. prm.getminima.method = 'nucleus';
  306. prm.classifycells.method = 'minimacell';
  307. end;
  308. % test for credibility!
  309. if isequal(prm.getminima.method,'manual')
  310. if isempty(minima) && isempty(minimacell)
  311. error('You must specify either minima eller minimacell')
  312. end;
  313. end;
  314. if isequal(prm.getminima.method,'nucleus')
  315. if isempty(imnucl)
  316. error('You must specify a nucleus image');
  317. end;
  318. end;
  319. */
  320. /*Computed settings*/
  321. //get the ADJUSTED 3D cell size, in case its not a full 3D volume.
  322. //NB: This is not always linearly scalable, try to avoid using reduced 3D.
  323. mf_cellsize(minvolfull,maxvolfull,prm,dim[2]);
  324. //give the voxel sizes in thousand, since all programs are tuned for this
  325. //prm.classifycells.minvolfull = prm.classifycells.minvolfull;
  326. //prm.classifycells.maxvolfull = prm.classifycells.maxvolfull;
  327. prm.getminima_minvolfull = minvolfull/1000;
  328. prm.getminima_maxvolfull = maxvolfull/1000;
  329. prm.watminvolfull = minvolfull/1000;
  330. prm.watmaxvolfull = maxvolfull/1000;
  331. prm.minvolfull = minvolfull;
  332. prm.maxvolfull = maxvolfull;
  333. prm.classifycells.minvolfull = minvolfull/1000;
  334. prm.classifycells.maxvolfull = maxvolfull/1000;
  335. Console.WriteLine("Using settings:");
  336. /* 无用matlab代码
  337. printstructscreen(prm);
  338. */
  339. //pixel size
  340. prm.getminima_h = (double[])prm.h.Clone();
  341. prm.classifycells.h = (double[])prm.h.Clone();
  342. prm.smoothim.h = (double[])prm.h.Clone();
  343. //gpu for smoothing
  344. prm.smoothim.gpu = prm.gpu;
  345. /*Cell segmentation start*/
  346. //Correcting for uneven illumination
  347. //Smoothing
  348. PSmoothim prminsmt = prm.smoothim.Clone();
  349. imsegm = smoothim(imsegm,prm.smoothim.method,"prm",prm);
  350. Cv2.ImShow("smoothim", imsegm);//kkkkk
  351. Cv2.WaitKey(0);//kkkkk
  352. //Ridge enhancement
  353. if (1 == prm.filterridges)
  354. {
  355. Console.WriteLine("Ridge enhancement");
  356. //kkkkk imsegm = cellsegm.ridgeenhhessian(imsegm,prm.h);
  357. }
  358. else
  359. {
  360. Console.WriteLine("No ridge enhancement");
  361. }
  362. //Finding minima
  363. OUTgetminima gmout = getminima(imsegm, minimacell, prmin);
  364. //kkkkk minimacell = gmout.minimacell;
  365. minima = gmout.minima;
  366. //3D watershed segmentation
  367. Console.WriteLine("3D watershed segmentation");
  368. //Iimpose = imimposemin(imsegm,minima);
  369. //wat = watershed(Iimpose);
  370. //vector<vector<Point>> contour;
  371. Mat watermark = new Mat(imsegm.Size(), MatType.CV_32S);
  372. Point[][] contour;
  373. HierarchyIndex[] hier;
  374. Cv2.FindContours(minima,out contour,out hier,RetrievalModes.CComp,ContourApproximationModes.ApproxSimple,null);
  375. for(int i = 0;i < hier.Length;i++)
  376. {
  377. Cv2.DrawContours(watermark,contour,i,Scalar.All(i+1),1,LineTypes.Link8,hier);
  378. }
  379. //Mat Temp = new Mat(imsegm.Size(), MatType.CV_8UC3);
  380. //imsegm.CopyTo(Temp);
  381. Cv2.Watershed(IN5varhere.OrgImg, watermark);//mmmmm
  382. //Mat afterWatershed = new Mat();//kkkkk
  383. //Cv2.ConvertScaleAbs(watermark, afterWatershed);//kkkkk
  384. //Cv2.ImWrite("D:\\afterWatershed.jpg", afterWatershed);//kkkkk
  385. //Cv2.ImShow("watermark", afterWatershed);//kkkkk
  386. //Cv2.WaitKey(0);//kkkkk
  387. PClassifycells prmclf = prm.classifycells.Clone();
  388. OUTclassifycells cfout;
  389. if(null != minimacell)//mmmmm
  390. {
  391. cfout = classifycells(watermark,imsegmini,prmclf,minimacell);
  392. }
  393. else
  394. {
  395. cfout = classifycells(watermark,imsegmini,prmclf);
  396. }
  397. Mat cellbw = cfout.cellbw;
  398. //kkkkk info.classifycells = cfout.classifycells;
  399. //kkkkk info.prm = prm;
  400. //9. 绘制轮廓 drawContours
  401. //Mat maskers = Mat::zeros(imgDist8U.size(), CV_32SC1);
  402. //for (size_t i=0; i<contour.size(); i++){
  403. //drawContours(maskers, contour, static_cast<int>(i), Scalar::all(static_cast<int>(i) + 1)); }
  404. //imshow("maskers", maskers);
  405. //ttttt Cv2.FindContours(watermark, out contour, out hier, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, null);
  406. rtn.wat = new Mat(watermark.Size(), MatType.CV_8UC3);
  407. //ttttt Cv2.DrawContours(rtn.wat, contour, -1, Scalar.Red);
  408. int Rows = watermark.Rows;
  409. int Cols = watermark.Cols;
  410. int[] point = new int[2];
  411. Vec3b redcol = new Vec3b(0,0,255);
  412. for (point[0] = 0; point[0] < Rows; point[0]++)
  413. {
  414. for (point[1] = 0; point[1] < Cols; point[1]++)
  415. {
  416. if (0 >= watermark.At<int>(point[0], point[1]))
  417. {
  418. rtn.wat.Set<Vec3b>(point, redcol);
  419. }
  420. }
  421. }
  422. //Cv2.ImShow("contour", rtn.wat);//kkkkk
  423. //Cv2.WaitKey(0);//kkkkk
  424. return rtn;
  425. }
  426. OUTclassifycells classifycells(Mat watermark,Mat imsegmini,PClassifycells prmclf, Mat minimacell = null)
  427. {
  428. OUTclassifycells rtn = new OUTclassifycells();
  429. return rtn;
  430. }
  431. OUTgetminima getminima(Mat imsegm, Mat minimacell, In5segmsurf prmin)
  432. {
  433. OUTgetminima rtn = new OUTgetminima();
  434. rtn.minima = null;
  435. rtn.minimacell = null;
  436. if(null == minimacell)
  437. {
  438. rtn.minima = automated(imsegm,prmin);
  439. }
  440. return rtn;
  441. }
  442. Mat automated(Mat imsegm,In5segmsurf prmin)
  443. {
  444. Mat mat_mean = new Mat(), mat_stddev = new Mat();
  445. double m, s, d;
  446. //Cv2.MeanStdDev(imsegm, mat_mean, mat_stddev);
  447. //m = mat_mean.At<double>(0, 0);
  448. //s = mat_stddev.At<double>(0, 0);
  449. //d = 0;//mmmmm
  450. double th;
  451. //th = Math.Min(Math.Max(m+d*s, m/2),1.5*m);
  452. Mat minima = new Mat(), minimacell = new Mat(imsegm.Size(), MatType.CV_8UC3);
  453. //Cv2.Threshold(imsegm, minimacell, th, 255, ThresholdTypes.Binary);
  454. //Cv2.Threshold(imsegm, minimacell, 0, 255, ThresholdTypes.Otsu);
  455. int iRad = 39;
  456. Mat matTempA = new Mat();
  457. Mat matTempB = new Mat();
  458. Cv2.MedianBlur(imsegm, matTempA,iRad);
  459. Cv2.AddWeighted(imsegm, 1, matTempA, -1, 0, matTempB);
  460. Cv2.MeanStdDev(matTempB, mat_mean, mat_stddev);
  461. m = mat_mean.At<double>(0, 0);
  462. s = mat_stddev.At<double>(0, 0);
  463. d = 0;//mmmmm
  464. th = m+d*s;
  465. Cv2.Threshold(matTempB, minimacell, th, 255, ThresholdTypes.Binary);
  466. //Cv2.Threshold(matTempB, minimacell, 0, 255, ThresholdTypes.Otsu);
  467. int diam;//mmmmm
  468. Mat kernel;
  469. diam = 9;
  470. kernel = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(diam, diam), new Point(-1, -1));
  471. Cv2.Dilate(minimacell, minimacell, kernel);
  472. diam = 3;
  473. kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(diam, diam), new Point(-1, -1));
  474. Cv2.Erode(minimacell, minimacell, kernel);
  475. Cv2.MorphologyEx(minimacell, minimacell, MorphTypes.Open, kernel);
  476. Cv2.ImShow("bianjie", minimacell);
  477. Cv2.WaitKey(0);
  478. Cv2.BitwiseNot(minimacell, minima);
  479. Size bianjieSize = minima.Size();
  480. Mat Temp=Mat.Zeros(bianjieSize.Height+2,bianjieSize.Width+2,minimacell.Type());//延展图像
  481. minima.CopyTo(Temp.SubMat(new Range(1, bianjieSize.Height + 1), new Range(1, bianjieSize.Width + 1)));
  482. Cv2.FloodFill(Temp, new Point(0, 0), new Scalar(255));
  483. Mat cutImg = new Mat();
  484. Temp.SubMat(new Range(1, bianjieSize.Height + 1), new Range(1, bianjieSize.Width + 1)).CopyTo(cutImg);
  485. Cv2.BitwiseNot(cutImg, cutImg);
  486. minima = minima | cutImg;
  487. diam = 9;
  488. kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(diam, diam), new Point(-1, -1));
  489. Cv2.MorphologyEx(minima, minima, MorphTypes.Open, kernel);
  490. Cv2.ImShow("neibu", minima);//kkkkk
  491. Cv2.WaitKey(0);//kkkkk
  492. return minima;
  493. }
  494. Mat smoothim(Mat im,string method,string prmflg,In4smoothim prm)
  495. {
  496. //diameter of filter
  497. int iPrmD = 13;
  498. Mat rst = new Mat();
  499. Cv2.ConvertScaleAbs(dircohenh(im,iPrmD,prm.h),rst);
  500. return rst;
  501. }
  502. Mat dircohenh(Mat im,int iPrmD,double[] adPrmH)
  503. {
  504. int[] dim = new int[3] { im.Rows,im.Cols,1 };
  505. if(3 == im.Dims)
  506. {
  507. dim[2] = im.Height;
  508. }
  509. //number of elements to remove before one takes the Olympic average. Set to
  510. //1-->3
  511. int numremele = 2;
  512. int stepxy = 30;
  513. int numdeghere = (180-stepxy)/stepxy + 1;
  514. int[] deghere = new int[numdeghere];
  515. deghere[0] = 0;
  516. for(int i=1;i < numdeghere;i++)
  517. {
  518. deghere[i] = deghere[i-1] + stepxy;
  519. }
  520. double[,] deg2D = new double[numdeghere,2];
  521. for(int i=1;i < numdeghere;i++)
  522. {
  523. deg2D[i,0] = (double)(deghere[i]);
  524. deg2D[i,1] = 90;
  525. }
  526. double[,] deg;
  527. deg = deg2D;
  528. if(1 != dim[2])
  529. {
  530. double[,] deg3D = new double[numdeghere + 1, 2];
  531. for (int i = 1; i < numdeghere; i++)
  532. {
  533. deg3D[i, 0] = deg2D[i, 0];
  534. deg3D[i, 1] = deg2D[i, 1];
  535. }
  536. deg3D[numdeghere, 0] = 0;
  537. deg3D[numdeghere, 1] = 0;
  538. deg = deg3D;
  539. }
  540. //the half filter size
  541. int p = iPrmD / 2;
  542. //make filter
  543. MyFilter[] c = makefilter(deg, p);
  544. //number of directions
  545. int numdir = c.Length;
  546. //inisization
  547. Mat filtim = new Mat(im.Rows,im.Cols,MatType.CV_32F,0.0);
  548. for (int i = 0;i < numdir;i++)
  549. {
  550. //coordinates of points in this direction after rotation of filter
  551. MyFilter chere = c[i];
  552. //filter image for max value
  553. OUTmaxfilt3 fltrst = maxfilt3(im, chere, numremele/*, dim*/);
  554. //structural filtering
  555. //filtim = max(filtim,(sumim - sum(maxim,4))/ (numpoints-numremele));
  556. int[] point = new int[2];
  557. for (point[0] = 0; point[0] < filtim.Rows; point[0]++)
  558. {
  559. for (point[1] = 0; point[1] < filtim.Cols; point[1]++)
  560. {
  561. float fTemp = filtim.At<float>(point[0], point[1]);
  562. fTemp = Math.Max(fTemp,
  563. (fltrst.sumim[point[0], point[1]] - (fltrst.maxim[point[0], point[1]]).Sum()) / (fltrst.numpoints - numremele)
  564. );
  565. filtim.Set<float>(point, fTemp);
  566. }
  567. }
  568. }
  569. return filtim;
  570. }
  571. OUTmaxfilt3 maxfilt3(Mat im, MyFilter chere, int numremele/*, int[] dim*/)
  572. {
  573. Mat imFt = new Mat();
  574. Mat imRs = new Mat();
  575. im.ConvertTo(imFt,MatType.CV_32F);
  576. int iProportion = 5;
  577. Cv2.Resize(imFt,imRs,new Size(imFt.Cols*iProportion,imFt.Rows*iProportion),0,0,InterpolationFlags.Cubic);
  578. int BigRows = imRs.Rows;
  579. int BigCols = imRs.Cols;
  580. /*
  581. double[,] x = new double[dim[0], dim[1]];
  582. double[,] y = new double[dim[0], dim[1]];
  583. for (int i = 0; i < dim[0]; i++)
  584. {
  585. for (int j = 0; j < dim[1]; j++)
  586. {
  587. x[i, j] = (double)i;
  588. y[i, j] = (double)j;
  589. }
  590. }
  591. */
  592. OUTmaxfilt3 rst = new OUTmaxfilt3();
  593. //rst.maxim = new Mat[numremele];
  594. rst.sumim = new float[imFt.Rows, imFt.Cols];
  595. rst.maxim = new List<float>[imFt.Rows, imFt.Cols];
  596. for (int i = 0; i < imFt.Rows; i++)
  597. {
  598. for (int j = 0; j < imFt.Cols; j++)
  599. {
  600. (rst.sumim)[i, j] = 0;
  601. List<float> lisTmp = new List<float>();
  602. for (int k = 0; k < numremele; k++ )
  603. {
  604. lisTmp.Add(0);
  605. }
  606. (rst.maxim)[i, j] = lisTmp;
  607. }
  608. }
  609. rst.numpoints = chere.x.Length;
  610. //Mat imhere = new Mat(imFt.Rows, imFt.Cols, MatType.CV_32F, 0.0);
  611. for (int i = 0; i < rst.numpoints; i++)
  612. {
  613. //the coordinate where we want to find the values
  614. //NB!!!!!!!!!
  615. //Must not do this for z direction, then it goes wrong.
  616. //Do NOOOOOT replacestr any Inf or NaN by image values, then the filter
  617. //does not work anymore!!!!!!
  618. //xhere(xhere < h(1)) = h(1);xhere(xhere > dim(1)*h(1)) = dim(1)*h(1);
  619. //yhere(yhere < h(1)) = h(1);yhere(yhere > dim(2)*h(1)) = dim(2)*h(2);
  620. //double[,] xhere = new double[dim[0], dim[1]];
  621. //double[,] yhere = new double[dim[0], dim[1]];
  622. double xhere;
  623. double yhere;
  624. int[] point = new int[2];
  625. for (point[0] = 0; point[0] < imFt.Rows; point[0]++)
  626. {
  627. for (point[1] = 0; point[1] < imFt.Cols; point[1]++)
  628. {
  629. //xhere[i, j] = Math.Min(Math.Max(x[i, j]+(chere.x)[t],1),dim[0]);
  630. //yhere[i, j] = Math.Min(Math.Max(y[i, j]+(chere.y)[t],1),dim[1]);
  631. xhere = (point[0] + (chere.x)[i]) * iProportion;
  632. yhere = (point[1] + (chere.y)[i]) * iProportion;
  633. int iX = Math.Min(Math.Max((int)(xhere+0.5), 0),BigRows - 1);
  634. int iY = Math.Min(Math.Max((int)(yhere+0.5), 0),BigCols - 1);
  635. float fTemp = imRs.At<float>(iX, iY);
  636. //imhere.Set<float>(point, fTemp);
  637. (rst.sumim)[point[0], point[1]] += fTemp;
  638. (rst.maxim)[point[0], point[1]].Add(fTemp);
  639. (rst.maxim)[point[0], point[1]].Sort();
  640. (rst.maxim)[point[0], point[1]].RemoveAt(0);
  641. (rst.maxim)[point[0], point[1]].Reverse();
  642. }
  643. }
  644. }
  645. return rst;
  646. }
  647. MyFilter[] makefilter(double[,] deg,int p)
  648. {
  649. int iNum = deg.GetLength(0);
  650. MyFilter[] c = new MyFilter[iNum];
  651. //r = linspace(-p,p,7);
  652. int iArrLength = 7;
  653. double[] r = new double[iArrLength];
  654. double dStep = p*2.0/(iArrLength-1.0);
  655. for(int i=0;i < 7;i++)
  656. {
  657. r[i]=-1.0*p+i*dStep;
  658. }
  659. /*
  660. for i = 1 : size(deg,1)
  661. % the degrees
  662. theta = deg(i,1);
  663. phi = deg(i,2);
  664. % the positions
  665. c(i).x = r*sind(phi)*cosd(theta);
  666. c(i).y = r*sind(phi)*sind(theta);
  667. c(i).z = r*cosd(phi);
  668. end;
  669. */
  670. for (int i = 0; i < iNum; i++)
  671. {
  672. double theta = deg[i,0];
  673. double phi = deg[i,1];
  674. c[i] = new MyFilter();
  675. c[i].x = new double[iArrLength];
  676. c[i].y = new double[iArrLength];
  677. c[i].z = new double[iArrLength];
  678. for(int j = 0;j < iArrLength;j++)
  679. {
  680. (c[i].x)[j] = r[j] * Math.Sin(phi) * Math.Cos(theta); ;
  681. (c[i].y)[j] = r[j] * Math.Sin(phi) * Math.Sin(theta); ;
  682. (c[i].z)[j] = r[j] * Math.Cos(phi);
  683. }
  684. }
  685. return c;
  686. }
  687. }
  688. }