OLDcellsegm_0909版本.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 OLDcellsegm
  117. {
  118. public const double m_PI = 3.1415926535897931;
  119. void mf_mergeinputpar(In4smoothim prm,In5segmsurf prmin)
  120. {
  121. prm.smoothim.method = prmin.smoothim_method;
  122. prm.filterridges = prmin.filterridges;
  123. prm.gaussian_stdev = prmin.gaussian_stdev;
  124. prm.LEVEL = (string)prmin.LEVEL.Clone();
  125. prm.classifycells.convexarea = prmin.classifycells_convexarea;
  126. prm.classifycells.convexperim = prmin.classifycells_convexperim;
  127. }
  128. void mf_cellsize(double minvol,double maxvol,In4smoothim prm,int ThreeDimNO)
  129. {
  130. if (0 == prm.h[0]*prm.h[1]*prm.h[2])
  131. {
  132. Console.WriteLine("There is zero voxel size");
  133. }
  134. double minr = Math.Pow((3*minvol)/(4*m_PI), 1/3);
  135. //maxr = ((3*maxvol)/(4*pi))^(1/3);
  136. //maxz = maxr/h(3);
  137. double minz = minr/prm.h[2];
  138. if (ThreeDimNO < minz)
  139. {
  140. //shrinink a sphere to a circle
  141. double r = Math.Pow((3*maxvol)/(4*m_PI), 1/3);
  142. maxvol = Math.Pow(ThreeDimNO, prm.just)*m_PI*r*r;
  143. r = Math.Pow((3*minvol)/(4*m_PI), 1/3);
  144. minvol = Math.Pow(ThreeDimNO, prm.just)*m_PI*r*r;
  145. }
  146. double voxelvol = prm.h[0]*prm.h[1]*prm.h[2];
  147. double minvolvox = Math.Round(minvol/voxelvol, MidpointRounding.AwayFromZero);
  148. double maxvolvox = Math.Round(maxvol/voxelvol, MidpointRounding.AwayFromZero);
  149. prm.minvol = minvol;
  150. prm.minvolvox = minvolvox;
  151. prm.maxvol = maxvol;
  152. prm.maxvolvox = maxvolvox;
  153. }
  154. public OUTsegmsurf mf_segmsurf(Mat GryImg, double minvol, double maxvol,
  155. string[] INnamehere, In5segmsurf IN5varhere,In6segmsurf IN6varhere)
  156. {
  157. OUTsegmsurf rtn = new OUTsegmsurf();
  158. string mfilename = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  159. Console.WriteLine("This is"+ mfilename + "for segmentation of cells");
  160. //image for segmentation
  161. Mat imsegm = GryImg.Clone();
  162. //cell volumes in cubic microns
  163. double minvolfull = 1000*minvol;
  164. double maxvolfull = 1000*maxvol;
  165. Mat imsegmini = imsegm.Clone();
  166. Mat minimacell = null;
  167. Mat minima = null;
  168. Mat imnucl = null;
  169. string prmfile = null;
  170. /*
  171. //for visualilzation
  172. int vis = 0;
  173. int visfinal = 0;
  174. */
  175. In4smoothim prm = new In4smoothim();
  176. prm.mergefragments = new PMergefragments();
  177. prm.smoothim = new PSmoothim();
  178. prm.classifycells = new PClassifycells();
  179. /*Standard parameters*/
  180. //voxel size
  181. prm.h = new double[3]{0.5,0.5,1.5};
  182. //adjust for not fully circular shape of 3D cells
  183. prm.just = 0.9;
  184. //filter ridges
  185. prm.filterridges = 0;
  186. //GPU, requires
  187. prm.gpu = 0;
  188. //correct illumination
  189. prm.illum = 0;
  190. prm.illumdiameter = 25;
  191. /*Minima parameters*/
  192. //level
  193. prm.getminima_level = 0.30;
  194. /*
  195. //method
  196. prm.getminima_method = "automated";
  197. */
  198. /*Smoothing parameters*/
  199. //directional coherence enhancing diffusion
  200. prm.smoothim.method = "dirced";
  201. //2D or 3D smoothing
  202. prm.smoothim.dim = 2;
  203. //number of iterations of smoothing in CED
  204. prm.smoothim.ced_maxniter = 100;
  205. //dimension image
  206. int[] dim = new int[3] { imsegm.Rows, imsegm.Cols, 1 };
  207. /*Classification parameters*/
  208. prm.classifycells.method = "threshold";
  209. /*Watershed parameters*/
  210. //To test intensity of wat lines; merging
  211. prm.merge = 0;
  212. //methods for merging
  213. prm.mergefragments.optlog = 2;
  214. prm.mergefragments.optint = 2;
  215. /* The signicance of watershed lines, stronger if larger, done on ridgeim!!
  216. if the raw image, then use much smaller, around 1
  217. set to 1.05-1.10
  218. prm.watthint = 1.06;*/
  219. prm.mergefragments.intint = 1.3;
  220. /* The conexity measure for the merging, we should not allow a very much
  221. smaller convexity after merging
  222. thconv = 1 if no change in convexity
  223. thconv > 1 if increase in convexity
  224. thconv < 1 if decrease in convexity */
  225. prm.mergefragments.conv = 1.0;
  226. if(maxvolfull < minvolfull)
  227. {
  228. Console.WriteLine(mfilename + ": The upper cell volume is lower than the lower, check the input");
  229. }
  230. /* 无用matlab代码
  231. % read from parameter file?
  232. for i = 4 : 2 : nargin
  233. namehere = varargin{4};
  234. varhere = varargin{5};
  235. switch(namehere)
  236. case('prmfile')
  237. prmfile = varhere;
  238. otherwise
  239. % nothing
  240. end;
  241. end;
  242. %
  243. % Load the parameter file if one is given
  244. %
  245. if ~isempty(prmfile)
  246. isfolder = ~isempty(strfind(prmfile,'/'));
  247. [a b c] = fileparts(prmfile);
  248. if isfolder
  249. A = pwd;
  250. cd(a);
  251. end;
  252. msg = sprintf('Reading from parameter file %s',prmfile);
  253. disp(msg);
  254. cmd = [b c];
  255. prmin = eval(cmd);
  256. if isfolder
  257. cd(A);
  258. end;
  259. % merge the structs by overriding the existing values
  260. prm = mergestruct(prm,prmin);
  261. end;
  262. */
  263. /*The command line has the highest priority, merge the variables here*/
  264. In5segmsurf prmin = null;
  265. for (int i = 0;i < INnamehere.GetLength(0);i++ )
  266. {
  267. //this variable
  268. string namehere = INnamehere[i];
  269. switch(namehere)
  270. {
  271. case "minima":
  272. minima = IN6varhere.minima;
  273. break;
  274. case "prm":
  275. prmin = IN5varhere.Clone();
  276. mf_mergeinputpar(prm,prmin);
  277. break;
  278. case "minimacell":
  279. minimacell = IN6varhere.minimacell;
  280. break;
  281. case "imnucleus":
  282. imnucl = IN6varhere.imnucl;
  283. break;
  284. default:
  285. Console.WriteLine("Wrong option " + namehere);
  286. break;
  287. }
  288. }
  289. prm.dim = new int[2] { imsegm.Rows, imsegm.Cols};
  290. /* 无用matlab代码
  291. % if you give in a nucleus image you want to use it!
  292. if ~isempty(imnucl)
  293. prm.getminima.method = 'nucleus';
  294. prm.classifycells.method = 'minimacell';
  295. end;
  296. % test for credibility!
  297. if isequal(prm.getminima.method,'manual')
  298. if isempty(minima) && isempty(minimacell)
  299. error('You must specify either minima eller minimacell')
  300. end;
  301. end;
  302. if isequal(prm.getminima.method,'nucleus')
  303. if isempty(imnucl)
  304. error('You must specify a nucleus image');
  305. end;
  306. end;
  307. */
  308. /*Computed settings*/
  309. //get the ADJUSTED 3D cell size, in case its not a full 3D volume.
  310. //NB: This is not always linearly scalable, try to avoid using reduced 3D.
  311. mf_cellsize(minvolfull,maxvolfull,prm,dim[2]);
  312. //give the voxel sizes in thousand, since all programs are tuned for this
  313. //prm.classifycells.minvolfull = prm.classifycells.minvolfull;
  314. //prm.classifycells.maxvolfull = prm.classifycells.maxvolfull;
  315. prm.getminima_minvolfull = minvolfull/1000;
  316. prm.getminima_maxvolfull = maxvolfull/1000;
  317. prm.watminvolfull = minvolfull/1000;
  318. prm.watmaxvolfull = maxvolfull/1000;
  319. prm.minvolfull = minvolfull;
  320. prm.maxvolfull = maxvolfull;
  321. prm.classifycells.minvolfull = minvolfull/1000;
  322. prm.classifycells.maxvolfull = maxvolfull/1000;
  323. Console.WriteLine("Using settings:");
  324. /* 无用matlab代码
  325. printstructscreen(prm);
  326. */
  327. //pixel size
  328. prm.getminima_h = (double[])prm.h.Clone();
  329. prm.classifycells.h = (double[])prm.h.Clone();
  330. prm.smoothim.h = (double[])prm.h.Clone();
  331. //gpu for smoothing
  332. prm.smoothim.gpu = prm.gpu;
  333. /*Cell segmentation start*/
  334. //Correcting for uneven illumination
  335. //Smoothing
  336. PSmoothim prminsmt = prm.smoothim.Clone();
  337. //kkkkk imsegm = cellsegm.smoothim(imsegm,prm.smoothim.method,'prm',prm);
  338. //Ridge enhancement
  339. if (1 == prm.filterridges)
  340. {
  341. Console.WriteLine("Ridge enhancement");
  342. //kkkkk imsegm = cellsegm.ridgeenhhessian(imsegm,prm.h);
  343. }
  344. else
  345. {
  346. Console.WriteLine("No ridge enhancement");
  347. }
  348. //Finding minima
  349. OUTgetminima gmout = getminima(imsegm, minimacell, prmin);
  350. //kkkkk minimacell = gmout.minimacell;
  351. minima = gmout.minima;
  352. //3D watershed segmentation
  353. Console.WriteLine("3D watershed segmentation");
  354. //Iimpose = imimposemin(imsegm,minima);
  355. //wat = watershed(Iimpose);
  356. //vector<vector<Point>> contour;
  357. Mat watermark = new Mat(imsegm.Size(), MatType.CV_32S);
  358. Point[][] contour;
  359. HierarchyIndex[] hier;
  360. Cv2.FindContours(minima,out contour,out hier,RetrievalModes.CComp,ContourApproximationModes.ApproxSimple,null);
  361. for(int i = 0;i < hier.Length;i++)
  362. {
  363. Cv2.DrawContours(watermark,contour,i,Scalar.All(i+1),1,LineTypes.Link8,hier);
  364. }
  365. //Mat Temp = new Mat(imsegm.Size(), MatType.CV_8UC3);
  366. //imsegm.CopyTo(Temp);
  367. Cv2.Watershed(IN5varhere.OrgImg, watermark);//mmmmm
  368. //Mat afterWatershed = new Mat();//kkkkk
  369. //Cv2.ConvertScaleAbs(watermark, afterWatershed);//kkkkk
  370. //Cv2.ImWrite("D:\\afterWatershed.jpg", afterWatershed);//kkkkk
  371. //Cv2.ImShow("watermark", afterWatershed);//kkkkk
  372. //Cv2.WaitKey(0);//kkkkk
  373. PClassifycells prmclf = prm.classifycells.Clone();
  374. OUTclassifycells cfout;
  375. if(null != minimacell)//mmmmm
  376. {
  377. cfout = classifycells(watermark,imsegmini,prmclf,minimacell);
  378. }
  379. else
  380. {
  381. cfout = classifycells(watermark,imsegmini,prmclf);
  382. }
  383. Mat cellbw = cfout.cellbw;
  384. //kkkkk info.classifycells = cfout.classifycells;
  385. //kkkkk info.prm = prm;
  386. //9. 绘制轮廓 drawContours
  387. //Mat maskers = Mat::zeros(imgDist8U.size(), CV_32SC1);
  388. //for (size_t i=0; i<contour.size(); i++){
  389. //drawContours(maskers, contour, static_cast<int>(i), Scalar::all(static_cast<int>(i) + 1)); }
  390. //imshow("maskers", maskers);
  391. //ttttt Cv2.FindContours(watermark, out contour, out hier, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, null);
  392. rtn.wat = new Mat(watermark.Size(), MatType.CV_8UC3);
  393. //ttttt Cv2.DrawContours(rtn.wat, contour, -1, Scalar.Red);
  394. int Rows = watermark.Rows;
  395. int Cols = watermark.Cols;
  396. int[] point = new int[2];
  397. Vec3b redcol = new Vec3b(0,0,255);
  398. for (point[0] = 0; point[0] < Rows; point[0]++)
  399. {
  400. for (point[1] = 0; point[1] < Cols; point[1]++)
  401. {
  402. if (0 >= watermark.At<int>(point[0], point[1]))
  403. {
  404. rtn.wat.Set<Vec3b>(point, redcol);
  405. }
  406. }
  407. }
  408. //Cv2.ImShow("contour", rtn.wat);//kkkkk
  409. //Cv2.WaitKey(0);//kkkkk
  410. return rtn;
  411. }
  412. OUTclassifycells classifycells(Mat watermark,Mat imsegmini,PClassifycells prmclf, Mat minimacell = null)
  413. {
  414. OUTclassifycells rtn = new OUTclassifycells();
  415. return rtn;
  416. }
  417. OUTgetminima getminima(Mat imsegm, Mat minimacell, In5segmsurf prmin)
  418. {
  419. OUTgetminima rtn = new OUTgetminima();
  420. rtn.minima = null;
  421. rtn.minimacell = null;
  422. if(null == minimacell)
  423. {
  424. rtn.minima = automated(imsegm,prmin);
  425. }
  426. return rtn;
  427. }
  428. Mat automated(Mat imsegm,In5segmsurf prmin)
  429. {
  430. Mat mat_mean = new Mat(), mat_stddev = new Mat();
  431. Cv2.MeanStdDev(imsegm, mat_mean, mat_stddev);
  432. double m, s;
  433. m = mat_mean.At<double>(0, 0);
  434. s = mat_stddev.At<double>(0, 0);
  435. double d = 1.0;//mmmmm
  436. double th = m + d * s;
  437. Mat minima = new Mat(), minimacell = new Mat();
  438. Cv2.Threshold(imsegm, minimacell, th, 255, ThresholdTypes.Binary);
  439. int diam;//mmmmm
  440. Mat kernel;
  441. diam = 11;
  442. kernel = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(diam, diam), new Point(-1, -1));
  443. Cv2.Dilate(minimacell, minimacell, kernel);
  444. diam = 5;
  445. kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(diam, diam), new Point(-1, -1));
  446. Cv2.Erode(minimacell, minimacell, kernel);
  447. //Cv2.MorphologyEx(minimacell, minimacell, MorphTypes.Open, kernel);
  448. //Cv2.ImShow("bianjie", minimacell);
  449. //Cv2.WaitKey(0);
  450. Cv2.BitwiseNot(minimacell, minima);
  451. Size bianjieSize = minima.Size();
  452. Mat Temp=Mat.Zeros(bianjieSize.Height+2,bianjieSize.Width+2,minimacell.Type());//延展图像
  453. minima.CopyTo(Temp.SubMat(new Range(1, bianjieSize.Height + 1), new Range(1, bianjieSize.Width + 1)));
  454. Cv2.FloodFill(Temp, new Point(0, 0), new Scalar(255));
  455. Mat cutImg = new Mat();
  456. Temp.SubMat(new Range(1, bianjieSize.Height + 1), new Range(1, bianjieSize.Width + 1)).CopyTo(cutImg);
  457. Cv2.BitwiseNot(cutImg, cutImg);
  458. minima = minima | cutImg;
  459. diam = 10;
  460. kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(diam, diam), new Point(-1, -1));
  461. Cv2.MorphologyEx(minima, minima, MorphTypes.Open, kernel);
  462. //Cv2.ImShow("neibu", minima);//kkkkk
  463. //Cv2.WaitKey(0);//kkkkk
  464. return minima;
  465. }
  466. }
  467. }