Bsoft  2.1.0
Bernard's software package
Bimage_segment.cpp
Go to the documentation of this file.
1 
9 #include "rwimg.h"
10 #include "linked_list.h"
11 #include "utilities.h"
12 
13 // Declaration of global variables
14 extern int verbose; // Level of output to the screen
15 
19 struct GSedge {
20  long u, v; // GSedge ends in the 1D data array
21  float w; // GSedge weight: Neighbor value difference
22 } ;
23 
27 struct GSregion {
28  long p; // GSregion index
29  int r; // Number of region joins
30  int s; // Number of voxels in the region
31  float a; // Average value for the region
32 } ;
33 
34 
56 Bimage* Bimage::regions(double threshold, int sign)
57 {
58  // The extreme considered as a region depends on the threshold and sign
59  if ( sign < 0 ) sign = -1;
60  else if ( sign > 0 ) sign = 1;
61  else {
62  sign = 1;
63  if ( threshold < avg ) sign = -1;
64  }
65 
66  long i, count(0), rsize;
67  double abs_threshold(sign*threshold);
68 
69  if ( verbose & VERB_PROCESS ) {
70  cout << "Finding regions:" << endl;
71  cout << "Threshold: " << threshold << " (" << sign << ")" << endl;
72  }
73 
74  Bimage* pmask = new Bimage(Integer, TSimple, size(), n);
75  pmask->file_name(file_name());
76  pmask->sampling(sampling(0));
77  for ( i=0; i<n; i++ ) pmask->image[i] = image[i];
78 
79  //Using a mask, all the regions are grouped and numbered.
80  for ( i=0; i<datasize; i++ ) {
81  if ( (*pmask)[i] == 0 ) {
82  if ( sign*(*this)[i] > abs_threshold ) {
83  count++;
84  rsize = region_assign(pmask, i, count, threshold, sign);
85  if ( verbose & VERB_DEBUG )
86  cout << "DEBUG Bimage::regions: i=" << i << " count=" <<
87  count << " rsize=" << rsize << endl;
88  }
89  }
90  }
91 
92  pmask->statistics();
93 
94  if ( verbose & VERB_PROCESS )
95  cout << "Regions: " << count << endl << endl;
96 
97  return pmask;
98 }
99 
100 
119 long Bimage::region_assign(Bimage* pmask, long idx,
120  long region_number, double threshold, int sign)
121 {
122  if ( verbose & VERB_DEBUG )
123  cout << "DEBUG Bimage::region_assign: Starting with region " <<
124  region_number << " idx=" << idx << endl;
125 
126  if ( sign < 0 ) sign = -1;
127  else if ( sign > 0 ) sign = 1;
128  else {
129  sign = 1;
130  if ( threshold < avg ) sign = -1;
131  }
132 
133  double abs_threshold(sign*threshold);
134  long i, j, nn, kx, ky, kz;
135  Vector3<long> lo, hi;
136 
137  // Set up two lists:
138  // First list is for voxels to loop through for checking
139  // Second list is for new voxels to be checked in a subsequent iteration
140  long number, new_number, count(1);
141  long list_size = 2*(x + y)*z;
142  if ( z > 1 ) list_size += 2*x*y;
143  int* list = new int[list_size];
144  int* new_list = new int[list_size];
145 
146  // Initialize the first item in the list
147  pmask->set(idx, region_number);
148  number = 1;
149  list[0] = idx;
150  nn = idx / (x*y*z);
151 
152  // Find neighbors in shells around already found neighbors
153  while ( number > 0 ) {
154  if ( verbose & VERB_DEBUG )
155  cout << "DEBUG Bimage::region_assign: region=" << region_number << " list size=" << number << endl;
156  new_number = 0;
157  for ( i=0; i<number; i++ ) {
158  lo = kernel_low(list[i]);
159  hi = kernel_high(list[i]);
160 
161  // Loop through the kernel and construct the new list
162  for ( kz=lo[2]; kz<=hi[2]; kz++ ) {
163  for ( ky=lo[1]; ky<=hi[1]; ky++ ) {
164  for ( kx=lo[0]; kx<=hi[0]; kx++ ) {
165  j = index(kx, ky, kz, nn);
166  if ( ((*pmask)[j] == 0) && (sign*(*this)[j] > abs_threshold) ) {
167  pmask->set(j, region_number);
168  count++;
169  new_list[new_number] = j;
170  new_number++;
171  if ( new_number >= list_size ) {
172  cerr << "Error: The list size exceeded its limit ("
173  << list_size << ")" << endl;
174  }
175  }
176  }
177  }
178  }
179  }
180  number = new_number;
181  for ( i=0; i<number; i++ ) list[i] = new_list[i];
182  }
183 
184  delete[] list;
185  delete[] new_list;
186 
187  if ( verbose & VERB_DEBUG )
188  cout << "DEBUG Bimage::region_assign: Ending with region " << region_number << endl;
189 
190  return count;
191 }
192 
200 int Bimage::region_threshold_series(double threshold_first,
201  double threshold_last, double threshold_step)
202 {
203  int sign(1);
204  double threshold, a(0);
205  Bimage* pmask;
206 
207  if ( threshold_step == 0 ) {
208  if ( threshold_last == threshold_first )
209  threshold_step = 1;
210  else
211  threshold_step = threshold_last - threshold_first;
212  } else {
213  if ( threshold_step > 0 && threshold_first > threshold_last )
214  threshold_step = -threshold_step;
215  if ( threshold_step < 0 && threshold_first < threshold_last )
216  threshold_step = -threshold_step;
217  }
218 
219  if ( threshold_step < 0 ) sign = -1;
220  threshold_last += threshold_step/2;
221 
222  cout << "Finding the number of regions at each threshold:" << endl;
223  cout << "Thresh\tRegions\tAvgSize" << endl;
224  for ( threshold = threshold_first; sign*threshold <= sign*threshold_last;
225  threshold+=threshold_step ) {
226  pmask = regions(threshold, 0);
227  a = pmask->levelmask_average_region_size();
228  cout << threshold << tab << pmask->maximum() << tab << a << endl;
229  delete pmask;
230  }
231  cout << endl;
232 
233  return 0;
234 }
235 
256 long Bimage::region_flood(Bimage* pmask, double threshold_hi,
257  double threshold_lo, double threshold_step, int fill_borders)
258 {
259  if ( !pmask ) {
260  error_show("No region mask in Bimage::region_flood", __FILE__, __LINE__);
261  return 0;
262  }
263 
264  long i;
265  double threshold, dt;
266 
267  if ( threshold_hi < threshold_lo )
268  swap(threshold_hi, threshold_lo);
269  if ( threshold_step == 0 )
270  threshold_step = (threshold_lo - threshold_hi)/100;
271  else if ( (threshold_lo - threshold_hi)/threshold_step < 0 )
272  threshold_step *= -1;
273 
274  if ( verbose & VERB_LABEL ) {
275  cout << "Segmenting an image by flooding from a threshold or region set:" << endl;
276  if ( pmask )
277  cout << "Region set: " << pmask->file_name() << endl;
278  cout << "Starting threshold: " << threshold_hi << endl;
279  cout << "Finishing threshold: " << threshold_lo << endl;
280  cout << "Threshold step: " << threshold_step << endl;
281  }
282 
283  if ( !check_if_same_size(pmask) ) {
284  error_show("Error in Bimage::region_flood", __FILE__, __LINE__);
285  cerr << "The region mask must have the same dimensions as the image!" << endl;
286  return 0;
287  }
288 
289  if ( verbose & VERB_LABEL )
290  cout << "Starting regions: " << pmask->maximum() << endl;
291 
292  Bimage* pt = pmask->copy();
293 
294  // Progressively decrease threshold and find new adjacent voxels belonging to
295  // each region - disputes over voxel assignment are settled later
296  for ( threshold=threshold_hi; threshold>threshold_lo; threshold+=threshold_step ) {
297  dt = threshold_hi - threshold_lo;
298  if ( dt > 0 ) dt = 100*(threshold_hi - threshold)/dt;
299  else dt = 100;
300  if ( verbose )
301  cout << "Processing threshold: " << threshold << " (" << dt << " %) \r" << flush;
302 
303 #ifdef HAVE_GCD
304  dispatch_apply(datasize, dispatch_get_global_queue(0, 0), ^(size_t it){
305  if ( (*this)[it] > threshold )
306  pt->set(it, pmask->check_neighbors(it));
307  else
308  pt->set(it, 0);
309  });
310 #else
311 #pragma omp parallel for
312  for ( long it=0; it<datasize; it++ ) {
313  if ( (*this)[it] > threshold )
314  pt->set(it, pmask->check_neighbors(it));
315  else
316  pt->set(it, 0);
317  }
318 #endif
319  for ( i=0; i<datasize; i++ ) pmask->set(i, (*pt)[i]);
320  }
321 
322  if ( verbose )
323  cout << endl;
324 
325  long nborder(0), dnb(1), maxtries(20);
326 
327  for ( i=0; i<datasize; i++ ) if ( (*pmask)[i] < 0 ) nborder++;
328  if ( verbose & VERB_LABEL )
329  cout << "Border voxels: " << nborder << endl;
330 
331  // Assign the borders between regions to one of the regions
332  if ( fill_borders ) {
333  if ( verbose & VERB_PROCESS )
334  cout << "Assigning borders:" << endl;
335 
336  while ( maxtries-- > 0 && nborder > 0 && dnb > 0 ) {
337  if ( verbose )
338  cout << "Processing border voxels: " << nborder << " \r" << flush;
339  dnb = nborder;
340  nborder = 0;
341 
342 #ifdef HAVE_GCD
343  dispatch_apply(datasize, dispatch_get_global_queue(0, 0), ^(size_t it){
344  if ( (*pmask)[it] < 0 ) {
345  size_t j = kernel_max_neigbor(it, 1);
346  pmask->set(it, (*pmask)[j]);
347  if ( (*pmask)[it] < 0 ) {
348  j = kernel_max_neigbor(it, 2);
349  pmask->set(it, (*pmask)[j]);
350  }
351  }
352  });
353 #else
354 #pragma omp parallel for
355  for ( long it=0; it<datasize; it++ ) {
356  if ( (*pmask)[it] < 0 ) {
357  long j = kernel_max_neigbor(it, 1);
358  pmask->set(it, (*pmask)[j]);
359  if ( (*pmask)[it] < 0 ) {
360  j = kernel_max_neigbor(it, 2);
361  pmask->set(it, (*pmask)[j]);
362  }
363  }
364  }
365 #endif
366  for ( long it=0; it<datasize; it++ ) if ( (*pmask)[it] < 0 ) nborder++;
367 
368  dnb -= nborder;
369  }
370 
371  if ( verbose )
372  cout << "Processing border voxels: " << nborder << endl;
373  if ( verbose && nborder > 0 )
374  cerr << "Warning: " << nborder << " border voxels were not assigned!" << endl;
375  }
376 
377  long nseg = (long)(pmask->maximum() + 1.9);
378  int* vol;
379 
380  if ( verbose & VERB_FULL ) {
381  vol = new int[nseg];
382  for ( i=0; i<nseg; i++ ) vol[i] = 0;
383  for ( i=0; i<datasize; i++ )
384  if ( (*pmask)[i] > -1 ) vol[(long)(*pmask)[i]]++;
385  cout << "Region\tVoxels\tVolume\tMass" << endl;
386  for ( i=1; i<nseg; i++ )
387  cout << i << tab << vol[i] << tab << vol[i]*sampling(0).volume()
388  << tab << vol[i]*sampling(0).volume()*RHO << endl;
389  delete[] vol;
390  }
391 
392  if ( verbose )
393  cout << endl;
394 
395  if ( verbose & VERB_DEBUG )
396  cout << "DEBUG Bimage::region_flood: Finished with segmentation" << endl;
397 
398  return nseg;
399 }
400 
407 {
408  if ( (*this)[idx] != 0 ) return (long)(*this)[idx];
409 
410  long i, xx, yy, zz, nn(0), nv(0);
411 
412  //calculate the bounds on the kernel
413  Vector3<long> lo = kernel_low(idx);
414  Vector3<long> hi = kernel_high(idx);
415 
416  // Loop through the kernel and check neighbors
417  for ( zz=lo[2]; zz<=hi[2]; zz++ ) {
418  for ( yy=lo[1]; yy<=hi[1]; yy++ ) {
419  for ( xx=lo[0]; xx<=hi[0]; xx++ ) {
420  i = index(0,xx,yy,zz,nn);
421  if ( i != idx ) {
422  if ( (*this)[i] > 0 ) {
423  if ( nv == 0 )
424  nv = (long)(*this)[i];
425  else if ( nv != (*this)[i] )
426  nv = -100; // Border voxel
427  }
428  }
429  }
430  }
431  }
432 
433  if ( verbose & VERB_DEBUG )
434  cout << "DEBUG Bimage::check_neighbors: Ending with region " << (int)(*this)[idx] << endl;
435 
436  return nv;
437 }
438 
457 Bimage* Bimage::region_peaks(long kernel_size, double threshold, int flood, int wrap)
458 {
459  if ( kernel_size < 3 ) kernel_size = 3;
460 
461  long i, nn, dn;
462  long hk(kernel_size/2), npeak(0);
463 
464  if ( verbose & VERB_LABEL ) {
465  cout << "Segmenting an image by flooding from peaks:" << endl;
466  cout << "Kernel size: " << 2*hk+1 << endl;
467  cout << "Threshold: " << threshold << endl;
468  if ( wrap ) cout << "With wrapping" << endl;
469  }
470 
471  Bimage* pmask = new Bimage(Integer, TSimple, size(), n);
472  for ( nn=0; nn<n; nn++ ) pmask->image[nn] = image[nn];
473 
474  int* pnt = new int[datasize];
475  for ( i=0; i<datasize; i++ ) pnt[i] = -1;
476 
477 #ifdef HAVE_GCD
478  dispatch_apply(datasize, dispatch_get_global_queue(0, 0), ^(size_t i){
479  if ( (*this)[i] >= threshold ) {
480  if ( wrap ) pnt[i] = kernel_max_wrap(i, hk);
481  else pnt[i] = kernel_max(i, hk);
482  }
483  });
484 #else
485 #pragma omp parallel for
486  for ( i=0; i<datasize; ++i ) {
487  if ( (*this)[i] >= threshold ) {
488  if ( wrap ) pnt[i] = kernel_max_wrap(i, hk);
489  else pnt[i] = kernel_max(i, hk);
490  }
491  }
492 #endif
493 
494  for ( i=npeak=0; i<datasize; i++ )
495  if ( pnt[i] == i ) pmask->set(i, ++npeak);
496 
497  if ( flood ) {
498  nn = 0;
499  dn = 1;
500  while ( dn ) {
501  dn = nn;
502  for ( i=0; i<datasize; i++ )
503  if ( (*this)[i] >= threshold && (*pmask)[i] < 1 )
504  pmask->set(i, (*pmask)[pnt[i]]);
505  for ( i=nn=0; i<datasize; i++ ) if ( (*pmask)[i] > 0 ) nn++;
506  dn = nn - dn;
507  }
508  }
509 
510  delete[] pnt;
511 
512  pmask->maximum(npeak);
513 
514  if ( verbose & VERB_LABEL )
515  cout << "Number of peaks: " << npeak << endl << endl;
516 
517  return pmask;
518 }
519 
537 long Bimage::blobs(double threshold, double min_size, double max_size,
538  double setvalue, int sign)
539 {
540  if ( min_size > max_size ) swap(min_size, max_size);
541 
542  if ( sign < 0 ) sign = -1;
543  else if ( sign > 0 ) sign = 1;
544  else {
545  sign = 1;
546  if ( threshold < avg ) sign = -1;
547  }
548 
549  if ( verbose & ( VERB_LABEL | VERB_PROCESS ) ) {
550  if ( sign > 0 )
551  cout << "Finding blobs above " << threshold << endl;
552  else
553  cout << "Finding blobs below " << threshold << endl;
554  }
555 
556  if ( verbose & VERB_PROCESS ) {
557  cout << "Size range to keep: " << min_size << " - " << max_size << endl;
558  cout << "Set value: " << setvalue << endl << endl;
559  }
560 
561  Bimage* pmask = regions(threshold, sign);
562  long count = (long) pmask->maximum();
563 
564  long i, f, nvox(0), nblobs(0);
565 
566  int* region_size = new int[count+1];
567 
568  for ( i=0; i<=count; i++ ) region_size[i] = 0;
569 
570  for ( i=0; i<datasize; i++ ) region_size[(long)(*pmask)[i]]++;
571 
572  if ( verbose & VERB_PROCESS ) {
573  cout << "Region\tSize";
574  for ( i=0; i<=count; i++ ) {
575  if ( i%5 == 0 ) cout << endl << i;
576  cout << tab << region_size[i];
577  }
578  cout << endl << endl;
579  }
580 
581  if ( ( min_size > 0 ) || ( max_size < datasize ) ) {
582  for ( i=1; i<=count; i++ )
583  if ( region_size[i] < min_size || region_size[i] > max_size ) nblobs++;
584 
585  for ( i=0; i<datasize; i++ ) {
586  f = (long)(*pmask)[i];
587  if ( f > 0 ) {
588  if ( ( region_size[f] < min_size ) || ( region_size[f] > max_size ) ) {
589  set(i, setvalue);
590  nvox++;
591  }
592  }
593  }
594  }
595 
596  if ( verbose & VERB_PROCESS ) {
597  cout << "Number of blobs deleted: " << nblobs << endl;
598  cout << "Number of voxels set: " << nvox << endl << endl;
599  }
600 
601  delete[] region_size;
602 
603 // write_img("pf.pif", pmask);
604 
605  delete pmask;
606 
607  statistics();
608 
609  return nvox;
610 }
611 
621 {
622  statistics();
623 
624  double threshold = avg + 3*std;
625  if ( threshold >= max ) threshold = (max - avg)*0.75 + avg;
626 
627  blobs(threshold, 100, 1e30, avg, 0);
628 
629  threshold = avg - 3*std;
630  if ( threshold <= min ) threshold = (min - avg)*0.75 + avg;
631 
632  blobs(threshold, 1000, 1e30, avg, 0);
633 
634  return 0;
635 }
636 
649 int Bimage::filter_extremes(int mod_flag)
650 {
651  double tmin, tmax;
652 
653  histogram_thresholds(tmin, tmax);
654 
655  if ( mod_flag )
656  truncate_to_min_max(tmin, tmax);
657  else
658  truncate_to_avg(tmin, tmax);
659 
660  return 0;
661 }
662 
663 
678 long Bimage::replace_maxima(double threshold)
679 {
680  Bimage* pmask = regions(threshold, 0);
681 
682  if ( verbose & ( VERB_LABEL | VERB_PROCESS ) ) {
683  cout << "Replacing maxima above: " << threshold << endl;
684  cout << "Number of maxima: " << pmask->maximum() << endl << endl;
685  }
686 
687  if ( pmask->maximum() < 1 ) { // No regions found = no modification
688  delete pmask;
689  return 0;
690  }
691 
692  long i, j, k, m, nn, xx, yy, zz, iter, nvr(0);
693  long kx, ky, kz, nval, tx, ty, tz;
694  long nr((long) (pmask->maximum() + 1.9)), rs;
695  double val;
696  Vector3<long> lo, hi, region_size;
697 
698  int* num = new int[nr];
699  int* nimg = new int[nr];
700  Vector3<float>* region = new Vector3<float>[nr];
701  Vector3<int>* rmin = new Vector3<int>[nr];
702  Vector3<int>* rmax = new Vector3<int>[nr];
703  float* temp;
704 
705  for ( j=1; j<nr; j++ ) rmin[j] = size();
706 
707  for ( i=nn=0; nn<n; nn++ ) {
708  for ( zz=0; zz<z; zz++ ) {
709  for ( yy=0; yy<y; yy++ ) {
710  for ( xx=0; xx<x; xx++, i++ ) {
711  j = (long) (*pmask)[i];
712  if ( j ) {
713  num[j]++;
714  nimg[j] = nn;
715  region[j][0] += xx;
716  region[j][1] += yy;
717  region[j][2] += zz;
718  if ( rmin[j][0] > xx ) rmin[j][0] = xx;
719  if ( rmin[j][1] > yy ) rmin[j][1] = yy;
720  if ( rmin[j][2] > zz ) rmin[j][2] = zz;
721  if ( rmax[j][0] < xx ) rmax[j][0] = xx;
722  if ( rmax[j][1] < yy ) rmax[j][1] = yy;
723  if ( rmax[j][2] < zz ) rmax[j][2] = zz;
724  }
725  }
726  }
727  }
728  }
729 
730  if ( verbose & VERB_STATS )
731  cout << "Regions:\n#\tImage\tx\ty\tz\tSize" << endl;
732  for ( j=1; j<nr; j++ ) {
733  nn = nimg[j];
734  if ( num[j] ) region[j] /= num[j];
735  if ( verbose & VERB_STATS )
736  cout << j << tab << nn << tab << region[j] << tab << num[j] << endl;
737  rmin[j] = rmin[j].max(0);
738  rmax[j] = rmax[j].min(size()-1);
739  region_size = rmax[j] - rmin[j] + 1;
740  rs = (long) region_size.volume();
741  temp = new float[rs];
742  nval = iter = 0;
743  val = 0;
744  while ( nval < num[j] ) {
745  for ( k=0; k<rs; k++ )
746  temp[k] = min;
747  for ( zz=rmin[j][2], tz=0; zz<=rmax[j][2]; zz++, tz++ ) {
748  for ( yy=rmin[j][1], ty=0; yy<=rmax[j][1]; yy++, ty++ ) {
749  for ( xx=rmin[j][0], tx=0; xx<=rmax[j][0]; xx++, tx++ ) {
750  i = index(0,xx,yy,zz,nn);
751  lo = kernel_low(i);
752  hi = kernel_high(i);
753  if ( (*pmask)[i] == j ) {
754  val = 0;
755  m = 0;
756  for ( kz=lo[2]; kz<=hi[2]; kz++ ) {
757  for ( ky=lo[1]; ky<=hi[1]; ky++ ) {
758  for ( kx=lo[0]; kx<=hi[0]; kx++ ) {
759  k = index(0,kx,ky,kz,nn);
760  if ( (*pmask)[k] < 1 ) {
761  val += (*this)[k];
762  m++;
763  }
764  }
765  }
766  }
767  if ( m ) {
768  k = (tz*region_size[1] + ty)*region_size[0] + tx;
769  temp[k] = val/m;
770  }
771  }
772  }
773  }
774  }
775  for ( zz=rmin[j][2], k=tz=0; zz<=rmax[j][2]; zz++, tz++ ) {
776  for ( yy=rmin[j][1], ty=0; yy<=rmax[j][1]; yy++, ty++ ) {
777  for ( xx=rmin[j][0], tx=0; xx<=rmax[j][0]; xx++, tx++, k++ ) {
778  if ( temp[k] > min ) {
779  i = index(0,xx,yy,zz,nn);
780  set(i, temp[k]);
781  if ( (*pmask)[i] == j ) pmask->set(i, 0);
782  nval++;
783  }
784  }
785  }
786  }
787  iter++;
788  if ( verbose & VERB_FULL )
789  cout << iter << ":\t" << nval << endl;
790  }
791  delete[] temp;
792  nvr += nval;
793  }
794  if ( verbose & ( VERB_STATS | VERB_FULL ) )
795  cout << endl;
796 
797  delete[] num;
798  delete[] nimg;
799  delete[] region;
800  delete[] rmin;
801  delete[] rmax;
802 
803  delete pmask;
804 
805  return nvr;
806 }
807 
820 double Bimage::mass_threshold(long img_num, double mol_weight, double rho)
821 {
822  if ( rho <= 0 ) rho = RHO;
823 
824  long i, j, nn, nvox(0);
825  long dnvox(-1);
826  long imgsize(x*y*z);
827 
828  double mass, dmass, vs(voxel_size());
829  double volume(mol_weight/rho);
830  double threshold(0);
831  double thresh_step;
832  double vol_diff;
833  double min_vol(vs);
834  double min_step(1e-6*std);
835 
836  if ( verbose & VERB_LABEL ) {
837  cout << "Finding the threshold for image " << img_num+1 << ":" << endl;
838  cout << "Protein density: " << rho << " Da/A3" << endl;
839  cout << "Molecular weight: " << mol_weight << " Da" << endl;
840  cout << "Molecular volume: " << volume << " A3" << endl;
841  cout << "Voxel size: " << vs << " A3" << endl << endl;
842  }
843 
844  if ( verbose )
845  cout << "Image\tThresh\tVolRes\tIntMass\tMW/mass" << endl;
846  for ( nn=0; nn<n; nn++ ) {
847  if ( verbose & VERB_FULL )
848  cout << " Threshold\tThreshStep\tVolume(A3)\tDifference\tMass" << endl;
849  threshold = avg;
850  thresh_step = std/2;
851  nvox = 0;
852  mass = 0;
853  vol_diff = 1e30;
854  while ( fabs(vol_diff) >= min_vol && fabs(thresh_step) > min_step ) {
855  dnvox = nvox;
856  dmass = mass;
857  if ( vol_diff > 0 ) {
858  if ( thresh_step < 0 ) thresh_step *= -0.5;
859  } else {
860  if ( thresh_step > 0 ) thresh_step *= -0.5;
861  }
862  threshold += thresh_step;
863  for ( i=nn*imgsize, j=i+imgsize, nvox = 0, mass = 0; i<j; i++ ) {
864  if ( (*this)[i] >= threshold ) {
865  nvox++;
866  mass += (*this)[i];
867  }
868  }
869  vol_diff = nvox*vs - volume;
870  if ( verbose & VERB_FULL )
871  cout << threshold << tab << thresh_step << tab
872  << nvox*vs << tab << vol_diff << tab << mass << endl;
873  dnvox = nvox - dnvox;
874  dmass = mass - dmass;
875  }
876  if ( verbose )
877  cout << nn+1 << tab << threshold << tab <<
878  fabs(vol_diff)/volume << tab << mass << tab << mol_weight/mass << endl;
879  }
880  if ( verbose )
881  cout << endl;
882 
883 /*
884  if ( verbose & VERB_LABEL ) {
885  cout << "Threshold: " << threshold << endl;
886  cout << "Relative volume residual: " << fabs(vol_diff)/volume << endl;
887  cout << "Integrated mass: " << mass << endl;
888  cout << "Molecular weight/mass: " << mol_weight/mass << endl << endl;
889  }
890 */
891  return threshold;
892 }
893 
904 double Bimage::mass_at_threshold(long img_num, double threshold, double rho)
905 {
906  if ( rho <= 0 ) rho = RHO;
907 
908  long i, j, nvox;
909  long imgsize(x*y*z);
910 
911  for ( i=img_num*imgsize, j=i+imgsize, nvox=0; i<j; i++ )
912  if ( (*this)[i] >= threshold ) nvox++;
913 
914  double vs(voxel_size());
915  double volume(nvox*vs);
916  double mass(volume*rho);
917 
918  if ( verbose & VERB_LABEL ) {
919  cout << "Protein density: " << rho << " Da/A3" << endl;
920  cout << "Threshold: " << threshold << endl;
921  cout << "Volume: " << volume << " A3" << endl;
922  cout << "Molecular weight: " << mass << " Da" << endl << endl;
923  }
924 
925  return mass;
926 }
927 
934 Bimage* Bimage::internal_volume(double threshold)
935 {
936  long i, j, jn, jz, jy, nn;
937  long xx, yy, zz;
938  long slicesize(x*y), imgsize(x*y*z);
939  long mode, kmax;
940  double d0, dk, dd;
941  Vector3<long> lo, hi, nk(3,3,3), k;
942 
943  int sign(1);
944  if ( threshold < avg ) sign = -1;
945 
946  Bimage* pv = copy();
947  pv->fill(0);
948 
949  for ( i=nn=0; nn<n; nn++ ) {
950  jn = nn*imgsize;
951  for ( zz=0; zz<z; ++zz ) {
952  lo[2] = (zz>nk[2])? zz-nk[2]: 0;
953  hi[2] = (zz<z-nk[2])? zz+nk[2]: zz;
954  cout << "z = " << zz << endl;
955  for ( yy=0; yy<y; ++yy ) {
956  lo[1] = (yy>nk[1])? yy-nk[1]: 0;
957  hi[1] = (yy<y-nk[1])? yy+nk[1]: yy;
958  for ( xx=0; xx<x; ++xx, ++i ) {
959  lo[0] = (xx>nk[0])? xx-nk[0]: 0;
960  hi[0] = (xx<x-nk[0])? xx+nk[0]: xx;
961  mode = kmax = 0;
962  if ( sign*(*this)[i] >= threshold ) {
963  mode = 1;
964  d0 = (Vector3<double>(xx, yy, zz) -
965  image[nn].origin()).length();
966  }
967  jz = jn + lo[2]*slicesize;
968  dd = 0;
969  for ( k[2]=lo[2]; k[2]<=hi[2]; ++k[2], jz += slicesize ) {
970  jy = jz + lo[1]*x;
971  for ( k[1]=lo[1]; k[1]<=hi[1]; ++k[1], jy += x ) {
972  j = jy + lo[0];
973  for ( k[0]=lo[0]; k[0]<=hi[0]; ++k[0], ++j ) {
974  if ( mode ) {
975  dk = (image[nn].origin() - k).length();
976  if ( sign*(*this)[j] < threshold )
977  dd += d0 - dk;
978  if ( dk < d0 && sign*(*this)[j] < threshold )
979  kmax++;
980 // pv->set(j, 1);
981 // } else {
982 // if ( kmax < (*pv)[j] ) kmax = (*pv)[j];
983  }
984  }
985  }
986  }
987 // if ( kmax > 6 ) pv->set(i, 1);
988  if ( dd > 12 ) pv->set(i, 1);
989  }
990  }
991  }
992  }
993 
994  return pv;
995 }
996 
1004 Bimage* Bimage::internal_volume(double threshold, int mask_out_freq)
1005 {
1006  long i, j, jn, jz, jy, nn;
1007  long xx, yy, zz, kx, ky, kz;
1008  long iter, dvol, vol(0);
1009  long slicesize(x*y), imgsize(x*y*z);
1010  double vs(voxel_size());
1011  Vector3<long> lo, hi;
1012  Vector3<long> lo2, hi2;
1013 
1014  Bstring fn;
1015 
1016  int nb, nbcut(6), sign(1);
1017  if ( z < 2 ) nbcut = 2;
1018  if ( threshold < avg ) sign = -1;
1019 
1020  Bimage* pv = copy();
1021  pv->fill(0);
1022 
1023  for ( nn=0; nn<n; nn++ ) {
1024  jn = nn*imgsize;
1025  lo2 = image[nn].origin();
1026  i = index(lo2,nn);
1027  lo = image[nn].origin() - 1;
1028  lo = lo.max(0);
1029  hi = image[nn].origin() + 1;
1030  hi = hi.min(size()-1);
1031  pv->set(i, 2);
1032  dvol = vol = 1;
1033  if ( verbose ) {
1034  cout << "Image " << nn+1 << ":" << endl;
1035  cout << "Origin: " << lo2 << endl;
1036  cout << "Iter\tVol\tdVol\tVol(A3)\tdVol(A3)" << endl;
1037  }
1038  iter = 0;
1039  while ( dvol > 0 ) {
1040  dvol = 0;
1041  iter++;
1042  for ( zz=lo[2]; zz<=hi[2]; zz++ ) {
1043  lo2[2] = (zz)? zz-1: 0;
1044  hi2[2] = (zz<z-1)? zz+1: zz;
1045  for ( yy=lo[1]; yy<=hi[1]; yy++ ) {
1046  lo2[1] = (yy)? yy-1: 0;
1047  hi2[1] = (yy<y-1)? yy+1: yy;
1048  for ( xx=lo[0]; xx<=hi[0]; xx++ ) {
1049  lo2[0] = (xx)? xx-1: 0;
1050  hi2[0] = (xx<x-1)? xx+1: xx;
1051  i = index(0,xx,yy,zz,nn);
1052  nb = 0;
1053  if ( (*pv)[i] < 1 && sign*(*this)[i] <= threshold ) {
1054  jz = jn + lo2[2]*slicesize;
1055  for ( kz=lo2[2]; kz<=hi2[2]; kz++, jz += slicesize ) {
1056  jy = jz + lo2[1]*x;
1057  for ( ky=lo2[1]; ky<=hi2[1]; ky++, jy += x ) {
1058  j = jy + lo2[0];
1059  for ( kx=lo2[0]; kx<=hi2[0]; kx++, j++ ) {
1060  if ( i != j && (*pv)[j] > 1 ) nb++;
1061  }
1062  }
1063  }
1064  if ( ( nb >= vol ) || ( nb > nbcut ) ) {
1065  pv->set(i, 1);
1066  dvol++;
1067  } else pv->set(i, 0);
1068  }
1069  }
1070  }
1071  }
1072  lo2 = lo;
1073  hi2 = hi;
1074  for ( zz=lo2[2]; zz<=hi2[2]; zz++ ) {
1075  for ( yy=lo2[1]; yy<=hi2[1]; yy++ ) {
1076  for ( xx=lo2[0]; xx<=hi2[0]; xx++ ) {
1077  i = index(0,xx,yy,zz,nn);
1078  if ( (*pv)[i] == 1 ) {
1079  pv->set(i, 2);
1080  if ( lo[0] == xx && xx > 0 ) lo[0]--;
1081  if ( lo[1] == yy && yy > 0 ) lo[1]--;
1082  if ( lo[2] == zz && zz > 0 ) lo[2]--;
1083  if ( hi[0] == xx && xx < x - 1 ) hi[0]++;
1084  if ( hi[1] == yy && yy < y - 1 ) hi[1]++;
1085  if ( hi[2] == zz && zz < z - 1 ) hi[2]++;
1086  }
1087  }
1088  }
1089  }
1090  vol += dvol;
1091  if ( verbose )
1092  cout << iter << tab << vol << tab << dvol << tab
1093  << vol*vs << tab << dvol*vs << endl;
1094  if ( ( mask_out_freq > 0 && iter%mask_out_freq == 0 ) ||
1095  ( dvol <= 0 ) ) {
1096  if ( n == 1 ) fn = Bstring(iter, "v%04ld.mrc");
1097  else fn = Bstring(nn, "v%02ld") + Bstring(iter, "_%04ld.mrc");
1098 // write(fn);
1099  write_img(fn, pv, 0);
1100  }
1101  }
1102  }
1103 
1104  return pv;
1105 }
1106 
1125 Bimage* Bimage::kmeans_segment(long nregion, long max_iter, double ratio)
1126 {
1127  random_seed();
1128 
1129  long i, j, j4, h, k, m;
1130  double v, dv, mdv, da(1e30);
1131  double r(ratio/std);
1132  Vector3<long> coor;
1133  Vector3<double> vec, start, end(size()-1);
1134 
1135  long* nm = new long[nregion];
1136  double* a = new double[4*nregion]; // 3 values for coordinates and one for density
1137  double* an = new double[4*nregion];
1138 
1139  Bimage* pseg = copy_header();
1140  pseg->data_type(Integer);
1141  pseg->data_alloc_and_clear();
1142 
1143  if ( verbose ) {
1144  cout << "Segmentation using K-means:" << endl;
1145  cout << "Number of regions: " << nregion << endl;
1146  cout << "Density:distance ratio: " << ratio << endl << endl;
1147  }
1148 
1149  // Initial averages
1150  for ( j=j4=0; j<nregion; j++, j4+=4 ) {
1151  vec = vector3_random(start, end);
1152  for ( h=0; h<3; h++ ) a[j4+h] = vec[h];
1153  a[j4+3] = get(0, vec);
1154  if ( verbose & VERB_FULL )
1155  cout << j+1 << tab << vec << tab << a[j4+3] << endl;
1156  }
1157 
1158  // Iterations
1159  if ( verbose )
1160  cout << "#\tChange" << endl;
1161  for ( i=0; i<max_iter && da > 0.001; i++ ) {
1162  for ( j=0; j<nregion; j++ ) nm[j] = 0;
1163  for ( j=0; j<4*nregion; j++ ) an[j] = 0;
1164 
1165  for ( k=0; k<datasize; k++ ) {
1166  v = (*this)[k];
1167  coor = coordinates(k);
1168  for ( j=j4=m=0, mdv=1e30; j<nregion; j++, j4+=4 ) {
1169  if ( i ) dv = r * fabs(a[j4+3] - v);
1170  else dv = 0; // First iteration only distance
1171  for ( h=0; h<3; h++ ) dv += fabs(a[j4+h] - coor[h])/size()[h];
1172  if ( mdv > dv ) {
1173  mdv = dv;
1174  m = j;
1175  }
1176  }
1177  an[4*m+3] += v;
1178  for ( h=0; h<3; h++ ) an[4*m+h] += coor[h];
1179  nm[m]++;
1180  pseg->set(k, m);
1181  }
1182 
1183  for ( j=j4=0, da=0; j<nregion; j++, j4+=4 ) {
1184  if ( nm[j] < 1 ) {
1185  vec = vector3_random(start, end);
1186  for ( h=0; h<3; h++ ) an[j4+h] = vec[h];
1187  an[j4+3] = get(0, vec);
1188  }
1189  if ( verbose & VERB_FULL )
1190  cout << j+1 << tab << nm[j];
1191  for ( h=0; h<4; h++ ) {
1192  if ( nm[j] ) an[j4+h] /= nm[j];
1193  da += fabs(a[j4+h] - an[j4+h]);
1194  a[j4+h] = an[j4+h];
1195  if ( verbose & VERB_FULL )
1196  cout << tab << a[j4+h];
1197  }
1198  if ( verbose & VERB_FULL )
1199  cout << endl;
1200  }
1201  da /= 4*nregion;
1202  if ( verbose )
1203  cout << i+1 << tab << da << endl;
1204  }
1205 
1206  delete[] nm;
1207  delete[] a;
1208  delete[] an;
1209 
1210  return pseg;
1211 }
1212 
1213 /*
1214  Functions for graph segmentation
1215 */
1216 int QsortSmallToLargeEdge(const void *x, const void *y)
1217 {
1218  GSedge* r1 = (GSedge*) x;
1219  GSedge* r2 = (GSedge*) y;
1220  if( r1->w < r2->w ) return -1;
1221  else return 1;
1222 }
1223 
1224 long region_find(GSregion* region, long i)
1225 {
1226  long j(i);
1227  while ( j != region[j].p ) j = region[j].p;
1228  region[i].p = j;
1229  return j;
1230 }
1231 
1232 int region_join(GSregion* region, long i, long j)
1233 {
1234  if ( i == j ) return 0;
1235 
1236  int s(region[i].s + region[j].s);
1237  double a((region[i].s*region[i].a + region[j].s*region[j].a)/s);
1238 
1239  if ( region[i].r > region[j].r ) {
1240  region[j].p = i;
1241  region[i].s += region[j].s;
1242  region[i].a = a;
1243  } else {
1244  region[i].p = j;
1245  region[j].s += region[i].s;
1246  region[j].a = a;
1247  if ( region[i].r == region[j].r ) region[j].r++;
1248  }
1249 
1250  return 1;
1251 }
1252 
1253 /*
1254  Sets up every voxel as a region with the voxel value.
1255 */
1257 {
1258  long i, imagesize(p->image_size());
1259 
1260  GSregion* region = new GSregion[imagesize];
1261 
1262  if ( pmask ) pmask->to_mask();
1263 
1264  for ( i=0; i<imagesize; i++ ) {
1265  region[i].p = i;
1266  region[i].r = 0;
1267  region[i].s = 1;
1268  if ( !pmask || ( pmask && (*pmask)[i] ) ) {
1269  if ( p->compound_type() == TSimple )
1270  region[i].a = (*p)[i];
1271  else if ( p->compound_type() == TRGB )
1272  region[i].a = p->rgb(i).average();
1273  }
1274  else region[i].a = 0;
1275  }
1276 
1277  return region;
1278 }
1279 
1280 /*
1281  Sets up each forward edge
1282 */
1283 GSedge* edge_setup(Bimage* p, Bimage* pmask, int connect_type, long& me, long& ne)
1284 {
1285  long x(p->sizeX()), y(p->sizeY()), z(p->sizeZ());
1286  long i, xx, yy, zz, x1, y1, z1;
1287  long imagesize(p->image_size());
1288  long dim = (z > 1)? 3: 2;
1289  long nn(imagesize);
1290 
1291  if ( pmask ) {
1292  pmask->to_mask();
1293  for ( nn=i=0; i<imagesize; i++ ) if ( (*pmask)[i] ) nn++;
1294  }
1295 
1296  if ( connect_type < 1 ) me = dim*nn;
1297  else me = (z > 1)? 13*nn: 4*nn;
1298 
1299  GSedge* edge = new GSedge[me];
1300 
1301  for ( ne=i=zz=0; zz<z; zz++ ) {
1302  for ( yy=0; yy<y; yy++ ) {
1303  for ( xx=0; xx<x; xx++, i++ ) if ( !pmask || ( pmask && (*pmask)[i] ) ) {
1304  if ( xx < x - 1 ) {
1305  x1 = xx + 1;
1306  if ( connect_type ) {
1307  for ( z1=(zz>0)?zz-1:zz; z1<zz+1 && z1<z; z1++ ) {
1308  for ( y1=(yy>0)?yy-1:yy; y1<yy+1 && y1<y; y1++ ) {
1309  edge[ne].u = i;
1310  edge[ne++].v = (z1*y + y1)*x + x1;
1311  }
1312  }
1313  } else {
1314  edge[ne].u = i;
1315  edge[ne++].v = (zz*y + yy)*x + x1;
1316  }
1317  }
1318  if ( yy < y - 1 ) {
1319  y1 = yy + 1;
1320  if ( connect_type ) {
1321  for ( z1=(zz>0)?zz-1:zz; z1<zz+1 && z1<z; z1++ ) {
1322  edge[ne].u = i;
1323  edge[ne++].v = (z1*y + y1)*x + xx;
1324  }
1325  } else {
1326  edge[ne].u = i;
1327  edge[ne++].v = (zz*y + y1)*x + xx;
1328  }
1329  }
1330  if ( zz < z - 1 ) {
1331  z1 = zz + 1;
1332  edge[ne].u = i;
1333  edge[ne++].v = (z1*y + yy)*x + xx;
1334  }
1335  }
1336  }
1337  }
1338 
1339  if ( p->compound_type() == TSimple )
1340  for ( i=0; i<ne; i++ ) edge[i].w = fabs((*p)[edge[i].u] - (*p)[edge[i].v]);
1341  else if ( p->compound_type() == TRGB )
1342 // for ( i=0; i<ne; i++ ) edge[i].w = fabs((p->rgb(edge[i].u) - p->rgb(edge[i].v)).average());
1343  for ( i=0; i<ne; i++ ) edge[i].w = fabs((p->rgb(edge[i].u) - p->rgb(edge[i].v)).rms());
1344 
1345  return edge;
1346 }
1347 
1348 /*
1349  The starting threshold is taken to be the standard deviation divided by the complexity value
1350 */
1351 long region_merging(GSregion* region, GSedge* edge, long nrc, long ne, float threshold)
1352 {
1353  long i, u, v;
1354  GSedge e;
1355  for ( i=0; i<ne; i++ ) {
1356  e = edge[i];
1357  u = region_find(region, e.u);
1358  v = region_find(region, e.v);
1359  if ( u != v ) {
1360  if ( e.w <= region[u].a && e.w <= region[v].a ) {
1361  nrc -= region_join(region, u, v);
1362  u = region_find(region, u);
1363  region[u].a = e.w + threshold/region[u].s;
1364  }
1365  }
1366  }
1367 
1368  return nrc;
1369 }
1370 
1371 /*
1372  fac = g*g/Q, g is taken to be the standard deviation and Q a complexity value
1373 */
1374 long statistical_region_merging(GSregion* region, GSedge* edge, long nr, long ne, double fac)
1375 {
1376  // Find segment memberships
1377  double d2, ln1, ln2, s1, s2;
1378  double lnd(2*log(6*nr));
1379  long i, u, v, nrc(nr);
1380  GSedge e;
1381 
1382  for ( i=0; i<ne; i++ ) {
1383  e = edge[i];
1384  u = region_find(region, e.u);
1385  v = region_find(region, e.v);
1386  if ( u != v ) {
1387  d2 = region[u].a - region[v].a; d2 *= d2;
1388  s1 = region[u].s; s2 = region[v].s;
1389 // ln1 = lnd + log(1.0 + s1) * ((g < s1)? g: s1);
1390 // ln2 = lnd + log(1.0 + s2) * ((g < s2)? g: s2);
1391  ln1 = lnd + log(1.0 + s1);
1392  ln2 = lnd + log(1.0 + s2);
1393  if ( d2 < fac * (ln1/s1 + ln2/s2) )
1394  nrc -= region_join(region, u, v);
1395  }
1396  }
1397 
1398  return nrc;
1399 }
1400 
1401 long region_merge_small(GSregion* region, GSedge* edge, long nrc, long ne, int min_size)
1402 {
1403  if ( min_size < 1 ) return nrc;
1404 
1405  // Merge small regions
1406  long i, u, v;
1407  GSedge e;
1408 
1409  for ( i=0; i<ne; i++ ) {
1410  e = edge[i];
1411  u = region_find(region, e.u);
1412  v = region_find(region, e.v);
1413  if ( ( u != v ) && ( region[u].s < min_size || region[v].s < min_size ) ) {
1414  nrc -= region_join(region, u, v);
1415  }
1416  }
1417 
1418  return nrc;
1419 }
1420 
1443 Bimage* Bimage::graph_segment(int type, Bimage* pmask, int connect_type,
1444  double complexity, long min_size, int return_type)
1445 {
1446 // color_to_simple();
1447 // change_type(Float);
1448 
1449  long i, j, ne;
1450  long slicesize(x*y);
1451  long imagesize(slicesize*z);
1452  long dim = (z > 1)? 3: 2;
1453  long max_edges;
1454  double threshold(std/complexity);
1455 
1456  if ( pmask ) pmask->to_mask();
1457 
1458  if ( verbose ) {
1459  cout << "Segmenting image:" << endl;
1460  cout << "Algorithm: ";
1461  if ( type == 1 ) {
1462  cout << "Simple" << endl;
1463  cout << "Threshold: " << threshold << endl;
1464  } else {
1465  cout << "Statistical region merging" << endl;
1466  cout << "Complexity: " << complexity << endl;
1467  }
1468  cout << "Connectivity: ";
1469  if ( connect_type < 1 ) cout << 2*dim << endl;
1470  else if ( dim < 3 ) cout << 8 << endl;
1471  else cout << 26 << endl;
1472  cout << "Minimum size: " << min_size << endl;
1473  }
1474 
1475  GSregion* region = region_setup(this, pmask);
1476 
1477  GSedge* edge = edge_setup(this, pmask, connect_type, max_edges, ne);
1478 
1479  qsort((void *) edge, ne, sizeof(GSedge),
1480  (int (*)(const void *, const void *)) QsortSmallToLargeEdge);
1481 
1482  if ( verbose )
1483  cout << "Number of edges: " << ne << endl;
1484 
1485  long nr(imagesize), nrc(imagesize);
1486 
1487  // Find segment memberships
1488  if ( type == 1 ) {
1489  for ( i=0; i<imagesize; i++ ) region[i].a = threshold;
1490  nrc = region_merging(region, edge, nr, ne, threshold);
1491  } else {
1492  nrc = statistical_region_merging(region, edge, imagesize, ne, threshold*threshold);
1493  }
1494 
1495  // Merge small regions
1496  if ( min_size > 0 ) {
1497  if ( verbose )
1498  cout << "Regions before merging: " << nrc << endl;
1499  nrc = region_merge_small(region, edge, nrc, ne, min_size);
1500  }
1501 
1502  delete[] edge;
1503 
1504  if ( verbose )
1505  cout << "Number of regions: " << nrc << endl << endl;
1506 
1507  Bimage* pseg = NULL;
1508 
1509  if ( return_type < 1 ) {
1510  pseg = new Bimage(Integer, TSimple, size(), 1);
1511 
1512  for ( nrc=i=0; i<imagesize; i++ )
1513  if ( region[i].p == i ) region[i].r = ++nrc;
1514 
1515  for ( i=0; i<imagesize; i++ ) {
1516  j = region_find(region, i);
1517  pseg->set(i, region[j].r);
1518  }
1519  } else {
1520  pseg = new Bimage(Float, TSimple, size(), 1);
1521 
1522  for ( i=0; i<imagesize; i++ )
1523  region[i].a = region[i].s = 0;
1524 
1525  for ( i=0; i<imagesize; i++ ) {
1526  j = region_find(region, i);
1527  region[j].a += (*this)[i];
1528  region[j].s += 1;
1529  }
1530 
1531  for ( i=0; i<imagesize; i++ )
1532  if ( region[j].s ) region[i].a /= region[i].s;
1533 
1534  for ( i=0; i<imagesize; i++ ) {
1535  j = region_find(region, i);
1536  pseg->set(i, region[j].a);
1537  }
1538  }
1539 
1540  delete[] region;
1541 
1542  pseg->sampling(sampling(0));
1543  pseg->origin(image->origin());
1544  pseg->statistics();
1545 
1546  return pseg;
1547 }
1548 
1549 /*
1550  For a pixel i:
1551  calculate kernel extents, size=k
1552  calculate superpixel centers, O(k): (4+c)*add
1553  calculate superpixel weights, O(k): (c-1)*add + (c+1)*mul
1554 */
1555 int img_update_segment(long i, Bimage* p, Bimage* pmask, vector<long> vstep,
1556  double colorweight, vector<Bsuperpixel>& seg)
1557 {
1558  long j, xx, yy, zz;
1559  double d, icw(1/colorweight);
1560  double m(p->standard_deviation()*p->standard_deviation()/colorweight);
1561  vector<double> dvec = seg[i].coordinates();
1562  vector<long> vec(dvec.begin(), dvec.end());
1563 
1564  vector<long> kmin = vec - vstep;
1565  kmin = vecmax(kmin, 0);
1566 // kmin = vecmin(kmin, p->size());
1567  if ( kmin[0] > p->sizeX() ) kmin[0] = p->sizeX();
1568  if ( kmin[1] > p->sizeY() ) kmin[1] = p->sizeY();
1569  if ( kmin[2] > p->sizeZ() ) kmin[2] = p->sizeZ();
1570 
1571  vector<long> kmax = vec + vstep;
1572 // kmax = vecmin(kmax, p->size());
1573  if ( kmax[0] > p->sizeX() ) kmax[0] = p->sizeX();
1574  if ( kmax[1] > p->sizeY() ) kmax[1] = p->sizeY();
1575  if ( kmax[2] > p->sizeZ() ) kmax[2] = p->sizeZ();
1576 
1577  seg[i].clear();
1578  seg[i].weight(m);
1579 
1580  for ( zz=kmin[2]; zz<kmax[2]; zz++ ) {
1581  for ( yy=kmin[1]; yy<kmax[1]; yy++ ) {
1582  for ( xx=kmin[0]; xx<kmax[0]; xx++ ) {
1583  j = p->index(xx, yy, zz);
1584  if ( i == (*pmask)[j]) {
1585  seg[i].add(xx, yy, zz, p->values(j));
1586  }
1587  }
1588  }
1589  }
1590 
1591  seg[i].average();
1592 
1593  for ( zz=kmin[2]; zz<kmax[2]; zz++ ) {
1594  for ( yy=kmin[1]; yy<kmax[1]; yy++ ) {
1595  for ( xx=kmin[0]; xx<kmax[0]; xx++ ) {
1596  j = p->index(xx, yy, zz);
1597  if ( i == (*pmask)[j]) {
1598  d = seg[i].difference2(p->values(j));
1599  d *= icw;
1600  if ( seg[i].weight() < d ) seg[i].weight(d);
1601  }
1602  }
1603  }
1604  }
1605 
1606  return 0;
1607 }
1608 
1609 int Bimage::superpixels_update(Bimage* pmask, vector<long> vstep,
1610  double colorweight, vector<Bsuperpixel>& seg)
1611 {
1612  long nseg(seg.size());
1613 
1614 #ifdef HAVE_GCD
1615  dispatch_apply(nseg, dispatch_get_global_queue(0, 0), ^(size_t i){
1616  img_update_segment(i, this, pmask, vstep, colorweight, seg);
1617  });
1618 #else
1619 #pragma omp parallel for
1620  for ( long i=0; i<nseg; i++ )
1621  img_update_segment(i, this, pmask, vstep, colorweight, seg);
1622 #endif
1623 
1624  return 0;
1625 }
1626 
1627 /*
1628  For a pixel i:
1629  For each neighboring superpixel center m:
1630  fom = wd * distance^2 + color_difference^2 / superpixel_weight
1631  set the mask to the minimum fom
1632  O(NNEIGHBOR)
1633  (6+c)*add + (7+c)*mul + 1*div
1634 */
1635 int img_assign_pixel(long i, Bimage* p, Bimage* pmask, double wd,
1636  vector<Bsuperpixel>& seg)
1637 {
1638  long j((*pmask)[i]), k, m;
1639  double dd, dc, d, fom(1e30);
1640  Vector3<long> coor3 = p->coordinates(i*p->channels());
1641 // vector<double> coor = {double(coor3[0]), double(coor3[1]), double(coor3[2])};
1642  vector<double> scoor;
1643 
1644  vector<double> val = p->values(i);
1645 
1646 // cout << i << endl;
1647 
1648  for ( k=-1, m=j; k<NNEIGHBOR; ) {
1649  scoor = seg[m].coordinates() - coor3;
1650  dd = length2(scoor);
1651  dc = seg[m].difference2(val);
1652  d = dd*wd + dc/seg[m].weight();
1653  if ( fom >= d ) {
1654  fom = d;
1655  pmask->set(i, m);
1656  }
1657  if ( ++k == NNEIGHBOR || ( m = seg[j].neighbor(k) ) < 0 ) break;
1658  }
1659 
1660  return 0;
1661 }
1662 
1663 int img_assign_segments(Bimage* p, Bimage* pmask, vector<long> vstep,
1664  vector<Bsuperpixel>& seg)
1665 {
1666  long i, nc(0);
1667  double dr(volume(vstep)), wd(1.0L/dr);
1668 
1669  Bimage* pmc = pmask->copy();
1670 
1671 #ifdef HAVE_GCD
1672  dispatch_apply(p->image_size(), dispatch_get_global_queue(0, 0), ^(size_t i){
1673  img_assign_pixel(i, p, pmask, wd, seg);
1674  });
1675 #else
1676 #pragma omp parallel for
1677  for ( i=0; i<p->image_size(); i++ )
1678  img_assign_pixel(i, p, pmask, wd, seg);
1679 #endif
1680 
1681  for ( i=0; i<pmask->image_size(); i++ ) if ( (*pmask)[i] - (*pmc)[i] ) nc++;
1682 
1683  delete pmc;
1684 
1685  return nc;
1686 }
1687 
1688 int img_impose_segments(Bimage* p, Bimage* pmask, vector<Bsuperpixel>& seg)
1689 {
1690  long i, j, cc;
1691 
1692  for ( i=j=0; i<p->image_size(); i++ )
1693  for ( cc=0; cc<p->channels(); cc++, j++ )
1694  p->set(j, seg[(long)(*pmask)[i]].channel(cc));
1695 
1696  return 0;
1697 }
1698 
1699 long segment_lowest_neighbor(vector<Bsuperpixel>& seg, long i, long cc)
1700 {
1701  long j, k, ln(i);
1702  double min(seg[i].channel(cc));
1703  for ( j=0; j<NNEIGHBOR && ( k = seg[i].neighbor(j) ) >= 0; ++j ) {
1704  if ( seg[k].channel(cc) < min ) {
1705  min = seg[k].channel(cc);
1706  ln = k;
1707  }
1708  }
1709  return ln;
1710 }
1711 
1712 int img_impose_lowest_neighbor(Bimage* p, Bimage* pmask, vector<Bsuperpixel>& seg)
1713 {
1714  long i, j, is, cc;
1715 
1716  for ( i=j=0; i<p->image_size(); i++ )
1717  for ( cc=0; cc<p->channels(); cc++, j++ ) {
1718  is = segment_lowest_neighbor(seg, (*pmask)[i], cc);
1719  p->set(j, seg[is].channel(cc));
1720  }
1721 
1722  return 0;
1723 }
1724 
1725 long segment_highest_neighbor(vector<Bsuperpixel>& seg, long i, long cc)
1726 {
1727  long j, k, ln(i);
1728  double max(seg[i].channel(cc));
1729  for ( j=0; j<NNEIGHBOR && ( k = seg[i].neighbor(j) ) >= 0; ++j ) {
1730  if ( seg[k].channel(cc) > max ) {
1731  max = seg[k].channel(cc);
1732  ln = k;
1733  }
1734  }
1735  return ln;
1736 }
1737 
1738 int img_impose_highest_neighbor(Bimage* p, Bimage* pmask, vector<Bsuperpixel>& seg)
1739 {
1740  long i, j, is, cc;
1741 
1742  for ( i=j=0; i<p->image_size(); i++ )
1743  for ( cc=0; cc<p->channels(); cc++, j++ ) {
1744  is = segment_highest_neighbor(seg, (*pmask)[i], cc);
1745  p->set(j, seg[is].channel(cc));
1746  }
1747 
1748  return 0;
1749 }
1750 
1751 int img_impose_difference_from_highest_neighbor(Bimage* p, Bimage* pmask, vector<Bsuperpixel>& seg)
1752 {
1753  long i, j, is, cc;
1754  double v;
1755 
1756  for ( i=j=0; i<p->image_size(); i++ )
1757  for ( cc=0; cc<p->channels(); cc++, j++ ) {
1758  is = segment_highest_neighbor(seg, (*pmask)[i], cc);
1759  v = seg[(long)(*pmask)[i]].channel(cc);
1760  p->set(j, seg[is].channel(cc) - v);
1761  }
1762 
1763  return 0;
1764 }
1765 
1766 long segment_setup_neighbors(long i, vector<Bsuperpixel>& seg, double dmax)
1767 {
1768  long nseg(seg.size());
1769  long j, nn(0);
1770  double d;
1771 
1772  for ( j=0; j<nseg; j++ ) if ( j != i ) {
1773  d = distance(seg[i].coordinates(), seg[j].coordinates());
1774  if ( d < dmax ) {
1775  seg[i].add_neighbor(j);
1776  nn++;
1777  }
1778  }
1779 
1780  return nn;
1781 }
1782 
1783 long segments_setup_neighbors(vector<Bsuperpixel>& seg, long step)
1784 {
1785  long nseg(seg.size());
1786  long i, j, nn(0);
1787  double dmax(1.9*step);
1788 
1789  for ( i=0; i<nseg; i++ ) seg[i].clear_neighbors();
1790 
1791 #ifdef HAVE_GCD
1792  dispatch_apply(nseg, dispatch_get_global_queue(0, 0), ^(size_t i){
1793  segment_setup_neighbors(i, seg, dmax);
1794  });
1795 #else
1796 #pragma omp parallel for
1797  for ( i=0; i<nseg; i++ )
1798  segment_setup_neighbors(i, seg, dmax);
1799 #endif
1800 
1801  for ( i=0; i<nseg; i++ )
1802  for ( j=0; j<NNEIGHBOR && seg[i].neighbor(j) >= 0; ++j ) nn++;
1803 
1804  if ( verbose & VERB_FULL ) {
1805  for ( i=0; i<nseg; i++ ) {
1806  cout << seg[i].index() << tab << seg[i].coordinates();
1807  for ( j=0; j<NNEIGHBOR && seg[i].neighbor(j) >= 0; ++j ) cout << tab << seg[i].neighbor(j);
1808  cout << endl;
1809  }
1810  }
1811 
1812  return nn;
1813 }
1814 
1821 vector<Bsuperpixel> Bimage::superpixels_from_mask(long cc, long step)
1822 {
1823  long nseg = (long) (max + 1.9);
1824 
1825  if ( verbose )
1826  cout << "Setting up " << nseg << " segments" << endl;
1827 
1828  vector<Bsuperpixel> seg(nseg);
1829 
1830  long i, j, nn(0);
1831  Vector3<long> coor3;
1832  vector<double> v(cc, 0);
1833 
1834  for ( i=0; i<nseg; i++ ) {
1835  seg[i].index(i);
1836  seg[i].channels(cc);
1837  }
1838 
1839  for ( i=0; i<image_size(); i++ ) {
1840  j = (*this)[i];
1841  coor3 = coordinates(i);
1842  seg[j].add(coor3[0], coor3[1], coor3[2], v);
1843  }
1844 
1845  for ( i=0; i<nseg; i++ )
1846  seg[i].average();
1847 
1848  nn = segments_setup_neighbors(seg, step);
1849 
1850  if ( verbose )
1851  cout << "Total neigbors: " << nn << endl << endl;
1852 
1853  return seg;
1854 }
1855 
1872 vector<Bsuperpixel> Bimage::superpixels(long step, double colorweight, long iterations, double stop)
1873 {
1874  Bimage* pmask = tile_mask(step);
1875 
1876  long i, nc(image_size()), ncp(0), nstop(image_size()*stop/100);
1877 
1878  if ( verbose ) {
1879  cout << "SLIC superpixel segmentation:" << endl;
1880  cout << "Step size: " << step << endl;
1881  cout << "Color weight: " << colorweight << endl;
1882  cout << "Maximum number of iterations: " << iterations << endl;
1883  cout << "Stopping condition: " << stop << " % (" << nstop << ")" << endl << endl;
1884  }
1885 
1886  vector<Bsuperpixel> seg = pmask->superpixels_from_mask(c, step);
1887 
1888  vector<long> vstep = {step,step,step};
1889  for ( i=0; i<3; ++i ) vstep[i] *= 2;
1890 
1891  if ( vstep[2] > z ) vstep[2] = z;
1892 
1893  superpixels_update(pmask, vstep, colorweight, seg);
1894 
1895 // write_img("t.tif", pmask);
1896 
1897  time_t t = time(NULL);
1898 
1899  if ( verbose )
1900  cout << "Iter\tChange\t∆\tTime" << endl;
1901 
1902  for ( i=0; i<iterations && nc > nstop; i++ ) {
1903  nc = img_assign_segments(this, pmask, vstep, seg); // Slow step
1904  if ( verbose )
1905  cout << i+1 << tab << nc << tab << nc-ncp << tab << (long)(time(NULL) - t) << endl;
1906 // write_img("t.tif", pmask);
1907  ncp = nc;
1908  superpixels_update(pmask, vstep, colorweight, seg);
1909  segments_setup_neighbors(seg, step);
1910  }
1911 
1912  next = pmask;
1913 
1914  return seg;
1915 }
1916 
1918 {
1919  if ( !p->next ) return 0;
1920 
1921  long i, j;
1922  Vector3<long> c;
1923  Bimage* pb = NULL;
1924 
1925  for ( pb = p; pb->next; p = pb, pb = pb->next ) ;
1926 
1927  for ( i=0; i<p->image_size(); ++i ) {
1928  c = p->coordinates(i)/2;
1929  j = pb->index(c, 0);
1930  p->set(i, (*pb)[j]);
1931  }
1932 
1933  delete pb;
1934  p->next = NULL;
1935 
1936  return p;
1937 }
1938 
1939 vector<Bsuperpixel> Bimage::superpixels(long step, double colorweight, long iterations, long bin_level, double stop)
1940 {
1941  Bimage* pmask = tile_mask(step);
1942 
1943  if ( verbose ) {
1944  cout << "SLIC superpixel segmentation:" << endl;
1945  cout << "Step size: " << step << endl;
1946  cout << "Bin levels: " << bin_level << endl;
1947  cout << "Color weight: " << colorweight << endl;
1948  cout << "Maximum number of iterations: " << iterations << endl;
1949  cout << "Stopping condition: " << stop << " %" << endl << endl;
1950  }
1951 
1952  vector<Bsuperpixel> seg = pmask->superpixels_from_mask(c, step);
1953 
1954  long i, bin(1);
1955  vector<long> vstep = {step,step,step}, vbstep(3);
1956  for ( i=0; i<3; ++i ) vstep[i] *= 2;
1957  if ( vstep[2] > z ) vstep[2] = z;
1958 
1959  superpixels_update(pmask, vstep, colorweight, seg);
1960 
1961  time_t t = time(NULL);
1962 
1963  Bimage* pb = this;
1964  Bimage* pm = pmask;
1965  for ( i=1; i<bin_level; ++i ) {
1966  bin *= 2;
1967 // cout << "creating bin level " << i << endl;
1968  pb->next = pb->bin_copy(2);
1969  pm->next = pm->bin_copy(2);
1970  pb = pb->next;
1971  pm = pm->next;
1972  }
1973 
1974  long nc, ncp(0), nstop(pb->image_size()*stop/100);
1975  long bstep = step/bin;
1976  for ( i=0; i<3; ++i ) vbstep[i] = vstep[i]/bin;
1977  if ( vbstep[2] < 1 ) vbstep[2] = 1;
1978  for ( auto it = seg.begin(); it != seg.end(); ++it )
1979  it->scale(1.0/bin);
1980 
1981  while ( bin ) {
1982  nc = pb->image_size();
1983 
1984 // cout << "size = " << pb->size() << endl;
1985 // cout << "step = " << bstep << tab << vbstep[1] << endl;
1986 
1987  if ( verbose ) {
1988  cout << "Binning: " << bin << endl;
1989  cout << "Iter\tChange\t∆\tTime" << endl;
1990  }
1991 
1992  for ( i=0; i<iterations && nc > nstop; i++ ) {
1993  nc = img_assign_segments(pb, pm, vbstep, seg); // Slow step
1994  if ( verbose )
1995  cout << i+1 << tab << nc << tab << nc-ncp << tab << (long)(time(NULL) - t) << endl;
1996  ncp = nc;
1997  pb->superpixels_update(pm, vbstep, colorweight, seg);
1998  segments_setup_neighbors(seg, bstep);
1999  }
2000 
2001  bin /= 2;
2002 
2003  if ( bin ) {
2004  bstep *= 2;
2005  for ( i=0; i<3; ++i ) {
2006  vbstep[i] *= 2;
2007  if ( size()[i] > 1 ) ncp *= 2;
2008  }
2009  if ( z == 1 ) vbstep[2] = 1;
2010  for ( auto it = seg.begin(); it != seg.end(); ++it )
2011  it->scale(2.0);
2012  for ( pb = this; pb->next && pb->next->next; pb = pb->next ) ;
2013  delete pb->next;
2014  pb->next = NULL;
2015  pm = img_unbin_update(pmask);
2016 // pb->superpixels_update(pm, vbstep, colorweight, seg);
2017 // segments_setup_neighbors(seg, bstep);
2018  }
2019 
2020  iterations /= 2;
2021  }
2022 
2023  next = pmask;
2024 
2025  if ( verbose ) cout << endl;
2026 
2027  return seg;
2028 }
2029 
2045 int Bimage::impose_superpixels(Bimage* pmask, vector<Bsuperpixel>& seg, int impose)
2046 {
2047  if ( impose < 1 ) return 0;
2048  if ( !pmask ) {
2049  cerr << "Error in impose_superpixels: No multi-level mask!" << endl;
2050  return -1;
2051  }
2052 
2053  long i, j, cc, is, isn;
2054  double v, vv;
2055 
2056  change_type(Float);
2057 // pmask->information();
2058 
2059  if ( next ) delete next;
2060  next = copy();
2061 
2062  if ( verbose )
2063  cout << "Imposing segments using feature type " << impose << endl;
2064 
2065  for ( i=j=0; i<image_size(); i++ ) {
2066  for ( cc=0; cc<channels(); cc++, j++ ) {
2067  is = isn = (long)(*pmask)[i];
2068  if ( impose == 2 || impose == 3 ) {
2069  isn = segment_lowest_neighbor(seg, is, cc);
2070  } else if ( impose == 4 || impose == 5 ) {
2071  isn = segment_highest_neighbor(seg, is, cc);
2072  }
2073  if ( impose == 3 || impose == 5 ) {
2074  v = seg[isn].channel(cc) - seg[is].channel(cc);
2075  vv = seg[isn].variance(cc) - seg[is].variance(cc);
2076  } else {
2077  v = seg[isn].channel(cc);
2078  vv = seg[isn].variance(cc);
2079  }
2080  set(j, v);
2081  next->set(j, vv);
2082  }
2083  }
2084 
2085  return 0;
2086 }
2087 
2088 
2095 /*Bimage* Bimage::region_color_by_size(Bimage* pmask)
2096 {
2097  Bimage* pcol = new Bimage(UCharacter, TRGB, size(), n);
2098  pcol->sampling(sampling(0));
2099  pcol->origin(image->origin());
2100  RGB<unsigned char>* color = (RGB<unsigned char> *) pcol->data_pointer();
2101 
2102  if ( verbose )
2103  cout << "Coloring regions by size" << endl;
2104 
2105  long i, j, nseg((long)(pmask->maximum() + 1.9));
2106  long vmin(datasize), vmax(0);
2107  double vavg(0), vstd(0);
2108  RGB<unsigned char> black(0,0,0);
2109  int* vol = new int[nseg];
2110 
2111  for ( i=0; i<nseg; i++ ) vol[i] = 0;
2112 
2113  for ( i=0; i<datasize; i++ )
2114  if ( (*pmask)[i] > -1 ) vol[(long)(*pmask)[i]]++;
2115 
2116  for ( i=1; i<nseg; i++ ) {
2117  if ( vmin > vol[i] ) vmin = vol[i];
2118  if ( vmax < vol[i] ) vmax = vol[i];
2119  vavg += vol[i];
2120  vstd += vol[i] * vol[i];
2121  }
2122  vavg /= nseg - 1;
2123  vstd /= nseg - 1;
2124  vstd -= vavg * vavg;
2125  vstd = sqrt(vstd);
2126  if ( vmin < vavg - 3*vstd ) vmin = vavg - 3*vstd;
2127  if ( vmax > vavg + 3*vstd ) vmax = vavg + 3*vstd;
2128 
2129  if ( verbose )
2130  cout << "Coloring range: " << vmin << " - " << vmax << endl;
2131 
2132  for ( i=0; i<datasize; i++ ) {
2133  j = (*pmask)[i];
2134  if ( j > 0 )
2135  color[i].spectrum(vol[j], vmin, vmax);
2136  else
2137  color[i] = black;
2138  }
2139 
2140  delete[] vol;
2141 
2142  return pcol;
2143 }
2144 */
2145 
Bimage::regions
Bimage * regions(double threshold, int sign)
Segments an image into contiguous regions.
Definition: Bimage_segment.cpp:56
Bimage::coordinates
void coordinates(long i, long &nx, long &ny, long &nz)
Definition: Bimage.h:429
length2
double length2(vector< T > v)
Definition: Vector3.h:519
GSregion::p
long p
Definition: Bimage_segment.cpp:28
Bimage::region_threshold_series
int region_threshold_series(double threshold_first, double threshold_last, double threshold_step)
Segments a map through a series of thresholds and reports results.
Definition: Bimage_segment.cpp:200
Bimage::sizeZ
void sizeZ(long nz)
Definition: Bimage.h:392
RHO
#define RHO
Definition: utilities.h:95
GSedge::u
long u
Definition: Bimage_segment.cpp:20
VERB_DEBUG
#define VERB_DEBUG
Definition: utilities.h:116
segment_lowest_neighbor
long segment_lowest_neighbor(vector< Bsuperpixel > &seg, long i, long cc)
Definition: Bimage_segment.cpp:1699
Bimage::voxel_size
double voxel_size()
Definition: Bimage.h:506
Bimage::get
double get(long nn, long xx, long yy, long zz, long cc=0)
Returns the data value at the given coordinates.
Definition: Bimage.cpp:960
edge_setup
GSedge * edge_setup(Bimage *p, Bimage *pmask, int connect_type, long &me, long &ne)
Definition: Bimage_segment.cpp:1283
Bimage::average
double average()
Definition: Bimage.h:543
Bimage::set
void set(long j, double v)
Sets a single value at the given index.
Definition: Bimage.cpp:1118
Bstring
Definition: Bstring.h:29
region_merging
long region_merging(GSregion *region, GSedge *edge, long nrc, long ne, float threshold)
Definition: Bimage_segment.cpp:1351
Bimage::next
Bimage * next
Definition: Bimage.h:179
Bimage::superpixels_from_mask
vector< Bsuperpixel > superpixels_from_mask(long cc, long step)
Create superpixels from a multilevel mask.
Definition: Bimage_segment.cpp:1821
img_assign_segments
int img_assign_segments(Bimage *p, Bimage *pmask, vector< long > vstep, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1663
Bimage::Bimage
Bimage()
Initializes an image.
Definition: Bimage.cpp:43
Bimage::copy
Bimage * copy()
Copies the header information and data of an image into a new image structure.
Definition: Bimage.cpp:2702
vecmax
vector< T1 > vecmax(vector< T1 > v1, vector< T2 > v2)
Definition: Vector3.h:591
Vector3< long >
Bimage::sizeX
void sizeX(long nx)
Definition: Bimage.h:390
Bimage::values
vector< double > values(long i)
Definition: Bimage.h:297
Bimage::mass_at_threshold
double mass_at_threshold(long img_num, double threshold, double rho)
Calculates the mass from the density threshold.
Definition: Bimage_segment.cpp:904
error_show
int error_show(string message, string file, int line)
Displays the error with file and line reference.
Definition: utilities.cpp:719
Bimage::size
Vector3< long > size() const
Definition: Bimage.h:386
Bimage::levelmask_average_region_size
double levelmask_average_region_size()
Calculates the average size of regions in a level mask.
Definition: Bimage_mask.cpp:2022
vector3_random
Vector3< double > vector3_random(const double min, const double max)
Generates a random vector within a defined cube.
Definition: random_numbers.cpp:440
Bimage::kmeans_segment
Bimage * kmeans_segment(long nregion=2, long max_iter=10, double ratio=1)
Segments an image based on K-means.
Definition: Bimage_segment.cpp:1125
QsortSmallToLargeEdge
int QsortSmallToLargeEdge(const void *x, const void *y)
Definition: Bimage_segment.cpp:1216
img_update_segment
int img_update_segment(long i, Bimage *p, Bimage *pmask, vector< long > vstep, double colorweight, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1555
length
double length(vector< T > v)
Definition: Vector3.h:530
Bimage::region_flood
long region_flood(Bimage *pmask, double threshold_hi, double threshold_lo, double threshold_step, int fill_borders)
Creates and expands a region map from a starting to ending threshold value.
Definition: Bimage_segment.cpp:256
Bimage::image
Bsub_image * image
Definition: Bimage.h:202
VERB_PROCESS
#define VERB_PROCESS
Definition: utilities.h:111
Bimage::maximum
double maximum()
Definition: Bimage.h:542
img_impose_segments
int img_impose_segments(Bimage *p, Bimage *pmask, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1688
Bimage::internal_volume
Bimage * internal_volume(double threshold)
Calculates the internal volume of a shell.
Definition: Bimage_segment.cpp:934
GSregion::r
int r
Definition: Bimage_segment.cpp:29
Bimage::standard_deviation
double standard_deviation()
Definition: Bimage.h:544
img_impose_highest_neighbor
int img_impose_highest_neighbor(Bimage *p, Bimage *pmask, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1738
Bimage::kernel_max_wrap
long kernel_max_wrap(long idx, long ksize)
Finds the highest value in a kernel with wrapping.
Definition: Bimage.cpp:2965
Bimage::mass_threshold
double mass_threshold(long img_num, double mol_weight, double rho)
Finds the density threshold associated with a particular molecular weight.
Definition: Bimage_segment.cpp:820
Bsub_image::origin
void origin(double x, double y, double z)
Definition: Bimage.h:136
img_assign_pixel
int img_assign_pixel(long i, Bimage *p, Bimage *pmask, double wd, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1635
TSimple
@ TSimple
Definition: Bimage.h:59
write_img
int write_img(const char *filename, Bimage *p, int compression)
General driver function to write multiple image formats.
Definition: rwimg.cpp:281
Bimage::kernel_max
long kernel_max(long idx, long ksize)
Finds the highest value in a kernel.
Definition: Bimage.cpp:2899
Bimage::sizeY
void sizeY(long ny)
Definition: Bimage.h:391
Bimage::file_name
string & file_name()
Definition: Bimage.h:246
GSedge::w
float w
Definition: Bimage_segment.cpp:21
region_find
long region_find(GSregion *region, long i)
Definition: Bimage_segment.cpp:1224
Bimage::image_size
long image_size()
Definition: Bimage.h:290
region_join
int region_join(GSregion *region, long i, long j)
Definition: Bimage_segment.cpp:1232
Bimage::histogram_thresholds
int histogram_thresholds(double &tmin, double &tmax)
Calculates minimum and maximum thresholds for truncation.
Definition: Bimage_histogram.cpp:421
segment_highest_neighbor
long segment_highest_neighbor(vector< Bsuperpixel > &seg, long i, long cc)
Definition: Bimage_segment.cpp:1725
Bimage::bin_copy
Bimage * bin_copy(long b)
Definition: Bimage.h:1298
Bimage::superpixels
vector< Bsuperpixel > superpixels(long step, double colorweight=0.2, long iterations=10, double stop=1)
Segment the image into superpixels.
Definition: Bimage_segment.cpp:1872
kmax
long kmax(long i, long km, long m)
Definition: Bimage_filter.cpp:22
Bimage::truncate_to_avg
int truncate_to_avg(double minim, double maxim)
Sets voxels in image data exceeding a given minimum and maximum to the average.
Definition: Bimage_rescale.cpp:349
Bimage::region_assign
long region_assign(Bimage *pmask, long idx, long region_number, double threshold, int sign)
Finds all the pixels that are part of the same region.
Definition: Bimage_segment.cpp:119
TRGB
@ TRGB
Definition: Bimage.h:63
Bimage::graph_segment
Bimage * graph_segment(int type=1, Bimage *pmask=NULL, int connect_type=0, double complexity=0, long min_size=0, int return_type=0)
Graph-based segmentation of an image.
Definition: Bimage_segment.cpp:1443
img_impose_difference_from_highest_neighbor
int img_impose_difference_from_highest_neighbor(Bimage *p, Bimage *pmask, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1751
Bimage
General image parameter class.
Definition: Bimage.h:177
Bimage::compound_type
CompoundType compound_type()
Definition: Bimage.h:364
volume
T volume(vector< T > v)
Definition: Vector3.h:547
segment_setup_neighbors
long segment_setup_neighbors(long i, vector< Bsuperpixel > &seg, double dmax)
Definition: Bimage_segment.cpp:1766
Bimage::check_neighbors
long check_neighbors(long idx)
Check neighbors in region map and assign a value if a neighbor is assigned.
Definition: Bimage_segment.cpp:406
Bimage::kernel_max_neigbor
long kernel_max_neigbor(long idx, long ksize)
Finds the highest value in a kernel excluding the central voxel.
Definition: Bimage.cpp:2931
distance
double distance(vector< T1 > &v1, vector< T2 > &v2)
Definition: Vector3.h:538
Bimage::truncate_to_min_max
int truncate_to_min_max(double minim, double maxim)
Truncates image data to a given minimum and maximum.
Definition: Bimage_rescale.cpp:331
Bimage::data_alloc_and_clear
unsigned char * data_alloc_and_clear()
Definition: Bimage.h:272
Bimage::region_peaks
Bimage * region_peaks(long kernel_size, double threshold, int flood=0, int wrap=0)
Generates a segmented image from peaks above a threshold value.
Definition: Bimage_segment.cpp:457
GSregion::a
float a
Definition: Bimage_segment.cpp:31
Bimage::file_name
void file_name(string s)
Definition: Bimage.h:245
Bimage::data_type
DataType data_type()
Definition: Bimage.h:362
region_merge_small
long region_merge_small(GSregion *region, GSedge *edge, long nrc, long ne, int min_size)
Definition: Bimage_segment.cpp:1401
NNEIGHBOR
#define NNEIGHBOR
Definition: Bsuperpixel.h:13
utilities.h
Header file for general utilities.
tab
ostream & tab(ostream &out)
Definition: utilities.cpp:22
img_unbin_update
Bimage * img_unbin_update(Bimage *p)
Definition: Bimage_segment.cpp:1917
Integer
@ Integer
Definition: utilities.h:158
segments_setup_neighbors
long segments_setup_neighbors(vector< Bsuperpixel > &seg, long step)
Definition: Bimage_segment.cpp:1783
verbose
int verbose
GSregion
Graph segmentation region structure.
Definition: Bimage_segment.cpp:27
GSedge
Graph segmentation edge structure.
Definition: Bimage_segment.cpp:19
Bimage::impose_superpixels
int impose_superpixels(Bimage *pmask, vector< Bsuperpixel > &seg, int impose)
Impose superpixel features onto an image.
Definition: Bimage_segment.cpp:2045
region_setup
GSregion * region_setup(Bimage *p, Bimage *pmask)
Definition: Bimage_segment.cpp:1256
Bimage::origin
void origin(double ox, double oy, double oz)
Definition: Bimage.h:570
random_seed
long random_seed()
Gets a random seed and sets the flag.
Definition: random_numbers.cpp:41
statistical_region_merging
long statistical_region_merging(GSregion *region, GSedge *edge, long nr, long ne, double fac)
Definition: Bimage_segment.cpp:1374
Bimage::change_type
void change_type(char letter)
Get the data type indicated by a single letter code.
Definition: Bimage.cpp:1765
Bimage::index
long index(long nx, long ny) const
Definition: Bimage.h:396
Vector3::volume
double volume()
Definition: Vector3.h:237
rwimg.h
Header file for 2D and 3D image I/O.
Bimage::copy_header
Bimage * copy_header()
Definition: Bimage.h:658
GSedge::v
long v
Definition: Bimage_segment.cpp:20
Bimage::kernel_high
Vector3< long > kernel_high(long i, long k=1)
Definition: Bimage.h:476
Bimage::fill
void fill(double v)
Definition: Bimage.h:706
linked_list.h
Header file for generalized linked list functions.
Bimage::blobs
long blobs(double threshold, double min_size, double max_size, double setvalue, int sign)
Identifies contiguous regions above a given threshold (blobs) and eliminate those less than a minimum...
Definition: Bimage_segment.cpp:537
VERB_FULL
#define VERB_FULL
Definition: utilities.h:113
Bimage::sampling
vector< Vector3< double > > sampling()
Definition: Bimage.h:529
VERB_STATS
#define VERB_STATS
Definition: utilities.h:112
Vector3::min
Type min()
Definition: Vector3.h:169
Bimage::sampling
void sampling(long nn, Vector3< double > u)
Definition: Bimage.h:514
Bimage::tile_mask
Bimage * tile_mask(long step)
Converts a mask to a tiled multilevel mask.
Definition: Bimage_mask.cpp:1412
kmin
long kmin(long i, long hk)
Definition: Bimage_filter.cpp:17
Bimage::kernel_low
Vector3< long > kernel_low(long i, long k=1)
Definition: Bimage.h:470
img_impose_lowest_neighbor
int img_impose_lowest_neighbor(Bimage *p, Bimage *pmask, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1712
Bimage::edge
int edge(int type, Vector3< long > rect, Vector3< double > start, double width, int fill_type=0, double fill=0)
Smooths the image edge with a soft rectangular function.
Definition: Bimage_edit.cpp:321
Float
@ Float
Definition: utilities.h:161
Bimage::channels
long channels()
Definition: Bimage.h:384
Bimage::rgb
RGB< double > rgb(long j)
Returns a color value at the given index.
Definition: Bimage.cpp:1055
VERB_LABEL
#define VERB_LABEL
Definition: utilities.h:110
Bimage::superpixels_update
int superpixels_update(Bimage *pmask, vector< long > vstep, double colorweight, vector< Bsuperpixel > &seg)
Definition: Bimage_segment.cpp:1609
Bimage::statistics
long statistics()
Calculates the statistics for an image.
Definition: Bimage_stats.cpp:22
Bimage::check_if_same_size
bool check_if_same_size(Bimage *p)
Check if two images are the same size.
Definition: Bimage.cpp:566
Bimage::filter_extremes
int filter_extremes()
Filters the extremes out of a micrograph image.
Definition: Bimage_segment.cpp:620
Bimage::to_mask
long to_mask()
Definition: Bimage.h:1313
Bimage::replace_maxima
long replace_maxima(double threshold)
Replaces maxima above a threshold using local averages.
Definition: Bimage_segment.cpp:678
GSregion::s
int s
Definition: Bimage_segment.cpp:30
Vector3::max
Type max()
Definition: Vector3.h:175