Beispiel #1
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string> -o <string> --intv <int> <int> <int>",
    "[--option <string>] [--fgc] [--help]",
    NULL};

  if (help(argc, argv, Spec) == 1) {
    return 0;
  }

  Process_Arguments(argc, argv, Spec, 1);

  Stack *stack = Read_Stack_U(Get_String_Arg("input"));
  Stack *out = NULL;
  
  int option = DS_NEAREST;
  if (Is_Arg_Matched("--option")) {
    const char *arg = Get_String_Arg("--option");
    if (eqstr(arg, "max")) {
      option = DS_MAX;
    } else if (eqstr(arg, "mean")) {
      option = DS_MEAN;
    } else if (eqstr(arg, "nearest")) {
      option = DS_NEAREST;
    } else {
      printf("Invalid option: %s\n. The default option (nearest) will be used.", arg);
    }
  }

  switch (option) {
    case DS_NEAREST:
      out = Downsample_Stack(stack, Get_Int_Arg("--intv", 1), 
          Get_Int_Arg("--intv", 2), Get_Int_Arg("--intv", 3));
      break;
    case DS_MAX:
      out = Downsample_Stack_Max(stack, Get_Int_Arg("--intv", 1), 
          Get_Int_Arg("--intv", 2), Get_Int_Arg("--intv", 3), NULL);
      break;
    case DS_MEAN:
      if (Is_Arg_Matched("--fgc")) {
        out = Downsample_Stack_Mean_F(stack, Get_Int_Arg("--intv", 1), 
            Get_Int_Arg("--intv", 2), Get_Int_Arg("--intv", 3), NULL);
      } else {
        out = Downsample_Stack_Mean(stack, Get_Int_Arg("--intv", 1), 
            Get_Int_Arg("--intv", 2), Get_Int_Arg("--intv", 3), NULL);
      }
      break;
    default:
      break;
  }
      
  Write_Stack(Get_String_Arg("-o"), out);

  return 0;
}
Beispiel #2
0
/*
 * bwdist - build a distance map for a binary stack
 *
 * bwdist [-b<int>] infile -o outfile
 *
 * -i: inverse the image
 * -b: byte number for output file (1 (default) or 2)
 * -sq: build square distance map
 */
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<image:string> -o <string>",
			 "[-b<int> | -sq] [-i] [--plane]",
			 NULL};


  Process_Arguments(argc, argv, Spec, 1);

  char *image_file = Get_String_Arg("image");
  
  Stack *stack = Read_Stack(image_file);

  if (Is_Arg_Matched("-i")) {
    Stack_Not(stack, stack);
  }

  Stack *distmap = NULL;

  if (!Is_Arg_Matched("-sq")) {
    distmap = Stack_Bwdist_L(stack, NULL, NULL);
    Kill_Stack(stack);
    
    int kind = GREY;
    if (Is_Arg_Matched("-b")) {
      kind = Get_Int_Arg("-b");
    }
    
    stack = Scale_Float_Stack((float *) distmap->array, distmap->width,
			     distmap->height, distmap->depth, kind);
    Kill_Stack(distmap);
    distmap = stack;
  } else {
    if (Is_Arg_Matched("--plane")) {
      distmap = Stack_Bwdist_L_U16P(stack, NULL, 0);
      Translate_Stack(distmap, GREY, 1);
    } else {
      distmap = Stack_Bwdist_L_U16(stack, NULL, 0);
    }
    Kill_Stack(stack);
  }

  char *out_file = Get_String_Arg("-o");
  Write_Stack(out_file, distmap);

  Kill_Stack(distmap);
  
  return 1;
}
Beispiel #3
0
  ParaSet::ParaSet (int argc, char * argv[], char * specifications []) {
    
    Process_Arguments(argc,argv,specifications,1);
    
//    ProjectionMethod::ParaSet parameter;
    
    if (Is_Arg_Matched("-r")) {         // grid size
      radius = Get_Int_Arg("-r");
      if (radius %2 != 0) {           // the grid size has to be even to enable a subsequent refinement
        radius++;
      }
    } else {
      radius = 20;
    }
    
    if (Is_Arg_Matched("-d")) {         // distance parameter
      distance = Get_Int_Arg("-d");
    } else {
      distance = 2;
    }
    
    if (Is_Arg_Matched("-l")) {         // number of cell layers
      layer = Get_Int_Arg("-l");
    } else {
      layer = 1;
    }
    
    if (Is_Arg_Matched("-t")) {         // threshold for brigth pixels
      threshold = Get_Int_Arg("-t");
    } else {
      threshold = 50;
    }
    
    if (Is_Arg_Matched("-hmd")) {      // export downsampled height map
      printHeightMap = true;
    } else {
      printHeightMap = false;
    }
    
    if (Is_Arg_Matched("-hmr")) {      // export height map
      printRealHeightMap = true;
    } else {
      printRealHeightMap = false;
    }
    
    if (Is_Arg_Matched("-mi")) {      // if the signal spreads several layers, then one can project the maximal intensities of the detected surface layers and its neighboring ones
      maxInterpolation = true;
    } else {
      maxInterpolation = false;
    }
    
    if (Is_Arg_Matched("-v")) {      // verbose parameter
      verbose = true;
    } else {
      verbose = false;
    }
  };
Beispiel #4
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string> -o <string> -tile_number <int> [-upsample <string>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  char filepath[500];
  int i;
  int n = Get_Int_Arg("-tile_number");
  for (i = 0; i < n; i++) {
    sprintf(filepath, "%s/%03d", Get_String_Arg("input"), i+1);
    int n = dir_fnum(filepath, "tif");
    sprintf(filepath, "%s/%03d.xml", Get_String_Arg("-o"), i+1);
    FILE *fp = GUARDED_FOPEN(filepath, "w");
    fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    fprintf(fp, "<trace>\n");
    fprintf(fp, "<data>\n");
    fprintf(fp, "<image type=\"bundle\">\n");
    fprintf(fp, "<prefix>%s/%03d/</prefix>\n", Get_String_Arg("input"), i+1);
    fprintf(fp, "<suffix>.tif</suffix>\n");
    if (n > 100) {
      fprintf(fp, "<num_width>3</num_width>\n");
    } else {
      fprintf(fp, "<num_width>2</num_width>\n");
    }
    fprintf(fp, "<first_num>1</first_num>\n");
    fprintf(fp, "</image>\n");
    fprintf(fp, "<resolution><x>0.0375</x><y>0.0375</y><z>0.2</z></resolution>\n");
    fprintf(fp, "</data>\n");
    fprintf(fp, "</trace>\n");
    fclose(fp);
    printf("%s created\n", filepath);
  }

  if (Is_Arg_Matched("-upsample")) {
    if (fexist(Get_String_Arg("-upsample"))) {
      FILE *fp = fopen(Get_String_Arg("-upsample"), "r");
      String_Workspace *sw = New_String_Workspace();
      char *line = NULL;
      int n;
      line = Read_Line(fp, sw);
      int *array = String_To_Integer_Array(line, NULL, &n);
      int i;
      for (i = 0; i < n; i++) {
	upsample(Get_String_Arg("-o"), array[i]);
      }
      fclose(fp);
    }
  }

  return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<file:string>", "[-u <int>]", NULL};

  Process_Arguments(argc, argv, Spec, 1);

  if (!fexist(Get_String_Arg("file"))) {
    printf("%s does not exist.\n", Get_String_Arg("file"));
    return 1;
  }

  struct stat buf;

  stat(Get_String_Arg("file"), &buf);

  int file_size = buf.st_size;
  printf("file size: %d\n", file_size);

  FILE *fp = fopen(Get_String_Arg("file"), "r");

  int length;

  if (fp != NULL) {
    if (fread(&length, sizeof(int), 1, fp) != 1) {
      printf("Wrong file format.\n");
      return 1;
    } else {
      if (((file_size - sizeof(int)) % length) != 0) {
	printf("Bad array file.\n");
	return 1;
      } else {
	if (Is_Arg_Matched("-u")) {
	  int unit = Get_Int_Arg("-u");
	  if (length * unit != file_size - sizeof(int)) {
	    printf("Bad array file.\n");
	    return 1;
	  }
	}
      }
    }

    fclose(fp);
  }

  printf("%d elements (%lu)\n", length, (file_size - sizeof(int)) / length);

  return 0;
}
Beispiel #6
0
void Output_Clusters(Segmentation *segs, Overlaps *ovl, Clusters *clust)
{ Array       *stack, *proj;
  int          i, j, k;

#ifdef PROGRESS
  printf("\nGenerating %d color cluster stacks\n",clust->inum);
  fflush(stdout);
#endif

  stack = Make_Array(RGB_KIND,UINT16_TYPE,3,Images[0]->dims);
  proj  = Make_Array(RGB_KIND,UINT16_TYPE,2,Images[0]->dims);

  for (i = 0; i < clust->inum; i++)
    { Array_Op_Scalar(stack,SET_OP,UVAL,VALU(0));

      for (j = clust->ilist[i]; j < clust->ilist[i+1]; j++)
        { Array_Bundle plane;
          int item = clust->item[j];
          int chan = ovl->chans[item];
          int seg  = item - segs[chan].base;
          for (k = 0; k < NumChans; k++)
            { plane = *stack;
              Draw_Region_Image(Get_Array_Plane(&plane,k%3),
                                Images[k],segs[chan].segs[seg]);
            }
        }

      if (!Is_Arg_Matched("-pj"))
        { sprintf(NameBuf,"%s/%s.clust%d.tif",RezFolder,CoreName,i);
          Write_Image(NameBuf,stack,LZW_PRESS);
        }

#ifdef PROGRESS
      printf("*"); fflush(stdout);
#endif

      Z_Projection(stack,proj);
      sprintf(NameBuf,"%s/%s.PR.clust%d.tif",RezFolder,CoreName,i);
      Write_Image(NameBuf,proj,LZW_PRESS);
    }

  Free_Array(proj);
  Free_Array(stack);

#ifdef PROGRESS
  printf("\n"); fflush(stdout);
#endif
}
Beispiel #7
0
 ExtendedParaSet::ExtendedParaSet (int argc, char * argv[], char * specifications []) {
   
   Process_Arguments(argc,argv,specifications,1);
   
   if (Is_Arg_Matched("-r")) {         // grid size
     radius = Get_Int_Arg("-r");
     if (radius %2 != 0) {           // the grid size has to be even to enable a subsequent refinement
       radius++;
     }
   } else {
     radius = 20;
   }
   
   if (Is_Arg_Matched("-d1")) {         // distance parameter
     distance1 = Get_Int_Arg("-d1");
   } else {
     distance1 = 0;
   }
 
   if (Is_Arg_Matched("-d2")) {         // distance parameter
     distance2 = Get_Int_Arg("-d2");
   } else {
     distance2 = 0;
   }
   
   if (Is_Arg_Matched("-t")) {         // threshold for brigth pixels
     threshold = Get_Int_Arg("-t");
   } else {
     threshold = 50;
   }
   
   if (Is_Arg_Matched("-hmd")) {      // export downsampled height map
     printHeightMap = true;
   } else {
     printHeightMap = false;
   }
   
   if (Is_Arg_Matched("-hmr")) {      // export height map
     printRealHeightMap = true;
   } else {
     printRealHeightMap = false;
   }
   
   if (Is_Arg_Matched("-v")) {      // verbose parameter
     verbose = true;
   } else {
     verbose = false;
   }
 };
Beispiel #8
0
void Output_Neurons(int numneur, Region **neurons, int do_brighten)
{ Array  *stack, *proj;
  int     i, k;

#ifdef PROGRESS
  printf("\nGenerating %d individual neuron stacks\n",numneur);
  fflush(stdout);
#endif

  stack = Make_Array(RGB_KIND,UINT16_TYPE,3,Images[0]->dims);
  proj  = Make_Array(RGB_KIND,UINT16_TYPE,2,Images[0]->dims);

  for (i = 0; i < numneur; i++)
    { Array_Op_Scalar(stack,SET_OP,UVAL,VALU(0));

      for (k = 0; k < NumChans; k++)
        { Array_Bundle plane = *stack;
          Draw_Region_Image(Get_Array_Plane(&plane,k%3),Images[k],neurons[i]);
        }

      if (do_brighten)
        Scale_Array_To_Range(stack,VALU(0),VALU(4095));

      if (!Is_Arg_Matched("-pj"))
        { sprintf(NameBuf,"%s/%s.neuron%d.tif",RezFolder,CoreName,i);
          Write_Image(NameBuf,stack,LZW_PRESS);
        }

#ifdef PROGRESS
      printf("*"); fflush(stdout);
#endif

      Z_Projection(stack,proj);
      sprintf(NameBuf,"%s/%s.PR.neuron%d.tif",RezFolder,CoreName,i);
      Write_Image(NameBuf,proj,LZW_PRESS);
    }

  // Kill_Array(proj); these are causing a glib.c memory error in Linux
  // Kill_Array(stack);

#ifdef PROGRESS
  printf("\n"); fflush(stdout);
#endif
}
Beispiel #9
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string> -o <string> [--dim <string>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  if (Is_Arg_Matched("--dim")) {
    if (strcmp(Get_String_Arg("--dim"), "x") == 0 || 
        strcmp(Get_String_Arg("--dim"), "X") == 0) {
      Stack *stack = Read_Stack(Get_String_Arg("input"));
      Image *image = Proj_Stack_Xmax(stack);
      Write_Image(Get_String_Arg("-o"), image);
    }
  } else {
    Mc_Stack *stack = Read_Mc_Stack(Get_String_Arg("input"), -1);
    Mc_Stack *proj = Mc_Stack_Mip(stack);

    Write_Mc_Stack(Get_String_Arg("-o"), proj, NULL);
  }
  return 0;
}
Beispiel #10
0
int main(int argc, char *argv[])
{ Stack *movie, *out;
  FILE  *fp;
  int    i,j,iPlane,depth;
  int   area;

  Process_Arguments(argc,argv,Spec,0);

  progress("Loading...\n"); fflush(stdout);
  movie = load(Get_String_Arg("movie"));
  if( Is_Arg_Matched("-t") )
  { Stack *tmovie = transpose_copy_uint8( movie );
    Free_Stack(movie);
    movie = tmovie;
  }
  progress("Done.\n");

  Write_Stack( Get_String_Arg("output"), movie );

  Free_Stack( movie );
  return 0;
}
Beispiel #11
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<image:string> -s <int> -o <string>",
			 "[-n <int>]",
			 NULL};

  Process_Arguments(argc, argv, Spec, 1);
  
  Stack *stack = Read_Stack(Get_String_Arg("image"));
  
  int n_nbr = 26;
  if (Is_Arg_Matched("-n")) {
    n_nbr = Get_Int_Arg("-n");
  }

  Stack_Label_Large_Objects_N(stack, NULL, 1, 2, Get_Int_Arg("-s") + 1, n_nbr);
  
  Stack_Threshold_Binarize(stack, 2);
  
  Write_Stack(Get_String_Arg("-o"), stack);

  return 0;
}
Beispiel #12
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[<number:string> | -a <num1:string> <num2:string>]", 
			 NULL};
  Process_Arguments(argc, argv, Spec, 1);

  if (Is_Arg_Matched("-a")) {
    char *numstr1 = Get_String_Arg("num1");
    char *numstr2 = Get_String_Arg("num2");
    uint32_t num1;
    uint32_t num2;
    if (numstr1[0] == 'x') {
      num1 = Hexstr_To_Uint(numstr1 + 1);
    } else {
      num1 = atoi(numstr1);
    }
    if (numstr2[0] == 'x') {
      num2 = Hexstr_To_Uint(numstr2 + 1);
    } else {
      num2 = atoi(numstr2);
    }
    
    char str[12];
    printf("%s\n", Uint_To_Hexstr(num1 + num2, str));
  } else {
    char *numstr = Get_String_Arg("number");
    if (numstr[0] == 'x') {
      printf("%u\n", Hexstr_To_Uint(numstr + 1));
    } else {
      char str[12];
      printf("%s\n", Uint_To_Hexstr(atoi(numstr), str));
    }
  }

  return 0;
}
Beispiel #13
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-t]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  if (Is_Arg_Matched("-t")) {
    /* Example test */
    Stack *stack = Make_Stack(GREY, 7, 7, 1);
    One_Stack(stack);
    Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
    ws->conn = 26;
    ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			  Stack_Depth(stack));
    Zero_Stack(ws->mask);

    /* set seeds */
    Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
    Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
    Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
    Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
    Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

    /* set stack values */
    Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
    Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
    
    Stack *out = Stack_Watershed(stack, ws);

    //Write_Stack("../data/test/watershed/golden/watershed1.tif", out);

    char *golden_file = "../data/test/watershed/golden/watershed1.tif";
    if (fexist(golden_file)) {
      Stack *golden = Read_Stack(golden_file);
      if (Stack_Identical(out, golden) == FALSE) {
	Print_Stack_Value(stack);
	Print_Stack_Value(out);
	Print_Stack_Value(golden);
	PRINT_EXCEPTION("Bug?", "Conflict with golden.");
	return 1;
      }

      Kill_Stack(stack);
      Kill_Stack(out);
      Kill_Stack(golden);
      Kill_Stack_Watershed_Workspace(ws);
    } else {
      printf("%s cannot be found.\n", golden_file);
    }

    char *test_file = "../data/benchmark/rice_label.tif";
    if (fexist(test_file)) {
      stack = Read_Stack_U(test_file);

      ws = Make_Stack_Watershed_Workspace(stack);
      ws->mask = Copy_Stack(stack);
      ws->conn = 26;
      One_Stack(stack);

      out = Stack_Watershed(stack, ws);

      //Write_Stack("../data/test/watershed/golden/watershed2.tif", out);

      Stack *golden = Read_Stack("../data/test/watershed/golden/watershed2.tif");
      if (Stack_Identical(out, golden) == FALSE) {
	PRINT_EXCEPTION("Bug?", "Conflict with golden.");
	return 1;
      }
    } else {
      printf("%s cannot be found.\n", test_file);
    }

    printf(":) Testing passed.\n");

    return 0;
  }

#if 0
  /* Initialize */
  Watershed_3d *watershed = New_Watershed_3d();
  Watershed_3d_Workspace *ws = New_Watershed_3d_Workspace();
  ws->conn = 26;

  /* Initialize stack */
  Stack *stack = Read_Stack("../data/fly_neuron/dist.tif");
  int nvoxel = Stack_Voxel_Number(stack);
  int i;
  uint16 *array16 = (uint16 *)stack->array;
  for (i = 0; i < nvoxel; i++) {
    array16[i] = 0xFFFF - array16[i];
  }
  
  /* Add mask to ignore dark voxels  */
  ws->mask = Copy_Stack(stack); 
  

  //Translate_Stack(stack, GREY, 1);

  //stack->array = stack->array + stack->width * stack->height * 100;
  //stack->depth = 1;
  // ws->mask = Copy_Stack(stack);
  //Stack_Binarize(ws->mask);
  // ws->mask = NULL;

  //Write_Stack("../data/dist.tif", stack);


  //Stack *stack2 = Copy_Stack(stack);


#  if 0
  Build_3D_Watershed(stack, watershed, ws);
  Write_Stack("../data/test.tif", watershed->labels);
#  endif

#  if 0
  
  Image_View iv = Image_View_Stack(stack2);
  Watershed_Test *watershed2 = Build_2D_Watershed_Test(&(iv.image), 0);
  Write_Image("../data/test2.tif", watershed2->labels);
#  endif
#endif

#if 0
  Image *image = Read_Image("../data/Ring15.tif_Sub1200_Original_inv.tif");
  Watershed_2D *ws = Build_2D_Watershed(image, 0);
  Image *result = Color_Watersheds(ws, image);
  Write_Image("../data/test.tif", result);
  Kill_Image(image);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 7, 7, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
  Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
  Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

  Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
  
  Stack *out = Stack_Watershed(stack, ws);

  Print_Stack_Value(out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 3, 3, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);

  Set_Stack_Pixel(ws->mask, 0, 0, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 2, 2, 0, 0, 2.0);

  Set_Stack_Pixel(stack, 0, 0, 0, 0, 5.0);
  Set_Stack_Pixel(stack, 2, 2, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 0, 2, 0, 0, 2.0);
  //Set_Stack_Pixel(stack, 1, 1, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 1, 2, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 2, 0, 0, 0, 2.0);
  Set_Stack_Pixel(stack, 2, 1, 0, 0, 2.0);

  Print_Stack_Value(stack);

  ws->start_level = 6;

  Stack *out = Stack_Watershed(stack, ws);

  Print_Stack_Value(out);
#endif
 
#if 0
  Stack *stack = Read_Stack_U("../data/benchmark/rice_label.tif");

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Copy_Stack(stack);
  ws->conn = 26;
  One_Stack(stack);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());

  Write_Stack("../data/test.tif", out); 
#endif

#if 0
  Stack *stack = Read_Stack_U("../data/diadem_d1_147.xml");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  ws->conn = 26;

  const int *dx = Stack_Neighbor_X_Offset(ws->conn);
  const int *dy = Stack_Neighbor_X_Offset(ws->conn);
  const int *dz = Stack_Neighbor_X_Offset(ws->conn);
  
  int seed[3];
  String_Workspace *sw = New_String_Workspace();
  char *line = NULL;
  FILE *fp = fopen("../data/diadem_d1_root_z.txt", "r");
  int k = 1;
    
  while ((line = Read_Line(fp, sw)) != NULL) {
    int n;
    String_To_Integer_Array(line, seed, &n);
    double maxv = -1;
    if (n == 3) {
      maxv = Get_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0);
      printf("%g\n", maxv);
      int i;
      for (i = 0; i < ws->conn; i++) {
	if (maxv < Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				   seed[2] + dz[i], 0)) {
	  maxv = Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				 seed[2] + dz[i], 0);
	}
      }

      //Set_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0, maxv);
      Set_Stack_Pixel(ws->mask, seed[0], seed[1], seed[2], 0, k);
      for (i = 0; i < ws->conn; i++) {
	//Set_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
	//		seed[2] + dz[i], 0, maxv);
	Set_Stack_Pixel(ws->mask, seed[0] + dx[i], seed[1] + dy[i], 
			seed[2] + dz[i], 0, k);	
      }
      k++;
    }
  }
  fclose(fp);
  Kill_String_Workspace(sw);
  
  /*
  Set_Stack_Pixel(ws->mask, 19, 605, 112, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 28, 565, 112, 0, 1.0);
  */
  Stack_Watershed_Infer_Parameter(stack, ws);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());

  Write_Stack("../data/diadem_d1_147_label.tif", out);

  static const uint8 Color_Map[][3] = { 
    {0, 0, 0},
    {0, 224, 64}, {32, 64, 128}, {64, 64, 0}, {64, 128, 64},
    {96, 64, 128}, {64, 0, 0}, {128, 200, 64}, {160, 128, 128},
    {192, 0, 0}, {192, 160, 64}, {224, 64, 128}, {224, 224, 192}};
  
  Translate_Stack(out, COLOR, 1);
  size_t nvoxel = Stack_Voxel_Number(out);
  size_t i;
  color_t *arrayc = (color_t*) out->array;
  for (i = 0; i < nvoxel; i++) {
    arrayc[i][2] = Color_Map[arrayc[i][0]][2];
    arrayc[i][1] = Color_Map[arrayc[i][0]][1];
    arrayc[i][0] = Color_Map[arrayc[i][0]][0];
  }

  Write_Stack("../data/diadem_d1_147_paint.tif", out);
#endif

#if 0
  Stack *stack = Read_Stack_U("../data/diadem_d1_146.xml");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  Stack *mask = Read_Stack("../data/test3.tif");
  ws->mask = Crop_Stack(mask, 252, -937, 2, 1024, 1024, 63, NULL);
  ws->conn = 26;

  Stack_Watershed_Infer_Parameter(stack, ws);

  tic();
  Stack *out = Stack_Watershed(stack, ws);
  printf("%lld\n", toc());
  
  Write_Stack("../data/test2.tif", out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 7, 7, 1);
  One_Stack(stack);
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);
  Set_Stack_Pixel(ws->mask, 1, 1, 0, 0, 1.0);
  Set_Stack_Pixel(ws->mask, 1, 5, 0, 0, 2.0);
  Set_Stack_Pixel(ws->mask, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(ws->mask, 5, 1, 0, 0, 4.0);
  Set_Stack_Pixel(ws->mask, 5, 5, 0, 0, 5.0);

  Set_Stack_Pixel(stack, 1, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 1, 5, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 3, 3, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 1, 0, 0, 3.0);
  Set_Stack_Pixel(stack, 5, 5, 0, 0, 3.0);
  
  Stack *out = Stack_Watershed(stack, ws);
  Print_Stack_Value(out);

  Stack *out2 = Stack_Region_Border_Shrink(out, ws);
  
  Print_Stack_Value(out2);

#endif

#if 0
  Stack *stack = Read_Stack("../data/diadem_d1_013_label.tif");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  //ws->conn = 26;

  Stack *out = Stack_Region_Border_Shrink(stack, ws);
  Write_Stack("../data/test.tif", out);
#endif

#if 0
  Stack *stack = Make_Stack(GREY, 1, 1, 19);
  One_Stack(stack);
  
  stack->array[3] = 5;
  stack->array[4] = 5;
  stack->array[7] = 5;
  stack->array[8] = 5;
  stack->array[10] = 4;
  stack->array[11] = 5;
  stack->array[12] = 5;
  stack->array[13] = 4;
  stack->array[16] = 5;
  stack->array[17] = 5;

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			Stack_Depth(stack));
  Zero_Stack(ws->mask);

  
  Print_Stack_Value(stack);
  Stack_Watershed_Zgap_Barrier(stack, ws->mask);
  Print_Stack_Value(ws->mask);
#endif

#if 0
  Stack *stack = Read_Stack("../data/diadem_d1_047_label.tif");
  Stack_Binarize(stack);

  Stack *stack2 = Stack_Bwdist_L_U16(stack, NULL, 0);
  Write_Stack("../data/test.tif", stack2);  
#endif

#if 0
  char stack_path[100];
  char mask_path[100];

  strcpy(stack_path, "../data/diadem_d1_064.xml");

  strcpy(mask_path, stack_path);
  strsplit(mask_path, '.', -1);
  sprintf(mask_path, "%s_label.tif", mask_path);

  if (!fexist(stack_path)) {
    fprintf(stderr, "Cannot find %s\n", stack_path);
    return 1;
  }
  
  printf("Processing %s\n", stack_path);
  Stack *stack = Read_Stack_U(stack_path);
  Stack *mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
			   Stack_Depth(stack));
  Zero_Stack(mask);

  int conn = 26;
  const int *dx = Stack_Neighbor_X_Offset(conn);
  const int *dy = Stack_Neighbor_X_Offset(conn);
  const int *dz = Stack_Neighbor_X_Offset(conn);
  
  int seed[3];
  String_Workspace *sw = New_String_Workspace();
  char *line = NULL;
  FILE *fp = fopen("../data/064.seeds.txt", "r");
  int k = 1;

  /* label seeds */
  while ((line = Read_Line(fp, sw)) != NULL) {
    int n;
    String_To_Integer_Array(line, seed, &n);
    double maxv = -1;
    if (n == 3) {
      maxv = Get_Stack_Pixel(stack, seed[0], seed[1], seed[2], 0);
      int i;
      for (i = 0; i < conn; i++) {
	if (maxv < Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				   seed[2] + dz[i], 0)) {
	  maxv = Get_Stack_Pixel(stack, seed[0] + dx[i], seed[1] + dy[i], 
				 seed[2] + dz[i], 0);
	}
      }
      
      Set_Stack_Pixel(mask, seed[0], seed[1], seed[2], 0, k);
      for (i = 0; i < conn; i++) {
	Set_Stack_Pixel(mask, seed[0] + dx[i], seed[1] + dy[i], 
			seed[2] + dz[i], 0, k);	
      }
      k++;
    }
  }
  fclose(fp);
  Kill_String_Workspace(sw);

  Stack_Running_Median(stack, 0, stack);
  Stack_Running_Median(stack, 1, stack);
    
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = mask;
    
  Filter_3d *filter = Gaussian_Filter_3d(2.0, 2.0, 1.5);
  Stack *filtered_stack  = Filter_Stack(stack, filter);
  Stack_Watershed_Zgap_Barrier(filtered_stack, ws->mask);
  Stack_Running_Max(ws->mask, 0, ws->mask);
  Stack_Running_Max(ws->mask, 1, ws->mask);
  //Write_Stack("../data/test.tif", ws->mask);
    
  Kill_Stack(filtered_stack);
  filtered_stack = NULL;

    
  FMatrix *dm = Mexihat_3D1_F(2.0, NULL, 2);
  //FMatrix *dm = Mexihat_3D_F(2.0, NULL);
  FMatrix_Negative(dm);

  filtered_stack = Filter_Stack(stack, dm);
  
  Stack_Threshold_Common(filtered_stack, 0, 65535);
  Stack_Binarize(filtered_stack);
  Translate_Stack(filtered_stack, GREY, 1);
    
    
  {
    int i, j, k;
    int offset = 0;
    uint16 *array = (uint16*) stack->array;
    for (k = 0; k < stack->depth; k++) {
      for (j = 0; j < stack->height; j++) {
	for (i = 0; i < stack->width; i++) {
	  if (filtered_stack != NULL) {
	    if (filtered_stack->array[offset] == 1) {
	      ws->mask->array[offset] = STACK_WATERSHED_BARRIER;
	    }
	  }
	  array[offset++] += k * 2;
	}
      }
    }
  }

  Kill_Stack(filtered_stack);
  
  Stack_Watershed_Infer_Parameter(stack, ws);
  ws->conn = 6;

  double weights[26] = {0.5, 0.5, 1.0, 1.0, 0.2, 0.2, 0.75, 0.75, 0.75, 0.75,
			0.35, 0.35, 0.35, 0.35, 0.6, 0.6, 0.6, 0.6, 
			0.45, 0.45, 0.45, 0.45,
			0.45, 0.45, 0.45, 0.45};

  ws->weights = weights;
  ws->weights = NULL;
  
  if (ws->weights != NULL) {
    ws->min_level /= 3;
  }
    
  Stack_Running_Median(stack, 0, stack);
  Stack_Running_Median(stack, 1, stack);
  
  Stack *out = Stack_Watershed(stack, ws);
  
  strcpy(mask_path, stack_path);
  strsplit(mask_path, '.', -1);
  sprintf(mask_path, "%s_label.tif", mask_path);
  
  Write_Stack("../data/test.tif", out);

#endif

#if 0
  Stack *stack = Read_Stack("../data/test/soma2.tif");

  int thre = Stack_Find_Threshold_A(stack, THRESHOLD_LOCMAX_TRIANGLE);
  Filter_3d *filter = Gaussian_Filter_3d(1.0, 1.0, 0.5);
  Stack *out = Filter_Stack(stack, filter);
  stack = Copy_Stack(out);
  Stack_Threshold_Binarize(out, thre);
  Stack *out2 = Stack_Bwdist_L_U16P(out, NULL, 0);
  int nvoxel = Stack_Voxel_Number(out);
  uint16_t *dist_array = (uint16_t*) out2->array;
  int i;
  for (i = 0; i < nvoxel; i++) {
    dist_array[i] = sqrt(dist_array[i]);
  }

  Write_Stack("../data/labmeeting13/distp.tif", out2);
#endif

#if 0
  //Stack *stack = Read_Stack("../data/test/soma2.tif");

  Stack *stack = Read_Stack("/Users/zhaot/Data/jinny/slice7_2to34ds_soma_c2.tif");
  int thre = Stack_Find_Threshold_A(stack, THRESHOLD_LOCMAX_TRIANGLE);
  Filter_3d *filter = Gaussian_Filter_3d(1.0, 1.0, 0.5);
  Stack *out = Filter_Stack(stack, filter);
  stack = Copy_Stack(out);
  Stack_Threshold_Binarize(out, thre);
  Stack *out2 = Stack_Bwdist_L_U16P(out, NULL, 0);

  /*
  out = Stack_Locmax_Region(out2, 26);
  */
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack),
      Stack_Depth(stack));
  Zero_Stack(ws->mask);
  size_t nvoxel = Stack_Voxel_Number(stack);
  size_t offset;
  uint16_t *dist_array = (uint16_t*) out2->array;
  for (offset = 0; offset < nvoxel; offset++) {
    if (/*(out->array[offset] == 1) && */(dist_array[offset] > 1000)) {
      ws->mask->array[offset] = 1;
    }
  }

  //Objlabel_Workspace *ow = New_Objlabel_Workspace();
  //Stack_Label_Large_Objects_W(ws->mask, 1, 2, 10, ow);
  //Stack_Label_Objects_N(ws->mask, NULL, 1, 2, 26);
  Object_3d_List *objs = Stack_Find_Object(ws->mask, 1, 100);
  Zero_Stack(ws->mask);
  Stack_Draw_Objects_Bw(ws->mask, objs, -255);
  printf("%g\n", Stack_Max(ws->mask, NULL));

  /*
  Write_Stack("../data/test.tif", ws->mask);
  return 1;
*/

  ws->min_level = thre;
  ws->start_level = 65535;

  Stack *out3 = Stack_Watershed(stack, ws);
  /*
  Write_Stack("../data/labmeeting13/watershed.tif", out3);
  return 1;
*/
  for (offset = 0; offset < nvoxel; offset++) {
    if (dist_array[offset] < 300) {
      out3->array[offset] = 0;
    }
  }

  int nregion = Stack_Max(out3, NULL);

  Kill_Stack(out2);
  Stack *filtered = Copy_Stack(stack);
  Kill_Stack(stack);
  
  ws->conn = 8;
  stack = Stack_Region_Border_Shrink(out3, ws);
  out2 = Stack_Region_Expand(stack, 4, 30, NULL);

  for (offset = 0; offset < nvoxel; offset++) {
    if (out->array[offset] == 0) {
      out2->array[offset] = 0;
    }
  }

  Write_Stack("../data/test2.tif", out2);

  Kill_Stack(stack);
  //stack = Read_Stack("../data/test/soma2.tif");
  stack = Read_Stack("/Users/zhaot/Data/jinny/slice7_2to34ds_soma_c2.tif");
  Translate_Stack(stack, COLOR, 1);
  int i;
  double h = 0.0;
  double s = 1.0;
  for (i = 0; i < nregion; i++) {
    Stack_Label_Color_L(stack, out2, i+1, h+=0.35, s, filtered);
    /*
    Rgb_Color color;
    Set_Color_Jet(&color, i*3);
    Stack_Label_Level(stack, out2, i+1, color);
    */
  }
  Write_Stack("../data/test.tif", stack);
#endif

#if 0
  Stack *stack = Read_Stack("../data/leaktest/leak3.tif");
  Stack *distmap = Stack_Bwdist_L_U16P(stack, NULL, 0);

  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->mask = Copy_Stack(distmap);
  Stack_Threshold_Binarize(ws->mask, 10);
  Translate_Stack(ws->mask, GREY, 1);
  Object_3d_List *objs = Stack_Find_Object(ws->mask, 1, 100);
  Zero_Stack(ws->mask);
  Stack_Draw_Objects_Bw(ws->mask, objs, -255);

  ws->min_level = 1;
  ws->start_level = 65535;
  Stack *out3 = Stack_Watershed(distmap, ws);
  Write_Stack("../data/test.tif", out3);

#endif

#if 0
  Stack *stack = Read_Stack("../data/benchmark/two_disk.tif");
  Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
  ws->conn = 26;
  Stack *out = Stack_Watershed(stack, ws);

  Write_Stack("../data/test.tif", out);
#endif
  return 0;
}
Beispiel #14
0
int main(int argc, char *argv[])
{

  static char *Spec[] = {"<dataset:string> | -D <string>", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  char file_path[100];
  if (Is_Arg_Matched("-D")) {
    sprintf(file_path, "%s/error.xml", Get_String_Arg("-D"));
  } else {
    sprintf(file_path, "../data/diadem_%s/error.xml",
	    Get_String_Arg("dataset"));
  }

  xmlDocPtr doc;
  xmlNodePtr cur;

  doc = xmlParseFile(file_path);
  if (doc == NULL) {
    fprintf(stderr, "XML parsing failed.\n");
    return 1;
  }

  cur = xmlDocGetRootElement(doc);
  if (cur == NULL) {
    fprintf(stderr, "empty document\n");
    xmlFreeDoc(doc);
    return 1;
  }

  if (xmlStrcmp(cur->name, (const xmlChar*) "diadem_metric")) {
    fprintf(stderr, "document of wrong type\n");
    xmlFreeDoc(doc);
    return 1;
  }

  cur = cur->xmlChildrenNode;
  char *miss_file = NULL;
  char *golden_file = NULL;
  char *extra_file = NULL;
  char *nearby_file = NULL;
  char *test_file = NULL;
  char *miss_swc_file = NULL;
  char *extra_swc_file = NULL;
  char *nearby_swc_file = NULL;
  char *miss_vlm_file = NULL;
  char *extra_vlm_file = NULL;
  char *nearby_vlm_file = NULL;
  char *miss_score_file = NULL;
  char *extra_score_file = NULL;

  double EuDistThre_xy = 0.0;
  double EuDistThre_z = 0.0;
  double score;

  while (cur != NULL) {
    if (Xml_Node_Is_Element(cur, "miss") == TRUE) {
      miss_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "extra") == TRUE) {
      extra_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "score") == TRUE) {
      score = Xml_Node_Double_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "golden") == TRUE) {
      golden_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "nearby") == TRUE) {
      nearby_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "test") == TRUE) {
      test_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "miss_swc") == TRUE) {
      miss_swc_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "extra_swc") == TRUE) {
      extra_swc_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "nearby_swc") == TRUE) {
      nearby_swc_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "miss_vlm") == TRUE) {
      miss_vlm_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "extra_vlm") == TRUE) {
      extra_vlm_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "nearby_vlm") == TRUE) {
      nearby_vlm_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "miss_score") == TRUE) {
      miss_score_file = Xml_Node_String_Value(doc, cur);
    } else if (Xml_Node_Is_Element(cur, "extra_score") == TRUE) {
      extra_score_file = Xml_Node_String_Value(doc, cur);
    }else if(Xml_Node_Is_Element(cur, "xyth") == TRUE) {
      EuDistThre_xy = Xml_Node_Double_Value(doc, cur);
    }else if(Xml_Node_Is_Element(cur, "zth") == TRUE) {
      EuDistThre_z = Xml_Node_Double_Value(doc, cur);
    }

    cur = cur->next;
  }

  if ((EuDistThre_xy <= 0.0) || (EuDistThre_z <= 0.0)) {
    fprintf(stderr, "Invalid threshold value\n");
    xmlFreeDoc(doc);
    return 1;
  }

  Swc_Tree *tree = Read_Swc_Tree(golden_file);

  double bound[6];
  Swc_Tree_Bound_Box(tree, bound);
  double marker_ratio = dmax3(bound[3] - bound[0], bound[4] - bound[1],
			      bound[5] - bound[2]) / 512.0;

  Geo3d_Scalar_Field *miss_field = read_node_file(miss_file);
  printf("The missed nodes:\n");
  Print_Geo3d_Scalar_Field(miss_field);

  Geo3d_Scalar_Field *extra_field = read_node_file(extra_file);
  printf("The extra nodes:\n");
  Print_Geo3d_Scalar_Field(extra_field);

  Geo3d_Scalar_Field *nearby_field = read_node_file(nearby_file);
  //    Print_Geo3d_Scalar_Field(nearby_field);

  double wm = darray_sum(miss_field->values, miss_field->size);
  double we = darray_sum(extra_field->values, extra_field->size);
  double wg = round((score * we + wm) / (1 - score));

  //    printf("%g %g %g\n", wm, we, wg);

  Swc_Tree_Iterator_Start(tree, 2, FALSE);
  int max_id = 0;
  Swc_Tree_Node *tn = NULL;
  while ((tn = Swc_Tree_Next(tree)) != NULL) {
    Swc_Tree_Node_Data(tn)->type = 3;
    if (max_id < Swc_Tree_Node_Data(tn)->id) {
      max_id = Swc_Tree_Node_Data(tn)->id;
    }
  }

  uint8 *nearby_mask = u8array_calloc(max_id + 1);

  /* process nearby nodes */
  FILE *fp = NULL;
  FILE *fp3 = NULL;

  if (nearby_swc_file != NULL) {
    fp = fopen(nearby_swc_file, "w");
  }

  if (nearby_vlm_file != NULL) {
    fp3 = fopen(nearby_vlm_file, "w");
  }

  //    printf("Nearby list\n");
  int i;
  for (i = 0; i < nearby_field->size; i++) {
    Swc_Tree_Node *tn = Swc_Tree_Closest_Node(tree, nearby_field->points[i]);

    nearby_mask[Swc_Tree_Node_Data(tn)->id] = 1;

    double w = (1.0+3.0/(1+exp(-(nearby_field->values[i]*2.0-2.0))))
      * marker_ratio;

    if (fp != NULL) {
      fprintf(fp, "%d %d %g %g %g %g %d\n", i + 1, 7,
	      Swc_Tree_Node_Data(tn)->x,
	      Swc_Tree_Node_Data(tn)->y, Swc_Tree_Node_Data(tn)->z,w, -1);
    }

    if (fp3 != NULL) {
      fprintf(fp3, "%g,%g,%g,%g,1,%g\n", Swc_Tree_Node_Data(tn)->x,
	      Swc_Tree_Node_Data(tn)->y, Swc_Tree_Node_Data(tn)->z,
	      w, nearby_field->values[i]);
    }
  }
  if (fp != NULL) {
    fclose(fp);
  }
  if (fp3 != NULL) {
    fclose(fp3);
  }

  /* process missing nodes */
  fp = NULL;
  FILE *fp2 = fopen(miss_score_file, "w");
  fp3 = NULL;

  if (miss_swc_file != NULL) {
    fp = fopen(miss_swc_file, "w");
  }

  if (miss_vlm_file != NULL) {
    fp3 = fopen(miss_vlm_file, "w");
  }

  Swc_Tree *test_tree = Read_Swc_Tree(test_file);

  //    printf("Missing list\n");
  int n_leaves = 0;
  int n_branchings = 0;
  int n_leaves_distance = 0;
  int n_leaves_path = 0;
  int n_branchings_distance = 0;
  int n_branchings_path = 0;

  double score_leaves = 0.0;
  double score_branchings = 0.0;
  double score_leaves_distance = 0.0;
  double score_leaves_path = 0.0;
  double score_branching_distance = 0.0;
  double score_branching_path = 0.0;

  BOOL error_type; // 'true' indicates distance-error, 'false' indicates path-error

  for (i = 0; i < miss_field->size; i++) {
    Swc_Tree_Node *tn = Swc_Tree_Closest_Node(tree, miss_field->points[i]);
    double cur_score = miss_field->values[i] / (wg + we);
    fprintf(fp2, "%4d | %5.2f %5.2f %5.2f | %g | %g\n", Swc_Tree_Node_Data(tn)->id,
	    Swc_Tree_Node_Data(tn)->x, Swc_Tree_Node_Data(tn)->y,
	    Swc_Tree_Node_Data(tn)->z, miss_field->values[i],
	    cur_score);

    Swc_Tree_Node_Data(tn)->type = 2;

    double w = (1.0+3.0/(1+exp(-(miss_field->values[i]*2.0-2.0))))
      * marker_ratio;

    if (fp != NULL) {
      int type = 0;
      if (nearby_mask[Swc_Tree_Node_Data(tn)->id] == 1) {
	type = 1;
      }
      fprintf(fp, "%d %d %g %g %g %g %d\n", i + 1, type,
	      Swc_Tree_Node_Data(tn)->x,
	      Swc_Tree_Node_Data(tn)->y, Swc_Tree_Node_Data(tn)->z, w, -1);
    }

    if (fp3 != NULL) {
      double xy_dist, z_dist;
      Swc_Tree_Node *test_tn;
      double pos[3];
      Swc_Tree_Node_Pos(tn, pos);
      if(Swc_Tree_Node_Is_Branch_Point(tn))
	test_tn = Find_Closest_Branch_Point(test_tree, pos, &xy_dist, &z_dist);
      else
	test_tn = Find_Closest_Leaf_Point(test_tree, pos, &xy_dist, &z_dist);

      if(xy_dist >= EuDistThre_xy || z_dist >= EuDistThre_z){
	fprintf(fp3, "%g,%g,%g,%g,1,%g,[xy-%g z-%g | distance_error], 255, 255, 0\n",Swc_Tree_Node_Data(tn)->x + 1.0,
		Swc_Tree_Node_Data(tn)->y + 1.0, Swc_Tree_Node_Data(tn)->z + 1.0,
		w, miss_field->values[i], xy_dist, z_dist);
	error_type = TRUE;
      }else{
	fprintf(fp3, "%g,%g,%g,%g,1,%g,[xy-%g z-%g | path_error], 255, 0, 255\n",Swc_Tree_Node_Data(tn)->x + 1.0,
		Swc_Tree_Node_Data(tn)->y + 1.0, Swc_Tree_Node_Data(tn)->z + 1.0,
		w, miss_field->values[i], xy_dist, z_dist);
	error_type = FALSE;
      }
    }

    if(miss_field->values[i]==1){
      n_leaves ++;
      score_leaves += cur_score;
      if(error_type){ // distance error
	n_leaves_distance ++;
	score_leaves_distance += cur_score;
      }else{
	n_leaves_path ++;
	score_leaves_path += cur_score;
      }
    }else{
      n_branchings ++;
      score_branchings += cur_score;
      if(error_type){ // distance error
	n_branchings_distance ++;
	score_branching_distance += cur_score;
      }else{
	n_branchings_path ++;
	score_branching_path += cur_score;
      }
    }
  }

  if(fp2 != NULL){
    fprintf(fp2, "\nleaf errors:  \t %d | loss score: %g(%2.1f%%)\n", n_leaves, score_leaves, 100*score_leaves/(1 - score));
    fprintf(fp2, "leaf errors (dist): %d | loss score: %g(%2.1f%%) \n", n_leaves_distance, score_leaves_distance, 100*score_leaves_distance/(1 - score));
    fprintf(fp2, "leaf errors (path): %d | loss score: %g(%2.1f%%) \n", n_leaves_path, score_leaves_path, 100*score_leaves_path/(1 - score));
    fprintf(fp2, "\nbranching errors: \t %d | score loss: %g(%2.1f%%) \n", n_branchings, score_branchings, 100*score_branchings/(1 - score));
    fprintf(fp2, "branching error (dist):  %d | score loss: %g(%2.1f%%) \n", n_branchings_distance, score_branching_distance, 100*score_branching_distance/(1 - score));
    fprintf(fp2, "branching error (path):  %d | score loss: %g(%2.1f%%) \n", n_branchings_path, score_branching_path, 100*score_branching_path/(1 - score));
  }
  if (fp != NULL) {
    fclose(fp);
  }
  fclose(fp2);
  if (fp3 != NULL) {
    fclose(fp3);
  }

  /*
    sprintf(file_path, "../data/diadem_%s/error.swc", Get_String_Arg("dataset"));
    Write_Swc_Tree(file_path, tree);
  */

  tree = test_tree;

  /* process extra nodes*/
  fp = NULL;
  fp2 = fopen(extra_score_file, "w");
  fp3 = NULL;

  if (extra_swc_file != NULL) {
    fp = fopen(extra_swc_file, "w");
  }

  if (extra_vlm_file != NULL) {
    fp3 = fopen(extra_vlm_file, "w");
  }

  //    printf("Extra list\n");
  n_leaves = 0;
  n_branchings = 0;

  score_leaves = 0.0;
  score_branchings = 0.0;


  for (i = 0; i < extra_field->size; i++) {
    Swc_Tree_Node *tn = Swc_Tree_Closest_Node(tree, extra_field->points[i]);
    double cur_score = extra_field->values[i] * (wg - wm) / (wg + we) / (wg + we - extra_field->values[i]);

    fprintf(fp2, "%4d | %5.2f %5.2f %5.2f | %g | %g\n", Swc_Tree_Node_Data(tn)->id,
	    Swc_Tree_Node_Data(tn)->x, Swc_Tree_Node_Data(tn)->y,
	    Swc_Tree_Node_Data(tn)->z, extra_field->values[i], cur_score);

    double w = (1.0+3.0/(1+exp(-(extra_field->values[i]*2.0-2.0))))
      * marker_ratio;

    if (fp != NULL) {
      fprintf(fp, "%d %d %g %g %g %g %d\n", i + 1, 1,
	      Swc_Tree_Node_Data(tn)->x,
	      Swc_Tree_Node_Data(tn)->y, Swc_Tree_Node_Data(tn)->z, w, -1);
    }

    if (fp3 != NULL) {
      fprintf(fp3, "%g,%g,%g,%g,1,%g, error, 255, 255, 0\n", Swc_Tree_Node_Data(tn)->x + 1.0,
	      Swc_Tree_Node_Data(tn)->y + 1.0, Swc_Tree_Node_Data(tn)->z + 1.0,
	      w, extra_field->values[i]);
    }

    if(extra_field->values[i]==1){
      n_leaves ++;
      score_leaves += cur_score;
    }else{
      n_branchings ++;
      score_branchings += cur_score;
    }
  }

  if(fp2 != NULL){
    fprintf(fp2, "\nleaf errors:   %d | loss score: %g(%2.1f%%)\n", n_leaves, score_leaves, 100*score_leaves/(1 - score));
    fprintf(fp2, "branching errors:  %d | score loss: %g(%2.1f%%) \n", n_branchings, score_branchings, 100*score_branchings/(1 - score));
  }

  if (fp != NULL) {
    fclose(fp);
  }
  fclose(fp2);
  if (fp3 != NULL) {
    fclose(fp3);
  }

  xmlFreeDoc(doc);

  printf("Score = %g\n", score);

  return 0;
}
Beispiel #15
0
int main(int argc, char* argv[])
{ int n_rows, count;
  Measurements *table,*cursor;
  double thresh,
         px2mm,
         low_px,
         high_px;
  int face_x, face_y;
  int follicle_thresh = 0,
      follicle_col = 4,
      follicle_high;
  int n_cursor;

  Process_Arguments( argc, argv, Spec, 0);

  if( Is_Arg_Matched("-h") | Is_Arg_Matched("--help") )
  { Print_Argument_Usage(stdout,0);
    printf("--------------------------                                                   \n"
          " Classify 4 (radius filter)                                                   \n"
          "---------------------------                                                   \n"
          "                                                                              \n"
          "  Uses a length threshold to seperate hair/microvibrissae from main whiskers. \n"
          "  Then, for frames where the expected number of whiskers are found,           \n"
          "  label the whiskers according to their order on the face.                    \n"
          "\n"
          "  This version of classify filters out curves where the follicle side falls \n"
          "  outside of a circle centered at the face position with the radius specified \n"
          "  by the --follicle option."
          "\n"
          "  <source> Filename with Measurements table.\n"
          "  <dest>   Filename to which labelled Measurements will be saved.\n"
          "           This can be the same as <source>.\n"
          "  <faceX> <faceY> <faceAxis>\n"
          "           These are used for determining the order of whisker segments along \n"
          "           the face.  This requires an approximate position for the center of \n"
          "           the face and can be specified in pixel coordinates with <x> and <y>.\n"
          "           <axis> indicates the orientaiton of the face.  Values for <axis> may\n"
          "           be 'x' or 'h' for horizontal. 'y' or 'v' indicate a vertical face. \n"
          "           If the face is located along the edge of the frame then specify    \n"
          "           that edge with 'left', 'right', 'top' or 'bottom'.                 \n"
          "  --px2mm <double>\n"
          "           The length of a pixel in millimeters.  This is used to determine   \n"
          "           appropriate thresholds for discriminating hairs from whiskers.     \n"
          "  -n <int> (Optional) Optimize the threshold to find this number of whiskers. \n"
          "           If this isn't specified, or if this is set to a number less than 1 \n"
          "           then the number of whiskers is automatically determined.           \n"
          "  --follicle <int>\n"
          "           Only count follicles that lie inside a circle with this radius in  \n"
          "           (in pixels) and centered at the face position as whiskers.         \n"
          "--                                                                            \n");
    return 0;
  }

  px2mm   = Get_Double_Arg("--px2mm");
  low_px  = Get_Double_Arg("--limit",1) / px2mm;
  high_px = Get_Double_Arg("--limit",2) / px2mm;
#ifdef DEBUG_CLASSIFY_4
  debug("mm/px %f\n"
        "  low %f\n"
        " high %f\n", px2mm, low_px, high_px );
#endif

  table  = Measurements_Table_From_Filename ( Get_String_Arg("source"), NULL, &n_rows );
  if(!table) error("Couldn't read %s\n",Get_String_Arg("source"));
  Sort_Measurements_Table_Time(table,n_rows);

  { int maxx,maxy;
    const char *axis = Get_String_Arg("faceAxis");
    static const int x = 4,
                     y = 5;
    Measurements_Table_Pixel_Support( table, n_rows, &maxx, &maxy );
    face_x = Get_Int_Arg("faceX");
    face_y = Get_Int_Arg("faceY");
    follicle_thresh = 0;       // set defaults
    if( Is_Arg_Matched("--follicle") && Get_Int_Arg("--follicle")>0 )
    { follicle_thresh = Get_Int_Arg("--follicle");
      switch( axis[0] )        // respond to <follicle> option
      { case 'x':              // follicle must be between threshold and face
        case 'h':
        case 'y':
        case 'v':
          break;
        default:
          error("Could not recognize <axis>.  Must be 'x','h','y', or 'v'.  Got %s\n",axis);
      }
    }
  }
  // Follicle location threshold
  if( Is_Arg_Matched("--follicle") && Get_Int_Arg("--follicle")>0 )
    follicle_thresh = Get_Int_Arg("--follicle");
    //inline void Measurements_Table_Label_By_RadialThreshold( Measurements *table, int n_rows, double thresh, int ox, int oy, int colx, int coly)
  Measurements_Table_Label_By_RadialThreshold( table,
                                               n_rows,
                                               follicle_thresh,
                                               face_x,
                                               face_y,
                                               follicle_col,
                                               follicle_col+1);

#ifdef DEBUG_CLASSIFY_4
  debug("   Face Position: ( %3d, %3d )\n", face_x, face_y);
#endif
  // Shuffle to select subset with good follicles
  Sort_Measurements_Table_State_Time( table, n_rows );
  { cursor = table;
    while( (cursor->state == 0) && (cursor < table+n_rows ) )
      cursor++;
    n_cursor = n_rows - (cursor-table);
  }
  Sort_Measurements_Table_Time(cursor,n_cursor); //resort selected by time

#ifdef DEBUG_CLASSIFY_1
  { Measurements *row = cursor + n_cursor; //Assert all state==1
    while(row-- > cursor)
      assert(row->state == 1);
 }
#endif
  //
  // Estimate best length threshold and apply
  //
  if( Is_Arg_Matched("-n") && ( (count = Get_Int_Arg("-n"))>=1 ) )
  { thresh = Measurements_Table_Estimate_Best_Threshold_For_Known_Count( cursor, //table, 
                                                                         n_cursor, //n_rows, 
                                                                         0 /*length column*/, 
                                                                         low_px, 
                                                                         high_px, 
                                                                         1, /*use > */
                                                                         count );
  } else 
  { thresh = Measurements_Table_Estimate_Best_Threshold( cursor, //table, 
                                                         n_cursor, //n_rows, 
                                                         0 /*length column*/, 
                                                         low_px, 
                                                         high_px,
                                                         1, /* use > */
                                                         &count );
  }
  /*
  Measurements_Table_Label_By_Threshold    ( cursor,
                                             n_cursor,
                                             follicle_col,
                                             follicle_thresh,
                                             is_gt);
  */
  Measurements_Table_Label_By_RadialThreshold( table,
                                               n_rows,
                                               follicle_thresh,
                                               face_x,
                                               face_y,
                                               follicle_col,
                                               follicle_col+1);
#ifdef DEBUG_CLASSIFY_4
  { Measurements *row = cursor + n_cursor; //Assert all state==1
    while(row-- > cursor)
      assert(row->state == 1);
  }
#endif
  Measurements_Table_Label_By_Threshold_And ( cursor,
                                              n_cursor,
                                              0 /*length column*/, 
                                              thresh,
                                              1 /*use gt*/);
  
#ifdef DEBUG_CLASSIFY_4
  debug("   Length threshold: %f\n"
        "       Target count: %d\n",
        thresh,count); 
#endif

  Measurements_Table_Set_Constant_Face_Position     ( table, n_rows, face_x, face_y);
  Measurements_Table_Set_Follicle_Position_Indices  ( table, n_rows, 4, 5 );

  Measurements_Table_Label_By_Order(table, n_rows, count ); //re-sorts

  Measurements_Table_To_Filename( Get_String_Arg("dest"), NULL, table, n_rows );
  Free_Measurements_Table(table);
  return 0;
}
Beispiel #16
0
int main(int argc, char *argv[])
{ FILE *output;

  Process_Arguments(argc,argv,Spec,0);

#ifdef PROGRESS
  printf("\nParameters: c=%g e=%g s=%d\n",
         Get_Double_Arg("-c"),Get_Double_Arg("-e"),Get_Int_Arg("-s"));
  printf("SubFolder:  %s\n",Get_String_Arg("folder"));
  printf("CoreName:   %s\n",Get_String_Arg("core"));
  fflush(stdout);
#endif

  RezFolder = strdup(Get_String_Arg("folder"));
  if (RezFolder[strlen(RezFolder)-1] == '/')
    RezFolder[strlen(RezFolder)-1] = '\0';

  if (mkdir(RezFolder,S_IRWXU|S_IRWXG|S_IRWXO))
    { if (errno != EEXIST)
        { fprintf(stderr,"Error trying to create directory %s: %s\n",RezFolder,strerror(errno)); 
          exit (1);
        }
    }

  CoreName = strdup(Get_String_Arg("core"));

  sprintf(NameBuf,"%s.neu",CoreName);
  output = fopen(NameBuf,"w");
  fprintf(output,"NEUSEP: Version 0.9\n");

  { Histogram *hist;
    int        curchan;
    int        maxchans;
    int        i, n;

    n = Get_Repeat_Count("inputs");
    fwrite(&n,sizeof(int),1,output);

    hist = Make_Histogram(UVAL,0x10000,VALU(1),VALU(0));

    maxchans = 0;
    for (i = 0; i < n; i++)
      { 
	curchan  = NumChans;
        maxchans = Read_All_Channels(Get_String_Arg("inputs",i),maxchans);
	int channelsInCurrentFile=NumChans-curchan;


        { Size_Type sum, max;
          Indx_Type p;
          int       j, wch;
          uint16   *val;

          max = -1;
          for (j = curchan; j < NumChans; j++)
            { val = AUINT16(Images[j]);
              sum = 0;
              for (p = 0; p < Images[j]->size; p++)
                sum += val[p];
              if (sum > max)
                { max = sum;
                  wch = j;
                }
            }

          fprintf(output,"%s\n",Get_String_Arg("inputs",i));
          j = wch-curchan;
          fwrite(&j,sizeof(int),1,output);

#ifdef PROGRESS
          printf("\n  Eliminating channel %d from %s\n",j+1,Get_String_Arg("inputs",i));
          fflush(stdout);
#endif

	  {
	    // Section to write out the reference channel
	    printf("\n Considering reference channel output, channelsInCurrentFile=%d\n", channelsInCurrentFile);
	    fflush(stdout);
	    if (channelsInCurrentFile>2) { // should work with both lsm pair with channels=3, or raw file with channels=4
	      sprintf(NameBuf,"%s/Reference.tif",RezFolder,CoreName,i);
	      Write_Image(NameBuf,Images[wch],LZW_PRESS);
	    }

	  }

          Free_Array(Images[wch]);
          NumChans -= 1;
          for (j = wch; j < NumChans; j++)
            Images[j] = Images[j+1];
        }

        { int        j, ceil;
          Indx_Type  p;
          uint16    *val;

          for (j = curchan; j < NumChans; j++)
            {
              Histagain_Array(hist,Images[j],0);

              ceil = Percentile2Bin(hist,1e-5);

	      if (ceil==0) {
		fprintf(stderr, "Channel must have non-zero values for this program to function\n");
		exit(1);
	      } 

#ifdef PROGRESS
              printf("  Clipping channel %d at ceil = %d\n",j,ceil); fflush(stdout);
              fflush(stdout);
#endif
    
              val  = AUINT16(Images[j]);
              for (p = 0; p < Images[j]->size; p++)
                { 
		  if (val[p] > ceil)
		    val[p] = ceil;
		  val[p] = (val[p]*4095)/ceil;
		  }
	      //              Convert_Array_Inplace(Images[j],PLAIN_KIND,UINT8_TYPE,8,0);
            }
    
        }
      }

    Free_Histogram(hist);

    printf("Starting ConsolidatedSignal.tif section\n");
    fflush(stdout);

    // NA addition: write tif with re-scaled intensities to serve as basis for mask file
    {
      Array *signalStack;
      signalStack = Make_Array(RGB_KIND,UINT8_TYPE,3,Images[0]->dims);
      uint8 *sp=AUINT8(signalStack);
      int m;
      Indx_Type signalIndex;
      signalIndex=0;
      for (m=0;m<NumChans;m++) {
	sprintf(NameBuf, "%s/Signal_%d.tif", RezFolder, m);
	printf("Writing 16-bit channel file %s...", NameBuf);
	Write_Image(NameBuf, Images[m], LZW_PRESS);
	printf("done\n");
	uint16 *ip=AUINT16(Images[m]);
	Indx_Type  channelIndex;
	for (channelIndex=0;channelIndex<Images[m]->size;channelIndex++) {
	  int value=ip[channelIndex]/16;
	  if (value>255) {
	    value=255;
	  }
	  sp[signalIndex++]=value; // convert 12-bit to 8-bit
	}
      }
      sprintf(NameBuf,"%s/ConsolidatedSignal.tif", RezFolder);
      printf("Writing 8-bit consolidated signal file %s...", NameBuf);
      Write_Image(NameBuf,signalStack,LZW_PRESS);
      printf("done");
      //Free_Array(signalStack); - this is causing a bug
    }

    printf("Finished ConsolidatedSignal.tif section\n");
    fflush(stdout);

  }

  { int           i;
    Segmentation *segs;
    Overlaps     *ovl;
    Clusters     *clust;
    int           numneur;
    Region      **neurons;

    segs = (Segmentation *) Guarded_Malloc(sizeof(Segmentation)*NumChans,Program_Name());

    for (i = 0; i < NumChans; i++)
      { Segment_Channel(Images[i],segs+i);
        if (i == 0)
          segs[i].base = 0;
        else
          segs[i].base = segs[i-1].base + segs[i-1].nsegs;
	printf("channel=%d segmentBase=%d\n", i, segs[i].base);
      }

    ovl     = Find_Overlaps(segs);
    clust   = Merge_Segments(segs,ovl);
    neurons = Segment_Clusters(segs,ovl,clust,&numneur);

    if (Is_Arg_Matched("-gp"))
      Output_Clusters(segs,ovl,clust);
    if (Is_Arg_Matched("-nr"))
      Output_Neurons(numneur,neurons,1);

    // Added for NA
    Output_Consolidated_Mask(numneur,neurons,1);

    fwrite(&numneur,sizeof(int),1,output);
    for (i = 0; i < numneur; i++)
      Write_Region(neurons[i],output);

#ifdef PROGRESS
    printf("\nProduced %d neurons/fragments in %s.neu\n",numneur,CoreName);
    fflush(stdout);
#endif

    printf("DEBUG: starting cleanup\n");
    fflush(stdout);

    for (i = 0; i < numneur; i++) {
      printf("DEBUG: calling Kill_Region on neuron=%d\n", i);
      fflush(stdout);
      Kill_Region(neurons[i]);
    }
    printf("DEBUG: calling Kill_Clusters\n");
    fflush(stdout);
    Kill_Clusters(clust);
    printf("DEBUG: calling Kill_Overlaps\n");
    fflush(stdout);
    //Kill_Overlaps(ovl); - causing a bug
    printf("DEBUG: starting Kill_Segmentation loop\n");
    fflush(stdout);
    for (i = 0; i < NumChans; i++) {
      printf("DEBUG: Kill_Segmentation on index=%d\n", i);
      fflush(stdout);
      Kill_Segmentation(segs+i);
    }
    printf("DEBUG: calling free() on segs\n");
    fflush(stdout);
    free(segs);
  }

  printf("DEBUG: starting filestream cleanup\n");
  fflush(stdout);

  { int i;

    fclose(output);
    free(CoreName);
    free(RezFolder);
    for (i = 0; i < NumChans; i++)
      Kill_Array(Images[i]);
    free(Images);
  }

#ifdef VERBOSE
  printf("\nDid I free all arrays?:\n"); 
  Print_Inuse_List(stdout,4);
#endif

  exit (0);
}
bool ZArgumentProcessor::isArgMatched(const char *arg)
{
  return Is_Arg_Matched(const_cast<char*>(arg));
}
Beispiel #18
0
int main(int argc, char *argv[])
{
  if (Show_Version(argc, argv, "1.0") == 1) {
    return 0;
  }

  static char *Spec[] = {
    "[-R<string> -T<string> -M<string>] -D<string> [-minlen <double>]",
    "[-root <double> <double> <double>] [-trans <double> <double> <double>]",
    "[-rtlist <string>] [-sup_root] [-dist <double>]",
    "[-C<string>] [-I<string>] [-z <double>] -o <string> [-b] [-res <string>]",
    "[-screen] [-sp] [-intp] [-sl] [-rb] [-rz] [-rs] [-ct] [-al <double>]",
    "[-screenz <double>] [-force_merge <double>] [-ct_break <double>]",
    "[-jumpz <double>] [-single_break]",
    NULL};

  Print_Arguments(argc, argv);

  Process_Arguments(argc, argv, Spec, 1);
  
  char *dir = Get_String_Arg("-D");

  Stack_Document *stack_doc = NULL;
  if (Is_Arg_Matched("-I")) {
    if (!fexist(Get_String_Arg("-I"))) {
      PRINT_EXCEPTION("File does not exist", "");
      fprintf(stderr, "%s cannot be found.\n", Get_String_Arg("-I"));
      return 1;
    }
    if (fhasext(Get_String_Arg("-I"), "xml")) {
      stack_doc = Xml_Read_Stack_Document(Get_String_Arg("-I"));
    }
  }

  /* Get number of chains */
  int chain_number2 = dir_fnum_p(dir, "^chain.*\\.tb");

  if (chain_number2 == 0) {
    printf("No tube found.\n");
    printf("Quit reconstruction.\n");
    return 1;
  }

  int i;
  int *chain_map = iarray_malloc(chain_number2);
  int chain_number;
  Locseg_Chain **chain_array =
    Dir_Locseg_Chain_Nd(dir, "chain.*\\.tb", &chain_number, chain_map);

  if (Is_Arg_Matched("-screenz")) {
    Locseg_Chain_Array_Screen_Z(chain_array, chain_number,
	Get_Double_Arg("-screenz"));
  }

  if (Is_Arg_Matched("-single_break")) {
    int i;
    for (i = 0; i < chain_number; i++) {
      if (Locseg_Chain_Length(chain_array[i]) == 1) {
	/* break the segment into two parts */
	Locseg_Chain_Break_Node(chain_array[i], 0, 0.5);
      }
    }
  }

  if (Is_Arg_Matched("-ct_break")) {
    int tmp_chain_number;
    Locseg_Chain **tmp_chain_array = 
      Locseg_Chain_Array_Break_Jump(chain_array, chain_number,
	  Get_Double_Arg("-ct_break"), &tmp_chain_number);
    kill_locseg_chain_array(chain_array, chain_number);
    chain_array = tmp_chain_array;
    chain_number = tmp_chain_number;
  }

  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();
  if (Is_Arg_Matched("-res")) {
    FILE *fp = fopen(Get_String_Arg("-res"), "r");
    if (fp != NULL) {
      if (darray_fscanf(fp, ctw->resolution, 3) != 3) {
	fprintf(stderr, "Failed to load %s\n", Get_String_Arg("-res"));
	ctw->resolution[0] = 1.0;
	ctw->resolution[1] = 1.0;
	ctw->resolution[2] = 1.0;
      } else {
	ctw->unit = 'u';
      }
      fclose(fp);
    } else {
      fprintf(stderr, "Failed to load %s. The file may not exist.\n", 
	      Get_String_Arg("-res"));
    }
  } else if (stack_doc != NULL) {
    ctw->resolution[0] = stack_doc->resolution[0];
    ctw->resolution[1] = stack_doc->resolution[1];
    ctw->resolution[2] = stack_doc->resolution[2];
  }

  if (Is_Arg_Matched("-force_merge")) {
    Connection_Test_Workspace *ws = New_Connection_Test_Workspace();
    ws->dist_thre = Get_Double_Arg("-force_merge");
    ws->interpolate = FALSE;
    ws->resolution[2] = ctw->resolution[2] / ctw->resolution[0];
    for (i = 0; i < chain_number; i++) {
      //Locseg_Chain_Correct_Ends(chain_array[i]); 
    }
    Locseg_Chain_Array_Force_Merge(chain_array, chain_number, ws); 
    Kill_Connection_Test_Workspace(ws);
  }

  chain_number2 = 0;
  Neuron_Component *chain_array2;
  GUARDED_MALLOC_ARRAY(chain_array2, chain_number, Neuron_Component); 
  for (i = 0; i < chain_number; i++) {
    if (Locseg_Chain_Is_Empty(chain_array[i]) == FALSE) {
      chain_map[chain_number2] = chain_map[i];
      Set_Neuron_Component(chain_array2+(chain_number2++), 
	  NEUROCOMP_TYPE_LOCSEG_CHAIN, chain_array[i]);
    } else {
      printf("chain_%d is empty.\n", chain_map[i]);
    }
  }
    /*
    Dir_Locseg_Chain_Nc(dir, "^chain.*\\.tb", &chain_number2, chain_map);
*/
  Stack *signal = NULL;
  //Stack *canvas = NULL;
  if (Is_Arg_Matched("-I")) {
    signal = Read_Stack_U(Get_String_Arg("-I"));
    //canvas = Translate_Stack(signal, COLOR, 0);
  } else {
    if (Is_Arg_Matched("-screen")) {
      perror("The -screen option requires -I option to be supplied.\n");
      return 1;
    }
  }

  /* Minimal tube length. */
  double minlen = 25.0;
  if (Is_Arg_Matched("-minlen")) {
    minlen = Get_Double_Arg("-minlen");
  }

  chain_number = 0;
  //int i;


  if (signal != NULL) {
    ctw->mask = Make_Stack(GREY, signal->width, signal->height, signal->depth);
    One_Stack(ctw->mask);
  }

  FILE *result_file = fopen(full_path(dir, Get_String_Arg("-o")), "w");


  double z_scale = 1.0;
  if (Is_Arg_Matched("-z")) {
    z_scale = Get_Double_Arg("-z");
  }


  /* Array to store corrected chains */
  Neuron_Component *chain_array_c = Make_Neuron_Component_Array(chain_number2);

  int screen = 0;

  double average_intensity = 0.0;

  if (Is_Arg_Matched("-screen")) {
    int good_chain_number = 0;
    int bad_chain_number = 0;
    for (i = 0; i < chain_number2; i++) {
      Locseg_Chain *chain = NEUROCOMP_LOCSEG_CHAIN(chain_array2 + i);

      average_intensity += Locseg_Chain_Average_Score(chain, signal, z_scale, 
						      STACK_FIT_MEAN_SIGNAL);

      if ((Locseg_Chain_Geolen(chain) > 55) || 
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF) > 0.6)) {
	good_chain_number++;
      } else {
	bad_chain_number++;
      }
    }
    
    printf("good %d bad %d\n", good_chain_number, bad_chain_number);

    if (good_chain_number + bad_chain_number > 50) {
      if (bad_chain_number > good_chain_number) {
	screen = 1;
      }
    } else {
      screen = 3;
      /*
      if (bad_chain_number > good_chain_number * 2) {
	screen = 2;
      }
      */
    }
  }

  average_intensity /= chain_number2;

  /* build chain map */
  for (i = 0; i < chain_number2; i++) {
    Locseg_Chain *chain = NEUROCOMP_LOCSEG_CHAIN(chain_array2 + i);
    BOOL good = FALSE;
    
    switch (screen) {
    case 1:
    case 2:
      if ((Locseg_Chain_Geolen(chain) > 100) || 
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF)
	   > 0.6)) {
	good = TRUE;
      } else {
	if (Locseg_Chain_Geolen(chain) < 100) {
	  if ((Locseg_Chain_Average_Score(chain, signal, z_scale, 
					 STACK_FIT_CORRCOEF) > 0.5) ||
	      (Locseg_Chain_Average_Score(chain, signal, z_scale, 
					  STACK_FIT_MEAN_SIGNAL) > 
	       average_intensity)) {
	    good = TRUE;
	  }
	}
      }
      break;
    case 3:
      if ((Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_CORRCOEF) > 0.50) ||
	  (Locseg_Chain_Average_Score(chain, signal, z_scale, 
				      STACK_FIT_MEAN_SIGNAL) > 
	   average_intensity)) {
	good = TRUE;
      }
      break;
    default:
      good = TRUE;
    }

    if (good == TRUE) {
      if (Locseg_Chain_Geolen(chain) < minlen) {
	good = FALSE;
      }
    }

    if (good == TRUE) {
      Locseg_Chain *tmpchain = chain;
      if (signal != NULL) {
	//Locseg_Chain_Trace_Np(signal, 1.0, tmpchain, tw);
	Locseg_Chain_Erase(chain, ctw->mask, 1.0);
      }
      fprintf(result_file, "%d %d\n", chain_number, chain_map[i]);
      chain_map[chain_number] = chain_map[i];
      if (z_scale != 1.0) {
	Locseg_Chain_Scale_Z(chain, z_scale);
      }
      Set_Neuron_Component(chain_array_c + chain_number, 
			   NEUROCOMP_TYPE_LOCSEG_CHAIN, tmpchain);
      chain_number++;
    } else {
#ifdef _DEBUG_
      printf("chain%d is excluded.\n", i);
      /*
      char tmpfile[500];
      sprintf(tmpfile, "../data/diadem_c1/bad_chain/chain%d.tb", i);
      Write_Locseg_Chain(tmpfile, chain);
      */
#endif
    }
  }

  z_scale = 1.0;

  fprintf(result_file, "#\n");

  //Int_Arraylist *hit_spots = Int_Arraylist_New(0, chain_number);
  /* reconstruct neuron */

  if (Is_Arg_Matched("-res")) {
    FILE *fp = fopen(Get_String_Arg("-res"), "r");
    if (fp != NULL) {
      if (darray_fscanf(fp, ctw->resolution, 3) != 3) {
	fprintf(stderr, "Failed to load %s\n", Get_String_Arg("-res"));
	ctw->resolution[0] = 1.0;
	ctw->resolution[1] = 1.0;
	ctw->resolution[2] = 1.0;
      } else {
	ctw->unit = 'u';
      }
      fclose(fp);
    } else {
      fprintf(stderr, "Failed to load %s. The file may not exist.\n", 
	      Get_String_Arg("-res"));
    }
  } else if (stack_doc != NULL) {
    ctw->resolution[0] = stack_doc->resolution[0];
    ctw->resolution[1] = stack_doc->resolution[1];
    ctw->resolution[2] = stack_doc->resolution[2];
  }

  if (!Is_Arg_Matched("-sp")) {
    ctw->sp_test = FALSE;
    if (ctw->sp_test == FALSE) {
      ctw->dist_thre = NEUROSEG_DEFAULT_H / 2.0;
    }
  } else {
    ctw->dist_thre = NEUROSEG_DEFAULT_H * 1.5;
  }
  
  if (Is_Arg_Matched("-dist")) {
    ctw->dist_thre = Get_Double_Arg("-dist");
  }

  if (!Is_Arg_Matched("-intp")) {
    ctw->interpolate = FALSE;
  }
  //ctw->dist_thre = 100.0;

  double *tube_offset = NULL;
  if (Is_Arg_Matched("-trans")) {
    tube_offset = darray_malloc(3);
    tube_offset[0] = Get_Double_Arg("-trans", 1);
    tube_offset[1] = Get_Double_Arg("-trans", 2);
    tube_offset[2] = Get_Double_Arg("-trans", 3);
  } else {
    if (stack_doc != NULL) {
      tube_offset = darray_malloc(3);
      tube_offset[0] = stack_doc->offset[0];
      tube_offset[1] = stack_doc->offset[1];
      tube_offset[2] = stack_doc->offset[2];
    }
  }

  Neuron_Structure *ns = New_Neuron_Structure();
  ns->comp = chain_array_c;
  ns->graph = New_Graph();
  ns->graph->nvertex = chain_number;
  
  if (Is_Arg_Matched("-rtlist")) {
    int m, n;
    double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);

    if (n > 0) {
      coordinate_3d_t *roots = GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
      int i;
      for (i = 0; i < n; i++) {
	if (Is_Arg_Matched("-trans")) {
	  roots[i][0] = d[i*3] - tube_offset[0];
	  roots[i][1] = d[i*3 + 1] - tube_offset[1];
	  roots[i][2] = d[i*3 + 2] - tube_offset[2];
	} else {
	  roots[i][0] = d[i*3];
	  roots[i][1] = d[i*3 + 1];
	  roots[i][2] = d[i*3 + 2];
	}
      }

      Neuron_Structure_Break_Root(ns, roots, n);
      Neuron_Structure_Load_Root(ns, roots, n);
    }
  }
  
  Locseg_Chain_Comp_Neurostruct_W(ns, signal, z_scale, ctw);

  if (tube_offset != NULL) {
    for (i = 0; i < chain_number; i++) {
      Locseg_Chain_Translate(NEUROCOMP_LOCSEG_CHAIN(chain_array_c + i), 
			     tube_offset);
    }
  }

  /*  
  Neuron_Structure *ns = Locseg_Chain_Comp_Neurostruct(chain_array, 
						       chain_number,
						       signal, z_scale, ctw);
  */

  FILE *tube_fp = fopen(full_path(dir, "tube.swc"), "w");
  int start_id = 1;

  for (i = 0; i < chain_number; i++) {
    int node_type = i % 10;
    int n = Locseg_Chain_Swc_Fprint_T(tube_fp, 
				      NEUROCOMP_LOCSEG_CHAIN(chain_array_c + i), 
				      node_type, start_id, 
				      -1, DL_FORWARD, 1.0, NULL);
    start_id += n;
  }
  fclose(tube_fp);

  //Neuron_Structure_To_Swc_File(ns, full_path(dir, "tube.swc"));
  /*
  Graph *testgraph = New_Graph(0, 0, FALSE);
  Int_Arraylist *cidx = Make_Int_Arraylist(0, 2);
  Int_Arraylist *sidx = Make_Int_Arraylist(0, 2);
  
  Locseg_Chain_Network_Simlify(&net, testgraph, cidx, sidx);
  */

  /* Find branch points */
  //Locseg_Chain *branches = Locseg_Chain_Network_Find_Branch(ns);

  //Graph *graph = Locseg_Chain_Graph(chain_array, chain_number, hit_spots);
  //Graph *graph = ns->graph;

  if (Is_Arg_Matched("-sup_root")) {
    if (Is_Arg_Matched("-rtlist")) {
      int m, n;
      double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);
      
      if (n > 0) {
	coordinate_3d_t *roots = 
	  GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
	int i;
	for (i = 0; i < n; i++) {
	  roots[i][0] = d[i*3];
	  roots[i][1] = d[i*3 + 1];
	  roots[i][2] = d[i*3 + 2];
	  /*
	  if (tube_offset != NULL) {
	    roots[i][0] += tube_offset[0];
	    roots[i][1] += tube_offset[1];
	    roots[i][2] += tube_offset[2];
	  }
	  */
	}
	neuron_structure_suppress(ns, roots, n);
	free(roots);
      }
    }
  }

  Process_Neuron_Structure(ns);

  Print_Neuron_Structure(ns);

#ifdef _DEBUG_
  for (i = 0; i < NEURON_STRUCTURE_LINK_NUMBER(ns); i++) {
    printf("chain_%d (%d) -- chain_%d (%d) ", 
	chain_map[ns->graph->edges[i][0]], 
	ns->graph->edges[i][0], 
	chain_map[ns->graph->edges[i][1]],
	ns->graph->edges[i][1]);
    Print_Neurocomp_Conn(ns->conn + i);
  }
#endif

  if (Is_Arg_Matched("-ct")) {
    Neuron_Structure_Crossover_Test(ns, 
				    ctw->resolution[0] / ctw->resolution[2]);
  }

  if (Is_Arg_Matched("-al")) {
    Neuron_Structure_Adjust_Link(ns, Get_Double_Arg("-al"));
  }

  Neuron_Structure_To_Tree(ns);
  Neuron_Structure_Remove_Negative_Conn(ns);

#ifdef _DEBUG_
  printf("\nTree:\n");
  for (i = 0; i < NEURON_STRUCTURE_LINK_NUMBER(ns); i++) {
    printf("chain_%d (%d) -- chain_%d (%d) ", 
	chain_map[ns->graph->edges[i][0]], 
	ns->graph->edges[i][0], 
	chain_map[ns->graph->edges[i][1]],
	ns->graph->edges[i][1]);
    Print_Neurocomp_Conn(ns->conn + i);
  }
#endif
  /*
  printf("\ncross over changed: \n");
  Print_Neuron_Structure(ns);
  */

#ifdef _DEBUG_2
  ns->graph->nedge = 0;
  Neuron_Structure_To_Swc_File(ns, "../data/test.swc"); 
  return 1;
#endif
  
  //Print_Neuron_Structure(ns);

  
  Neuron_Structure* ns2= NULL;
  
  if (Is_Arg_Matched("-intp")) {
    ns2 = Neuron_Structure_Locseg_Chain_To_Circle_S(ns, 1.0, 1.0);
  } else {
    ns2 = Neuron_Structure_Locseg_Chain_To_Circle(ns);
  }
    
  /*
  Neuron_Structure* ns2=
    Neuron_Structure_Locseg_Chain_To_Circle_S(ns, 1.0, 1.0);
  */
  Graph_To_Dot_File(ns2->graph, full_path(dir, "graph_d.dot"));

  //Neuron_Structure_Main_Graph(ns2);
  Neuron_Structure_To_Tree(ns2);
  
  double root[3];

  if (Is_Arg_Matched("-root")) {
    root[0] = Get_Double_Arg("-root", 1);
    root[1] = Get_Double_Arg("-root", 2);
    root[2] = Get_Double_Arg("-root", 3);
  }

  Swc_Tree *tree = NULL;

  if (Is_Arg_Matched("-root")) {
    /*
    int root_index = Neuron_Structure_Find_Root_Circle(ns2, root);
    Graph_Workspace *gw2 = New_Graph_Workspace();
    Graph_Clean_Root(ns2->graph, root_index, gw2);

    Neuron_Structure_To_Swc_File_Circle_Z(ns2, full_path(dir, "graph_d.swc"),
					  z_scale, root);
    */
    tree = Neuron_Structure_To_Swc_Tree_Circle_Z(ns2, z_scale, root);
    if (Swc_Tree_Node_Is_Virtual(tree->root) == TRUE) {
      tree->root->first_child->next_sibling = NULL;
    }
    Swc_Tree_Clean_Root(tree);
  } else {
    /*
    Neuron_Structure_To_Swc_File_Circle_Z(ns2, full_path(dir, "graph_d.swc"),
					  z_scale, NULL);
    */
    tree = Neuron_Structure_To_Swc_Tree_Circle_Z(ns2, z_scale, NULL);
  }

  ns->graph->nedge = 0;
  //Neuron_Structure_To_Swc_File(ns, full_path(dir, "tube.swc"));


  if (Is_Arg_Matched("-rb")) {
    //Swc_Tree_Tune_Branch(tree);
    Swc_Tree_Tune_Fork(tree);
  }

  if (Is_Arg_Matched("-sl")) {
    Swc_Tree_Leaf_Shrink(tree);
  }

  if (Is_Arg_Matched("-rz")) {
    Swc_Tree_Remove_Zigzag(tree);
  }

  if (Is_Arg_Matched("-rs")) {
    Swc_Tree_Remove_Spur(tree);
  }
  
  Swc_Tree_Resort_Id(tree);

  Write_Swc_Tree(full_path(dir, "graph_d.swc"), tree);

  if (Is_Arg_Matched("-rtlist")) {
    int m, n;
    double *d = darray_load_matrix(Get_String_Arg("-rtlist"), NULL, &m, &n);

    if (n > 0) {
      coordinate_3d_t *roots = GUARDED_MALLOC_ARRAY(roots, n, coordinate_3d_t);
      int i;
      for (i = 0; i < n; i++) {
	roots[i][0] = d[i*3];
	roots[i][1] = d[i*3 + 1];
	roots[i][2] = d[i*3 + 2];

	/*
	if (tube_offset != NULL) {
	  roots[i][0] += tube_offset[0];
	  roots[i][1] += tube_offset[1];
	  roots[i][2] += tube_offset[2];
	}
	*/

	Swc_Tree *subtree = Swc_Tree_Pull_R(tree, roots[i]);
	char filename[MAX_PATH_LENGTH];
	if (subtree->root != NULL) {
	  //Swc_Tree_Clean_Root(subtree);
	  Swc_Tree_Clean_Root(subtree);
	  Swc_Tree_Node_Set_Pos(subtree->root, roots[i]);
	  if (Is_Arg_Matched("-jumpz")) {
	    //swc_tree_remove_zjump(subtree, Get_Double_Arg("-jumpz"));
	  }
	  Swc_Tree_Resort_Id(subtree);
	  sprintf(filename, "graph%d.swc", i + 1);
	  Write_Swc_Tree(full_path(dir, filename), subtree);
	}
      }
    }
  }

  printf("%d chains\n", chain_number);

  return 0;
}
Beispiel #19
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string> -o <string>",
    "[-count <int>] [-dist <int>] [-minobj <int>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);


  Stack *input = Read_Stack(Get_String_Arg("input"));
  
  int nregion = Stack_Max(input, NULL);
  int nvoxel = Stack_Voxel_Number(input);
  int i;
  Stack *stack = Make_Stack(GREY, Stack_Width(input), Stack_Height(input),
      	Stack_Depth(input));
  Stack *out = Make_Stack(GREY, Stack_Width(input), Stack_Height(input),
      	Stack_Depth(input));
  Zero_Stack(out);

  int nobj = 0;
  for (i = 1; i <= nregion; i++) {
    int j;
    int count = 0;
    for (j = 0; j < nvoxel; j++) {
      stack->array[j] = (input->array[j] == i);
    }

    Stack *out3 = NULL;
    int maxcount = 100000;
    if (Is_Arg_Matched("-count")) {
      maxcount = Get_Int_Arg("-count");
    }
    if (count > maxcount) {
      out3 = Copy_Stack(stack);
      Stack_Addc_M(out3, nobj);
      nobj++;
    } else {
      Stack *distmap = Stack_Bwdist_L_U16P(stack, NULL, 0);

      Stack_Watershed_Workspace *ws = Make_Stack_Watershed_Workspace(stack);
      ws->mask = Copy_Stack(distmap);
      int mindist = 10;
      if (Is_Arg_Matched("-dist")) {
	mindist = Get_Int_Arg("-dist");
      }
      Stack_Threshold_Binarize(ws->mask, mindist);
      Translate_Stack(ws->mask, GREY, 1);
      int minobj = 100;
      if (Is_Arg_Matched("-minobj")) {
	minobj = Get_Int_Arg("-minobj");
      }
      Object_3d_List *objs = Stack_Find_Object(ws->mask, 1, minobj);
      Zero_Stack(ws->mask);
      Stack_Draw_Objects_Bw(ws->mask, objs, -255);

      ws->min_level = 1;
      ws->start_level = 65535;
      out3 = Stack_Watershed(distmap, ws);
      Stack_Addc_M(out3, nobj);
      nobj += Object_3d_List_Length(objs);
      Kill_Stack(distmap);
      Kill_Stack_Watershed_Workspace(ws);
      Kill_Object_3d_List(objs);
    }
    Stack_Add(out, out3, out);
    Kill_Stack(out3);
  }

  printf("number of regions: %d\n", nobj);
  Write_Stack(Get_String_Arg("-o"), out);
  char cmd[500];
  sprintf(cmd, "touch %s_done", Get_String_Arg("-o"));
  system(cmd);

  return 0;
}
Beispiel #20
0
int main(int argc, char* argv[])
{ int n_rows, count;
  Measurements *table;
  int face_x, face_y;

  Process_Arguments( argc, argv, Spec, 0);

  if( Is_Arg_Matched("-h") | Is_Arg_Matched("--help") )
  { Print_Argument_Usage(stdout,0);
    printf("-----------------------------------------                                    \n"
          " Classify test 3 (autotraj - no threshold)                                    \n"
          "------------------------------------------                                    \n"
          "                                                                              \n"
          "  For frames where the expected number of whiskers are found,                 \n"
          "  label the whiskers according to their order on the face.                    \n"
          "\n"
          "  <source> Filename with Measurements table.\n"
          "  <dest>   Filename to which labelled Measurements will be saved.\n"
          "           This can be the same as <source>.\n"
          "  <face>\n"
          "  <x> <y>  These are used for determining the order of whisker segments along \n"
          "           the face.  This requires an approximate position for the center of \n"
          "           the face and can be specified in pixel coordinates with <x> and <y>.\n"
          "           If the face is located along the edge of the frame then specify    \n"
          "           that edge with 'left', 'right', 'top' or 'bottom'.                 \n"
          "  -n <int> (Optional) Expect this number of whiskers.                         \n"
          "           If this isn't specified, or if this is set to a number less than 1 \n"
          "           then the number of whiskers is automatically determined.           \n"
          "--                                                                            \n");
    return 0;
  }

  table  = Measurements_Table_From_Filename          ( Get_String_Arg("source"), NULL, &n_rows );
  if(!table) error("Couldn't read %s\n",Get_String_Arg("source"));
  Sort_Measurements_Table_Time(table,n_rows);

  if( Is_Arg_Matched("face") )
  { int maxx,maxy;
    Measurements_Table_Pixel_Support( table, n_rows, &maxx, &maxy );
    Helper_Get_Face_Point( Get_String_Arg("face"), maxx, maxy, &face_x, &face_y);
  } else 
  {
    face_x = Get_Int_Arg("x");
    face_y = Get_Int_Arg("y");
  }
#ifdef DEBUG_CLASSIFY_3
  debug("   Face Position: ( %3d, %3d )\n", face_x, face_y);
#endif
 
  // Initialize
  Measurements_Table_Label_By_Threshold    ( table,
                                             n_rows,
                                             0, // length column
                                             0, // threshold
                                             1);// require greater than threshold
  //
  // Estimate whisker count if neccessary
  // 
  if( !Is_Arg_Matched("-n") || ( (count = Get_Int_Arg("-n"))<2 ) )
  { int n_good_frames;
    n_good_frames = Measurements_Table_Best_Frame_Count_By_State( table, n_rows, 1, &count );
	#ifdef DEBUG_CLASSIFY_3
		debug(
			  "   Frames with count: %d\n"
			  ,n_good_frames ); 
	#endif
  } 
#ifdef DEBUG_CLASSIFY_3
	debug("        Target count: %d\n"
		  ,count ); 
#endif
#ifdef DEBUG_CLASSIFY_3
  { Measurements *row = table + n_rows; //Assert all state==1
    while(row-- > table)
      assert(row->state == 1);
  }
#endif

  Measurements_Table_Set_Constant_Face_Position     ( table, n_rows, face_x, face_y);
  Measurements_Table_Set_Follicle_Position_Indices  ( table, n_rows, 4, 5 );

  Measurements_Table_Label_By_Order(table, n_rows, count ); //resorts

  Measurements_Table_To_Filename( Get_String_Arg("dest"), NULL, table, n_rows );
  Free_Measurements_Table(table);
  return 0;
}
Beispiel #21
0
int main(int argc, char *argv[])
{ char  *whisker_file_name, *bar_file_name, *prefix;
  size_t prefix_len;
  FILE  *fp;
  Image *bg=0, *image=0;
  int    i,depth;

  char * movie;

  /* Process Arguments */
  Process_Arguments(argc,argv,Spec,0);
  { char* paramfile = "default.parameters";
    if(Load_Params_File("default.parameters"))
    { warning(
        "Could not load parameters from file: %s\n"
        "Writing %s\n"
        "\tTrying again\n",paramfile,paramfile);
      Print_Params_File(paramfile);
      if(Load_Params_File("default.parameters"))
        error("\tStill could not load parameters.\n");
    }
  }

  prefix = Get_String_Arg("prefix");
  prefix_len = strlen(prefix);
  { char *dot = strrchr(prefix,'.');  // Remove any file extension from the prefix
    if(dot) *dot = 0;
  }
  whisker_file_name = (char*) Guarded_Malloc( (prefix_len+32)*sizeof(char), "whisker file name");
  bar_file_name = (char*) Guarded_Malloc( (prefix_len+32)*sizeof(char), "bar file name");
  memset(whisker_file_name, 0, (prefix_len+32)*sizeof(char) );
  memset(bar_file_name ,    0, (prefix_len+32)*sizeof(char) );

  sprintf( whisker_file_name, "%s.whiskers", prefix );
  sprintf(  bar_file_name, "%s.bar", prefix );

  progress("Loading...\n"); fflush(stdout);
  movie = Get_String_Arg("movie");
  TRY(image = load(movie,0,&depth),ErrorOpen);

  progress("Done.\n");

  // No background subtraction (init to blank)
  { bg = Make_Image( image->kind, image->width, image->height );
    memset(bg->array, 0, bg->width * bg->height );
  }
  Free_Image( image );

#if 0
  /*
   * Bar tracking
   */
  if( !Is_Arg_Matched("--no-bar") )
  { double x,y;
    BarFile *bfile = Bar_File_Open( bar_file_name, "w" );
    progress( "Finding bar positions\n" );
    for( i=0; i<depth; i++ )
    { progress_meter(i, 0, depth-1, 79, "Finding     post: [%5d/%5d]",i,depth);
      image = load(movie,i,NULL);
      invert_uint8( image );
      Compute_Bar_Location(   image,
                              &x,             // Output: x position
                              &y,             // Output: y position
                              15,             // Neighbor distance
                              15,             // minimum contour length
                              0,              // minimum intensity of interest
                              255,            // maximum intentity of interest
                              10.0,           // minimum radius of interest
                              30.0          );// maximum radius of interest
      Bar_File_Append_Bar( bfile, Bar_Static_Cast(i,x,y) );
      Free_Image(image);
    }
    Bar_File_Close( bfile );
  }
#endif

  /*
   * Trace whisker segments
   */
  //if( !Is_Arg_Matched("--no-whisk") )
  { int           nTotalSegs = 0;
    Whisker_Seg   *wv;
    int wv_n; 
    WhiskerFile wfile = Whisker_File_Open(whisker_file_name,"whiskbin1","w");

    if( !wfile )
    { fprintf(stderr, "Warning: couldn't open %s for writing.", whisker_file_name);
    } else
    { //int step = (int) pow(10,round(log10(depth/100)));
      for( i=0; i<depth; i++ )
      //for( i=450; i<460; i++ )
      //for( i=0; i<depth; i+= step )
      { int k;
        TRY(image=load(movie,i,NULL),ErrorRead);
        progress_meter(i, 0, depth, 79, "Finding segments: [%5d/%5d]",i,depth-1);
        wv = find_segments(i, image, bg, &wv_n);                                                // Thrashing heap
        k = Remove_Overlapping_Whiskers_One_Frame( wv, wv_n, 
                                                   image->width, image->height, 
                                                   2.0,    // scale down by this
                                                   2.0,    // distance threshold
                                                   0.5 );  // significant overlap fraction
        Whisker_File_Append_Segments(wfile, wv, k);
        Free_Whisker_Seg_Vec( wv, wv_n );
        Free_Image(image);
      }
      printf("\n");
      Whisker_File_Close(wfile);
    }
  }
  load(movie,-1,NULL); // Close (and free)
  if(bg) Free_Image( bg );
  return 0;
ErrorRead:
  load(movie,-1,NULL); // Close (and free)
  if(bg) Free_Image( bg );
  error("Could not read frame %d from %s"ENDL,i,movie);
  return 1;
ErrorOpen:
  error("Could not open %s"ENDL,movie);
  return 2;
}
Beispiel #22
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-t]", NULL};
  Process_Arguments(argc, argv, Spec, 1);
 
  if (Is_Arg_Matched("-t")) {
    coordinate_3d_t coord = {0, 0, 0};
    
    /* Translate coordinates. */
    Geo3d_Translate_Coordinate(coord, coord+1, coord+2, 1.0, 2.0, 3.0);

    if ((coord[0] != 1.0) || (coord[1] != 2.0) || (coord[2] != 3.0)) {
      Print_Coordinate_3d(coord);
      PRINT_EXCEPTION(":( Bug?", "Unexpected coordinate values.");
      return 1;      
    }
    
    coordinate_3d_t coord2 = {0, 0, 0};
    double dx, dy, dz;

    Geo3d_Coordinate_Offset(coord[0], coord[1], coord[2], coord2[0], coord2[1],
			    coord2[2], &dx, &dy, &dz);
    if ((dx != -coord[0]) || (dy != -coord[1]) || (dz != -coord[2])) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected offset values.");
      return 1;      
    }
    
    Coordinate_3d_Copy(coord2, coord);

    /* Rotate coordinates. */
    Geo3d_Rotate_Coordinate(coord, coord+1, coord+2, 0.1, 0.5, 0);
    
    if (fabs(Geo3d_Orgdist_Sqr(coord[0], coord[1], coord[2]) - 
	     Geo3d_Orgdist_Sqr(coord2[0], coord2[1], coord2[2])) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Rotation failed.");
      return 1;            
    }

    /* inverse rotation */
    Geo3d_Rotate_Coordinate(coord, coord+1, coord+2, 0.1, 0.5, 1);
    if ((fabs(coord[0] - coord2[0]) > 0.01) || 
	(fabs(coord[1] - coord2[1]) > 0.01) ||
	(fabs(coord[2] - coord2[2]) > 0.01)){
      PRINT_EXCEPTION(":( Bug?", "Rotation failed.");
      return 1;            
    }

    /* Normal vector of an orientation. This is a canonical representaion
     * of an orientation. */ 
    Geo3d_Orientation_Normal(0.1, 0.5, coord, coord+1, coord+2);

    /* We can also turn the normal vector into orientation. */
    double theta, psi;
    Geo3d_Normal_Orientation(coord[0], coord[1], coord[2], &theta, &psi);
    if (fabs(theta - 0.1) > 0.01 || fabs(Normalize_Radian(psi) - 0.5) > 0.01) {
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }

    /* If we rotate the vector back, we should get (0, 0, 1). */
    Geo3d_Rotate_Coordinate(coord, coord+1, coord+2, 0.1, 0.5, 1);
    
    if ((fabs(coord[0]) > 0.01) || (fabs(coord[1]) > 0.01) ||
	(fabs(coord[2] - 1.0) > 0.01)){
      PRINT_EXCEPTION(":( Bug?", "Rotation failed.");
      return 1;            
    }

    Geo3d_Coord_Orientation(1, 0, 0, &theta, &psi);
    double in[3] = {0, 0, 1};
    double out[3] = {0, 0, 0};
    Rotate_XZ(in, out, 1, theta, psi, 0);

    if (fabs(out[0] - 1.0) > 0.01 || fabs(out[1]) > 0.01 || 
	fabs(out[2]) > 0.01) {
      printf("%g, %g, %g\n", out[0], out[1], out[2]);
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }
    /*
    if (fabs(theta - TZ_PI_2) > 0.01 || 
	fabs(Normalize_Radian(psi) - TZ_PI_2) > 0.01) {
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }
    */

    Geo3d_Coord_Orientation(5, 0, 0, &theta, &psi);
    {
    double in[3] = {0, 0, 5};
    double out[3] = {0, 0, 0};
    Rotate_XZ(in, out, 1, theta, psi, 0);

    if (fabs(out[0] - 5.0) > 0.01 || fabs(out[1]) > 0.01 || 
	fabs(out[2]) > 0.01) {
      printf("%g, %g, %g\n", out[0], out[1], out[2]);
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }
    }
    /*
    if (fabs(theta - TZ_PI_2) > 0.01 || 
	fabs(Normalize_Radian(psi) - TZ_PI_2) > 0.01) {
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }
    */

    /* Rotate the orientation. */
    theta = TZ_PI_2;
    psi = TZ_PI;
    Geo3d_Rotate_Orientation(-TZ_PI, TZ_PI_2, &theta, &psi);
    if (fabs(theta + TZ_PI_2) > 0.01 || 
	fabs(psi + TZ_PI_2) > 0.01) {
      printf("%g, %g\n", theta, psi);
      PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
      return 1; 
    }
    
    /* More extensive test on rotation */
    Random_Seed(time(NULL) - getpid());
    int i;
    for (i = 0; i < 100; i++) {
      double x = Unifrnd() * (1 - Bernrnd(0.5) * 2.0);
      double y = Unifrnd() * (1 - Bernrnd(0.5) * 2.0);
      double z = Unifrnd() * (1 - Bernrnd(0.5) * 2.0);
      double theta, psi;
      Geo3d_Coord_Orientation(x, y, z, &theta, &psi);

      double x2 = 0.0;
      double y2 = 0.0;
      double z2 = Geo3d_Orgdist(x, y, z);
      Geo3d_Rotate_Coordinate(&x2, &y2, &z2, theta, psi, 0);

      if (fabs(x - x2) > 0.01 || fabs(y - y2) > 0.01 || fabs(z - z2) > 0.01) {
        printf("%g, %g\n", theta, psi);
        printf("%g, %g, %g\n", x, y, z);
        printf("%g, %g, %g\n", x2, y2, z2);
        PRINT_EXCEPTION(":( Bug?", "Unexpected orientation values.");
        return 1; 
      }
    }

    /* Dot product. */
    if (Geo3d_Dot_Product(1.0, 2.0, 3.0, 3.0, 2.0, 1.0) != 10.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected dot product.");
      return 1; 
    }

    /* Cross product. */
    Geo3d_Cross_Product(1.0, 2.0, 3.0, 3.0, 1.0, 2.0, coord, coord+1, coord+2);

    if (fabs(Geo3d_Dot_Product(1.0, 2.0, 3.0, coord[0], coord[1], coord[2])) >
	0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected dot product.");
      return 1; 
    }

    if (fabs(Geo3d_Dot_Product(3.0, 1.0, 2.0, coord[0], coord[1], coord[2])) >
	0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected dot product.");
      return 1; 
    }

    /* Distance calculations. */
    if (Geo3d_Orgdist_Sqr(1.0, 2.0, 3.0) != 14.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected value.");
      return 1;       
    }

    if (fabs(Geo3d_Orgdist(1.0, 2.0, 3.0) - sqrt(14.0)) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected value.");
      return 1;       
    }

    if (Geo3d_Dist(1.0, 2.0, 3.0, 1.0, 2.0, 3.0) != 0.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected value.");
      return 1;       
    }

    if (Geo3d_Dist_Sqr(1.0, 2.0, 3.0, 0.0, 0.0, 0.0) != 14.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected value.");
      return 1;       
    }

    /* Angle between two vectors. */
    if (fabs(Geo3d_Angle2(1, 0, 0, 0, 0, 1) - TZ_PI_2) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected value.");
      return 1;             
    }

    /* Distance between two lines */
    coordinate_3d_t line1_start = {0, 0, 0};
    coordinate_3d_t line1_end = {1, 0, 0};
    coordinate_3d_t line2_start = {0, 1, 1}; 
    coordinate_3d_t line2_end = {0, 2, 1}; 

    double d = Geo3d_Line_Line_Dist(line1_start, line1_end,
				    line2_start, line2_end);

    if (fabs(d - 1.0) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected distance.");
      return 1;             
    }
    
    /* Distance between two line segments. */
    double intersect1, intersect2;
    int cond;
    d = Geo3d_Lineseg_Lineseg_Dist(line1_start, line1_end,
				   line2_start, line2_end, 
				   &intersect1, &intersect2, &cond);
    if (fabs(d - sqrt(2.0)) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected distance.");
      return 1;             
    }

    /* Distance between a point and a line segment. */
    coord[0] = 0.5;
    coord[1] = 1.0;
    coord[2] = 1.0;
    d = Geo3d_Point_Lineseg_Dist(coord, line1_start, line1_end, &intersect1);
    if (fabs(d - sqrt(2.0)) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected distance.");
      return 1;             
    }

    /* Get a break point of a line segment. */
    Geo3d_Lineseg_Break(line1_start, line1_end, 0.1, coord);
    if ((coord[0] != 0.1) || (coord[1] != 0.0) || (coord[2] != 0.0)) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected break point.");
      return 1;                   
    }

    /* Orientations of a set of points */

    /* Orientation of a covariance matrix */

    /* 3D coordinates routines */
    /* Unitize a point. */
    Coordinate_3d_Unitize(coord);
    
    if (fabs(Coordinate_3d_Norm(coord) - 1.0) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected norm.");
      return 1;                   
    }

    Set_Coordinate_3d(coord, 0.0, 0.0, 0.0);

    /* origin point is not affected by unitization */
    Coordinate_3d_Unitize(coord);
    
    if (Coordinate_3d_Norm(coord) != 0.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected norm.");
      return 1;                   
    }
    
    Set_Coordinate_3d(coord, 1.0, 2.0, 3.0);

    /* Square length */
    if (Coordinate_3d_Length_Square(coord) != 14) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected square length");
    }

    /* Angle between two vectors */
    coordinate_3d_t coord_a1 = { 1, 0, 0 }; 
    coordinate_3d_t coord_a2 = { 0, 0, 1 };

    if (fabs(Coordinate_3d_Angle2(coord_a1, coord_a2) - TZ_PI_2) > 0.01) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected angle");
    }


    /* Scale coordinates */
    Coordinate_3d_Scale(coord, 2.0);
    
    if ((coord[0] != 2.0) || (coord[1] != 4.0) || (coord[2] != 6.0)) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected coordinate value.");
      return 1;                         
    }

    /* Normalizd dot product */
    if (Coordinate_3d_Normalized_Dot(coord, coord2) > 1.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected dot product.");
      return 1;                               
    }

    Set_Coordinate_3d(coord, 1.0, 2.0, 3.0);    

    Coordinate_3d_Copy(coord2, coord);
    Coordinate_3d_Scale(coord2, 2.0);

    coordinate_3d_t coord3;
    Coordinate_3d_Copy(coord3, coord);
    Coordinate_3d_Scale(coord3, 3.0);

    /* cos value of an angle formed by 3 points */
    if (Coordinate_3d_Cos3(coord, coord2, coord3) != 1.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected cos value.");
      return 1;      
    }

    /* cos value of an angle formed by 4 points */
    coordinate_3d_t coord4;
    Coordinate_3d_Copy(coord4, coord);
    Coordinate_3d_Scale(coord4, 4.0);

    if (Coordinate_3d_Cos4(coord, coord2, coord3, coord4) != 1.0) {
      PRINT_EXCEPTION(":( Bug?", "Unexpected cos value.");
      return 1;      
    }

    printf(":) Testing passed.\n");

    return 0;
  }

#if 0
  Geo3d_Vector v1 = {1.1, 0, 0};
  Geo3d_Vector v2 = {5, 0, 0};

  double theta1 = 3.83812;
  double psi1 = 3.53202;
  double theta2 = 0.72657;
  double psi2 = 3.61214;

  Geo3d_Orientation_Normal(theta1, psi1, &(v1.x), &(v1.y), &(v1.z));
  Geo3d_Orientation_Normal(theta2, psi2, &(v2.x), &(v2.y), &(v2.z));
 
  Print_Geo3d_Vector(&v1);
  Print_Geo3d_Vector(&v2);

  printf("%g\n", Geo3d_Vector_Dot(&v1, &v2));
  printf("%g\n", Geo3d_Vector_Angle2(&v1, &v2));

  
  double angle = Vector_Angle(-1.0, -1.0);
  
  theta1 = -3.0;
  psi1 = -5.0;
  
  double x, y, z;
  Geo3d_Orientation_Normal(theta1, psi1, &x, &y, &z);
  printf("%g, %g, %g\n", x, y, z);

  Geo3d_Normal_Orientation(x, y, z, &theta1, &psi1);

  printf("%g\n", angle * 180.0 / TZ_PI);

  printf("%g, %g\n", theta1, psi1);
  Geo3d_Orientation_Normal(theta1, psi1, &x, &y, &z);
  printf("%g, %g, %g\n", x, y, z);
#endif

#if 0
  Geo3d_Scalar_Field *field = 
    Read_Geo3d_Scalar_Field("../data/mouse_neuron/seeds.bn");
  Print_Geo3d_Scalar_Field_Info(field);
  Stack *stack = Read_Stack("../data/mouse_neuron/mask.tif");
  Geo3d_Scalar_Field_Draw_Stack(field, stack, NULL, NULL);
  Write_Stack("../data/test.tif", stack);
#endif

#if 0
  double line_start[3] = {2.0, 3.0, 4.0};
  double line_end[3] = {1.0, 1.0, 6.0};

  double point[3] = {10.5, 20.5, 40.7};

  double lamda;
  printf("%g\n", Geo3d_Point_Lineseg_Dist(point, line_start, line_end, &lamda));
  double line_point[3];
  double length = sqrt(Geo3d_Dist_Sqr(line_start[0], line_start[1], line_start[2], line_end[0], line_end[1], line_end[2]));
  line_point[0] = line_start[0] + lamda * (line_end[0] - line_start[0]);
  line_point[1] = line_start[1] + lamda * (line_end[1] - line_start[1]);
  line_point[2] = line_start[2] + lamda * (line_end[2] - line_start[2]);
  printf("%g\n", lamda);
  printf("%g\n", sqrt(Geo3d_Dist_Sqr(line_point[0], line_point[1], line_point[2], point[0], point[1], point[2])));

  darray_sub(point, line_point, 3);
  darray_sub(line_end, line_point, 3);
  printf("%g\n", Geo3d_Dot_Product(point[0], point[1], point[2],
				   line_end[0], line_end[1], line_end[2]));

#endif

#if 0
  Geo3d_Scalar_Field *field = Read_Geo3d_Scalar_Field("../data/mouse_neuron3_org/seeds");
  //Print_Geo3d_Scalar_Field(field);

  darray_write("../data/pts.bn", (double *)field->points, field->size * 3);
  darray_write("../data/ws.bn", field->values, field->size);

  coordinate_3d_t centroid;
  Geo3d_Scalar_Field_Centroid(field, centroid);
  Print_Coordinate_3d(centroid);
  
  double cov[9];
  Geo3d_Scalar_Field_Cov(field, cov);
  darray_print2(cov, 3, 3);

  darray_write("../data/cov.bn", cov, 9);

  double vec[3];
  Geo3d_Cov_Orientation(cov, vec);
  darray_print2(vec, 3, 1);

  
#endif

#if 0
  double mu1, mu2;

#  if 0 /* parallel case */
  double line1_start[3] = {0, 0, 0};
  double line1_end[3] = {1, 1, 10};
  double line2_start[3] = {0, 1, 0};
  double line2_end[3] = {1, 2, 10};
#  endif

#  if 0 /* parallel case */
  double line1_start[3] = {0, 0, 0};
  double line1_end[3] = {1, 1, 10};
  double line2_start[3] = {-1, -1, -1};
  double line2_end[3] = {-3, -3, -21};
#  endif

#  if 0 /* i-i case */
  double line1_start[3] = {0, 0, 0};
  double line1_end[3] = {3, 4, 5};
  double line2_start[3] = {-1, 8, 9};
  double line2_end[3] = {1, -3, -4};
#  endif

#  if 0 /* point to line case */
  double line1_start[3] = {3, 4, 5};
  double line1_end[3] = {3, 4, 5};
  double line2_start[3] = {-1, 8, 9};
  double line2_end[3] = {1, -3, -4};
#  endif

#  if 0 /* point to line case */
  double line2_start[3] = {3, 4, 5};
  double line2_end[3] = {3, 4, 5};
  double line1_start[3] = {-1, 8, 9};
  double line1_end[3] = {1, -3, -4};
#  endif

#  if 0 /* point to line case */
  double line2_start[3] = {3, 4, 5};
  double line2_end[3] = {3, 4, 5};
  double line1_start[3] = {-1, 8, 9};
  double line1_end[3] = {-1, 8, 9};
#  endif

#  if 0
  double line1_start[3] = {256.062, 328.674, 67.9029};
  double line1_end[3] = {246.162, 330.078, 67.9896};
  double line2_start[3] = {262.368, 336.609, 68.3076};
  double line2_end[3] = {259.956, 326.944, 67.4325};
#  endif

  int cond;
  double dist = Geo3d_Lineseg_Lineseg_Dist(line1_start, line1_end, 
					   line2_start, line2_end, 
					   &mu1, &mu2, &cond);
  printf("%d, %g\n", cond, dist);

  dist = Geo3d_Line_Line_Dist(line1_start, line1_end, line2_start, line2_end);

  printf("%g\n", dist);
#endif

#if 1
  double *d = Unifrnd_Double_Array(12000000, NULL);
  double *d2 = Unifrnd_Double_Array(12000000, NULL);
  tic();
  Rotate_XZ(d, d, 4000000, 0.1, 0.2, 1);
  printf("%llu\n", toc());
  tic();
  Rotate_XZ2(d, d, 4000000, 0.1, 0.2, 0);
  printf("%llu\n", toc());

#endif

#if 0
  double d[3] = {0.1, 0.2, 0.3};
  Rotate_XZ(d, d, 1, 0.1, 0.2, 0);
  darray_print2(d, 3, 1);
#endif

#if 0
  printf("%g\n", Ellipse_Point_Distance(5, 5, 3, 5));
#endif

#if 0
  Geo3d_Ellipse *ellipse = New_Geo3d_Ellipse();
  ellipse->scale = 0.5;
  ellipse->orientation[0] = 1.0;
  Print_Geo3d_Ellipse(ellipse);

  FILE *fp = fopen("../data/test.swc", "w");
  Swc_Node node;
  
  Geo3d_Ellipse_To_Swc_Node(ellipse, 1, -1, 1.0, 2, &node);
  Swc_Node_Fprint(fp, &node);  
  
  /*
  double pt[3] = {0.0, 0.0, 1.0};
  printf("%g\n", Geo3d_Ellipse_Point_Distance(ellipse, pt));
  */
  
  Geo3d_Ellipse *ellipse2 = Copy_Geo3d_Ellipse(ellipse);
  ellipse2->center[0] += 10.0;
  ellipse2->orientation[0] = 2.0;
  ellipse2->radius += 3.0;

  Geo3d_Ellipse *ellipse3 = Geo3d_Ellipse_Interpolate(ellipse, ellipse2, 0.2,
						      NULL);
  Geo3d_Ellipse_To_Swc_Node(ellipse3, 2, 1, 1.0, 2, &node);
  Swc_Node_Fprint(fp, &node);

  Geo3d_Ellipse_To_Swc_Node(ellipse2, 3, 2, 1.0, 2, &node);
  Swc_Node_Fprint(fp, &node);

  Print_Geo3d_Ellipse(ellipse3);

  fclose(fp);
#endif

#if 0
  Geo3d_Ellipse *ellipse = New_Geo3d_Ellipse();
  ellipse->scale = 0.5;

  FILE *fp = fopen("../data/test.swc", "w");
  coordinate_3d_t *pts = Geo3d_Ellipse_Sampling(ellipse, 20, 0, NULL);
  Geo3d_Point_Array_Swc_Fprint(fp, pts, 20, 1, -1, 1.0, 2);

  ellipse->orientation[0] = 1.0;
  pts = Geo3d_Ellipse_Sampling(ellipse, 20, 0, NULL);
  Geo3d_Point_Array_Swc_Fprint(fp, pts, 20, 21, -1, 1.0, 3);

  ellipse->center[2] = 5.0;
  pts = Geo3d_Ellipse_Sampling(ellipse, 20, 0, NULL);
  Geo3d_Point_Array_Swc_Fprint(fp, pts, 20, 41, -1, 1.0, 4);

  coordinate_3d_t vec[2];
  Coordinate_3d_Copy(vec[0], ellipse->center);
  Geo3d_Ellipse_First_Vector(ellipse, vec[1]);
  Coordinate_3d_Add(vec[0], vec[1], vec[1]);
  Geo3d_Point_Array_Swc_Fprint(fp, vec, 2, 101, -1, 1.0, 5);
 
  Geo3d_Ellipse_Second_Vector(ellipse, vec[1]);
  Coordinate_3d_Add(vec[0], vec[1], vec[1]);
  Geo3d_Point_Array_Swc_Fprint(fp, vec, 2, 111, -1, 1.0, 6);
 
  Geo3d_Ellipse_Normal_Vector(ellipse, vec[1]);
  Coordinate_3d_Add(vec[0], vec[1], vec[1]);
  Geo3d_Point_Array_Swc_Fprint(fp, vec, 2, 121, -1, 1.0, 7);
 
  fclose(fp);
#endif

#if 0
  Geo3d_Ellipse ep_array[10];

  Geo3d_Ellipse *ellipse = New_Geo3d_Ellipse();
  ellipse->scale = 0.5;

  Geo3d_Ellipse_Copy(ep_array, ellipse);

  FILE *fp = fopen("../data/test.swc", "w");

  ellipse->orientation[0] += 0.5;
  ellipse->center[2] += 3.0;
  ellipse->center[0] += 1.0;
  Geo3d_Ellipse_Copy(ep_array + 1, ellipse);

  ellipse->center[2] += 3.0;
  Geo3d_Ellipse_Copy(ep_array + 2, ellipse);

  coordinate_3d_t *pts = Geo3d_Ellipse_Array_Sampling(ep_array, 3, 20, NULL);
  Geo3d_Point_Array_Swc_Fprint(fp, pts, 60, 1, -1, 1.0, 2);

  fclose(fp);
#endif

#if 0
  printf("%g\n", Vector_Angle(1.0, 1.0) * 180 / TZ_PI);
#endif

#if 0
  double theta, psi;
  coordinate_3d_t coord;
  coord[0] = 0.0822;
  coord[1] = 0.1515;
  coord[2] = 0.1369;
  Geo3d_Coord_Orientation(coord[0], coord[1], coord[2], &theta, &psi);
  printf("%g, %g\n", theta, psi);

  Geo3d_Orientation_Normal(theta, psi, coord, coord+1, coord+2); 
  Print_Coordinate_3d(coord);
#endif

#if 0
  double theta, psi;
  double x = -1;
  double y = 1.83697019872103e-16;
  double z = 3;
  
  Geo3d_Coord_Orientation(x, y, z, &theta, &psi);
#endif

#if 0
  double theta = Vector_Angle2(0, 1, 1, 0, TRUE);
  printf("angle: %g\n", theta);

  theta = Vector_Angle2(0, 1, -1, 0, FALSE);
  printf("angle: %g\n", theta);

  theta = Vector_Angle2(-1, 0, -1, -1, TRUE);
  printf("angle: %g\n", theta);
#endif

  return 0;
}
Beispiel #23
0
int main(int argc, char* argv[])
{
  if (Show_Version(argc, argv, "1.00") == 1) {
    return 0;
  }

  static char *Spec[] = {
    " <image:string> -s <string> -o <string> [-e <string>] [-fo <int>] "
    "[-z <double> | -res <string>] [-field <int>] [-min_score <double>]",
    NULL};
  
  Process_Arguments(argc, argv, Spec, 1);
  
  Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(Get_String_Arg("-s"));

  size_t idx;
  double max_r = darray_max(seed->values, seed->size, &idx);

  max_r *= 1.5;

  //Set_Neuroseg_Max_Radius(max_r);

  Stack *signal = Read_Stack_U(Get_String_Arg("image"));

  dim_type dim[3];
  dim[0] = signal->width;
  dim[1] = signal->height;
  dim[2] = signal->depth;

  Rgb_Color color;
  Set_Color(&color, 255, 0, 0);

  int seed_offset = -1;

  double z_scale = 1.0;

  if (Is_Arg_Matched("-res")) {
    if (fexist(Get_String_Arg("-res"))) {
      double res[3];
      int length;
      darray_read2(Get_String_Arg("-res"), res, &length);
      if (res[0] != res[1]) {
	perror("Different X-Y resolutions.");
	TZ_ERROR(ERROR_DATA_VALUE);
      }
      z_scale = res[0] / res[2] * 2.0;
    }
  }
  
  if (Is_Arg_Matched("-z")) {
    z_scale = Get_Double_Arg("-z");
  }

  printf("z scale: %g\n", z_scale);

  tic();


  double *values = darray_malloc(seed->size);

  int i;
  Local_Neuroseg *locseg = (Local_Neuroseg *) 
    malloc(seed->size * sizeof(Local_Neuroseg));


  int index = 0;

  //int ncol = LOCAL_NEUROSEG_NPARAM + 1 + 23;
  //double *features = darray_malloc(seed->size * ncol);
  //double *tmpfeats = features;

  Stack *seed_mask = Make_Stack(GREY, signal->width, signal->height, 
				signal->depth);
  Zero_Stack(seed_mask);

  Locseg_Fit_Workspace *fws = New_Locseg_Fit_Workspace();
  
  if (Is_Arg_Matched("-field")) {
    fws->sws->field_func = Neuroseg_Slice_Field_Func(Get_Int_Arg("-field"));
  }

  fws->sws->fs.n = 2;
  fws->sws->fs.options[0] = STACK_FIT_DOT;
  fws->sws->fs.options[1] = STACK_FIT_CORRCOEF;

  if (Is_Arg_Matched("-fo")) {
    fws->sws->fs.options[1] = Get_Int_Arg("-fo");
  }

  for (i = 0; i < seed->size; i++) {
    printf("-----------------------------> seed: %d / %d\n", i, seed->size);

    index = i;
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    double width = seed->values[index];

    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);

    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(locseg[i].seg), width, 0.0, NEUROSEG_DEFAULT_H, 
		 0.0, 0.0, 0.0, 0.0, 1.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] /= z_scale;
    
    Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER);

    if (seed_mask->array[seed_offset] > 0) {
      printf("labeled\n");
      values[i] = 0.0;
      continue;
    }

    //Local_Neuroseg_Optimize(locseg + i, signal, z_scale, 0);
    Local_Neuroseg_Optimize_W(locseg + i, signal, z_scale, 0, fws);

    values[i] = fws->sws->fs.scores[1];
    /*
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    values[i] = Local_Neuroseg_Score(locseg + i, signal, z_scale, &fs);
    */

    //values[i] = Local_Neuroseg_Score_W(locseg + i, signal, z_scale, sws);

    printf("%g\n", values[i]);

    double min_score = LOCAL_NEUROSEG_MIN_CORRCOEF;
    if (Is_Arg_Matched("-min_score")) {
      min_score = Get_Double_Arg("-min_score");
    }

    if (values[i] > min_score) {
      Local_Neuroseg_Label_G(locseg + i, seed_mask, -1, 2, z_scale);
    } else {
      Local_Neuroseg_Label_G(locseg + i, seed_mask, -1, 1, z_scale);
    }

    /*
    tmpfeats += Local_Neuroseg_Param_Array(locseg + i, z_scale, tmpfeats);
    
    tmpfeats += Local_Neuroseg_Stack_Feature(locseg + i, signal, z_scale, 
					     tmpfeats); 
    */
  }

  if (Is_Arg_Matched("-e")) {
    Write_Stack(Get_String_Arg("-e"), seed_mask);
  }
  Write_Local_Neuroseg_Array(Get_String_Arg("-o"), locseg, seed->size);

  char file_path[MAX_PATH_LENGTH];
  sprintf(file_path, "%s_score", Get_String_Arg("-o"));
  darray_write(file_path, values, seed->size);

  //sprintf(file_path, "%s_feat", Get_String_Arg("-o"));
  //darray_write(file_path, features, seed->size * ncol); 

  Kill_Geo3d_Scalar_Field(seed);

  printf("Time passed: %lld\n", toc());

  
  return 0;
}
int main(int argc, char *argv[])
{ char        *in, *out;
  Tiff_Reader *reader;
  Tiff_Writer *writer;
  Tiff_IFD    *ifd;
  int          flag64, first, source, target;
  int         *colors, nchan;

  Process_Arguments(argc,argv,Spec,0);

  in  = Get_String_Arg("in");
  out = Get_String_Arg("out");

  reader = Open_Tiff_Reader(in,NULL,&flag64,strcmp(in+(strlen(in)-4),".lsm") == 0);
  if (reader == NULL)
    { fprintf(stderr,"Error opening tif %s:\n  %s\n",in,Tiff_Error_String());
      exit (1);
    }

  writer = Open_Tiff_Writer(out,flag64,0);
  if (writer == NULL)
    { fprintf(stderr,"Error opening tif %s:\n  %s\n",out,Tiff_Error_String());
      exit (1);
    }

  nchan  = 0;
  colors = NULL;
  target = 0;
  source = 0;

  first = 1;
  while ( ! End_Of_Tiff(reader))
    { ifd = Read_Tiff_IFD(reader);
      if (ifd == NULL)
        { fprintf(stderr,"Error reading IFD:\n  %s\n",Tiff_Error_String());
          exit (1);
        }
      if (first)
        { first = 0;
          if (Is_Arg_Matched("-m"))
            { source = Get_Int_Arg("-m",1);
              target = Get_Int_Arg("-m",2);
              if (source < 0 || source > 1)
                { fprintf(stderr,"Source is not 0 or 1\n"); exit (1); }
              if (target < 0 || target > 2)
                { fprintf(stderr,"Target is not 0, 1, or 2\n"); exit (1); }
            }
          else if (Get_Tiff_Tag(ifd,TIFF_CZ_LSM_INFO,NULL,NULL) != NULL)
            { if (nchan == 0)
                { nchan = Count_LSM_Colors(ifd);
                  colors = (int *) Guarded_Malloc(sizeof(int)*((size_t) nchan),Program_Name());
                }
              Get_LSM_Colors(ifd,nchan,colors);          //  Figure out which channel is green
              for (source = 0; source < nchan; source++) //    and map to green in the RGB
                if ((colors[source] & 0xff00) != 0)
                  break;
              if (source >= nchan)
                source = 0;
              target = 1;
             }
           else
             { source = 0;
               target = 1;
             }
        }
      if (Convert_2_RGB(ifd,source,target) != NULL)
        { if (Write_Tiff_IFD(writer,ifd))
            { fprintf(stderr,"Error writing IFD:\n  %s\n",Tiff_Error_String());
              exit (1);
            }
        }
      else
        { fprintf(stderr,"Error adding extra channel:\n  %s\n",Tiff_Error_String());
          exit (1);
        }
      Free_Tiff_IFD(ifd);
    }
  Free_Tiff_Writer(writer);

  exit (0);
}
Beispiel #25
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-root_id <int>] [<input:string>]",
    "[-a <string>] [-b <string>]", 
    "[-stitch_script] [-exclude <string>] [-tile_number <int>]",
    NULL};
  Process_Arguments(argc, argv, Spec, 1);

  int *excluded = NULL;
  int nexc = 0;
  int *excluded_pair = NULL;
  int nexcpair = 0;
  if (Is_Arg_Matched("-exclude")) {
    String_Workspace *sw = New_String_Workspace();
    FILE *fp = fopen(Get_String_Arg("-exclude"), "r");
    char *line = Read_Line(fp, sw);
    excluded = String_To_Integer_Array(line, NULL, &nexc);
    line = Read_Line(fp, sw);
    if (line != NULL) {
      excluded_pair = String_To_Integer_Array(line, NULL, &nexcpair);
      nexcpair /= 2;
    }
    Kill_String_Workspace(sw);
    fclose(fp);
  }

  int n = 0;
  Graph *graph = Make_Graph(n + 1, n, TRUE);
  char filepath1[100];
  char filepath2[100];
  int i, j;
  Stack *stack1 = NULL;
  FILE *fp = NULL;
  if (Is_Arg_Matched("-stitch_script")) {
    Cuboid_I *boxes = read_tile_array(Get_String_Arg("-a"), &n);
    for (i = 0; i < n; i++) {
      for (j = i + 1; j < n; j++) {      
	BOOL is_excluded = FALSE;
	int k;
	for (k = 0; k < nexc; k++) {
	  if ((i == excluded[k] - 1) || (j == excluded[k] - 1)) {
	    is_excluded = TRUE;
	    break;
	  }
	}
	for (k = 0; k < nexcpair; k++) {
	  if (((i == excluded_pair[k*2]) && (j == excluded_pair[k*2+1])) ||
	      ((j == excluded_pair[k*2]) && (i == excluded_pair[k*2+1]))) {
	    is_excluded = TRUE;
	    break;
	  }
	}
	/*
	if ((i != 103) && (j != 103) && (i != 115) && (j != 115) && (i != 59) &&
	    (j != 59) && !(i == 116 && j == 116)) {
	    */
	if (is_excluded == FALSE) {
	  Cuboid_I_Overlap_Volume(boxes + i, boxes + j);
	  Cuboid_I ibox;
	  Cuboid_I_Intersect(boxes + i, boxes + j, &ibox);
	  int width, height, depth;
	  Cuboid_I_Size(&ibox, &width, &height, &depth);

	  if ((imax2(width, height) > 1024 / 3) && (imin2(width, height) > 0)) {
	    sprintf(filepath1, "%s/stack/%03d.xml", 
		Get_String_Arg("input"), i + 1);
	    sprintf(filepath2, "%s/stack/%03d.xml", 
		Get_String_Arg("input"), j + 1);
	    if (stack1 == NULL) {
	      stack1 = Read_Stack_U(filepath1);
	    }
	    Stack *stack2 = Read_Stack_U(filepath2);

	    Stack *substack1= Crop_Stack(stack1, ibox.cb[0] - boxes[i].cb[0], 
		ibox.cb[1] - boxes[i].cb[1], 0,
		width, height, stack1->depth, NULL);
	    Stack *substack2 = Crop_Stack(stack2, ibox.cb[0] - boxes[j].cb[0], 
		ibox.cb[1] - boxes[j].cb[1], 0,
		width, height, stack2->depth, NULL);

	    Image *img1 = Proj_Stack_Zmax(substack1);	
	    Image *img2 = Proj_Stack_Zmax(substack2);
	    double w = u16array_corrcoef((uint16_t*) img1->array, 
		(uint16_t*) img2->array, 
		img1->width * img1->height);

	    Kill_Stack(stack2);
	    Kill_Stack(substack1);
	    Kill_Stack(substack2);
	    Kill_Image(img1);
	    Kill_Image(img2);
	    printf("%d, %d : %g\n", i + 1, j + 1, w);
	    Graph_Add_Weighted_Edge(graph, i + 1, j + 1, 1000.0 / (w + 1.0));
	  }
	}
	if (stack1 != NULL) {
	  Kill_Stack(stack1);
	  stack1 = NULL;
	}
      }
    }

    Graph_Workspace *gw = New_Graph_Workspace();
    Graph_To_Mst2(graph, gw);

    Arrayqueue q = Graph_Traverse_B(graph, Get_Int_Arg("-root_id"), gw);

    Print_Arrayqueue(&q);

    int *grown = iarray_malloc(graph->nvertex);
    for (i = 0; i < graph->nvertex; i++) {
      grown[i] = 0;
    }

    int index  = Arrayqueue_Dequeue(&q);
    grown[index] = 1;

    char stitch_p_file[5][500];
    FILE *pfp[5];
    for (i = 0; i < 5; i++) {
      sprintf(stitch_p_file[i], "%s/stitch/stitch_%d.sh", Get_String_Arg("input"), i);
      pfp[i] = fopen(stitch_p_file[i], "w");
    }

    sprintf(filepath1, "%s/stitch/stitch_all.sh", Get_String_Arg("input"));

    fp = GUARDED_FOPEN(filepath1, "w");
    fprintf(fp, "#!/bin/bash\n");

    int count = 0;
    while ((index = Arrayqueue_Dequeue(&q)) > 0) {
      for (i = 0; i < graph->nedge; i++) {
	int index2 = -1;
	if (index == graph->edges[i][0]) {
	  index2 = graph->edges[i][1];
	} else if (index == graph->edges[i][1]) {
	  index2 = graph->edges[i][0];
	}

	if (index2 > 0) {
	  if (grown[index2] == 1) {
	    char cmd[500];
	    sprintf(filepath2, "%s/stitch/%03d_%03d_pos.txt",
		Get_String_Arg("input"), index2, index);
	    sprintf(cmd, 
		"%s/stitchstack %s/stack/%03d.xml %s/stack/%03d.xml -o %s", 
		Get_String_Arg("-b"), Get_String_Arg("input"),
		index2, Get_String_Arg("input"), index, filepath2);
	    fprintf(fp, "%s\n", cmd);
	    count++;
	    fprintf(pfp[count%5], "%s\n", cmd);
	    /*
	    if (!fexist(filepath2)) {
	      system(cmd);
	    }
	    */
	    grown[index] = 1;
	    break;
	  }
	}
      }
    }

    fclose(fp);  
    for (i = 0; i < 5; i++) {
      fprintf(pfp[i], "touch %s/stitch/stitch_%d_done\n", 
	  Get_String_Arg("input"), i);
      fclose(pfp[i]);
    }
    return 0;
  }
  
  sprintf(filepath1, "%s/stitch/stitch_all.sh", Get_String_Arg("input"));
  fp = GUARDED_FOPEN(filepath1, "r");

//#define MAX_TILE_INDEX 153
  int tile_number = Get_Int_Arg("-tile_number");
  int max_tile_index = tile_number + 1;

  char *line = NULL;
  String_Workspace *sw = New_String_Workspace();
  int id[2];
  char filepath[100];
  int offset[max_tile_index][3];
  int relative_offset[max_tile_index][3];
  int array[max_tile_index];

  for (i = 0; i < max_tile_index; i++) {
    array[i] = -1;
    offset[i][0] = 0;
    offset[i][1] = 0;
    offset[i][2] = 0;
    relative_offset[i][0] = 0;
    relative_offset[i][1] = 0;
    relative_offset[i][2] = 0;
  }

  while ((line = Read_Line(fp, sw)) != NULL) {
    char *remain = strsplit(line, ' ', 1);
    if (String_Ends_With(line, "stitchstack")) {
      String_To_Integer_Array(remain, id, &n);
      id[0] = id[1];
      id[1] = id[3];
      array[id[1]] = id[0];

      sprintf(filepath, "%s/stitch/%03d_%03d_pos.txt", Get_String_Arg("input"),
	      id[0], id[1]);
      if (!fexist(filepath)) {
	fprintf(stderr, "file %s does not exist\n", filepath);
	return 1;
      }
      FILE *fp2 = GUARDED_FOPEN(filepath, "r");
      line = Read_Line(fp2, sw);
      line = Read_Line(fp2, sw);
      int tmpoffset[8];
      String_To_Integer_Array(line, tmpoffset, &n);
      relative_offset[id[1]][0] = tmpoffset[2];
      relative_offset[id[1]][1] = tmpoffset[3];
      relative_offset[id[1]][2] = tmpoffset[4];

      fclose(fp2);
    }
  }
  
  for (i = 1; i < max_tile_index; i++) {
    BOOL is_excluded = FALSE;
    int k;
    for (k = 0; k < nexc; k++) {
      if (i == excluded[k]) {
	is_excluded = TRUE;
	break;
      }
    }
    /*if ((i == 104) || (i == 116) || (i == 60) || (i == 152)) {*/
    if (is_excluded) {
      printf("%d: (0, 0, 10000)\n", i);
    } else {
      int index = i;
      while (index >= 0) {
	offset[i][0] += relative_offset[index][0];
	offset[i][1] += relative_offset[index][1];
	offset[i][2] += relative_offset[index][2];
	index = array[index];
      }
      printf("%d: (%d, %d, %d)\n", i, offset[i][0], offset[i][1], offset[i][2]);
    }
  }

  fclose(fp);

  return 0;
}
Beispiel #26
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-z <double>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

#if 0
  Locseg_Chain *chain1 = Read_Locseg_Chain("../data/ct017/test5/chain2.bn");
  Locseg_Chain *chain2 = Read_Locseg_Chain("../data/ct017/test5/chain1.bn");

  if (Is_Arg_Matched("-z")) {
    double z_scale = Get_Double_Arg("-z");
    Locseg_Chain_Scale_Z(chain1, z_scale);
    Locseg_Chain_Scale_Z(chain2, z_scale);
  }

  Neurocomp_Conn conn;
  Locseg_Chain_Connection_Test_P(chain1, chain2, &conn);
  Print_Neurocomp_Conn(&conn);

  double scale = 2.0;
  double offset = 5.0;

  Local_Neuroseg *locseg1;
  if (conn.info[0] == 0) {
    locseg1 = Locseg_Chain_Head_Seg(chain1);
    Local_Neuroseg_Stretch(locseg1, scale, offset, -1);
  } else {
    locseg1 = Locseg_Chain_Tail_Seg(chain1);
    Local_Neuroseg_Stretch(locseg1, scale, offset, 1);
  }

  Local_Neuroseg *locseg2 = Locseg_Chain_Peek_Seg_At(chain2, conn.info[1]);

  Local_Neuroseg_Stretch(locseg2, scale, offset, 0);

  printf("%g\n", Local_Neuroseg_Planar_Dist_L(locseg1, locseg2));

  FILE *fp = fopen("../data/ct017/test5/test.swc", "w");
  
  /* to avoid v3d bug */
  Local_Neuroseg *tmp_locseg = Copy_Local_Neuroseg(locseg1);
  tmp_locseg->seg.r1 = 0.1;
  Local_Neuroseg_Swc_Fprint(fp, tmp_locseg, 0, -1);

  Local_Neuroseg_Swc_Fprint(fp, locseg1, 2, -1);
  Local_Neuroseg_Swc_Fprint(fp, locseg2, 4, -1);
  
  fclose(fp);

  Locseg_Chain_Connection_Test(chain1, chain2, NULL, 1.0, &conn, NULL);
  Print_Neurocomp_Conn(&conn);
#endif

#if 0
  double z_scale = 0.5375;

  Locseg_Chain *chain[11];
  char file_path[100];
  
  int i, j;
  for (i = 0; i < 11; i++) {
    sprintf(file_path, "../data/mouse_single_org/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    Locseg_Chain_Scale_Z(chain[i], z_scale);
  }

  Neurocomp_Conn conn;
  for (i = 0; i < 11; i++) {
    for (j = 0; j < 11; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test_P(chain[i], chain[j], &conn) < 5.0) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  double z_scale = 0.5375;

  int n = 278;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/mouse_single_org/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    Locseg_Chain_Scale_Z(chain[i], z_scale);
  }

  Locseg_Chain *hook = chain[19];

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    if (i != 19) {
      if (Locseg_Chain_Connection_Test_P(hook, chain[i], &conn) < 5.0) {
	printf("19 -> %d \n", i);
	Print_Neurocomp_Conn(&conn);
      }
    }
  }
#endif
  
#if 0
  double z_scale = 0.32;
  Locseg_Chain *chain[17];
  char file_path[100];
  
  int i, j;
  for (i = 0; i < 17; i++) {
    sprintf(file_path, "../data/fly_neuron_n1/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    Locseg_Chain_Scale_Z(chain[i], z_scale);
  }

  Neurocomp_Conn conn;
  for (i = 0; i < 17; i++) {
    for (j = 0; j < 17; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test_P(chain[i], chain[j], &conn) < 5.0) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  double z_scale = 0.1400;
  //double z_scale = 1.0;

  int n = 12;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/ct017/test6/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    Locseg_Chain_Scale_Z(chain[i], z_scale);
  }

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test_P(chain[i], chain[j], &conn) < 10.0) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  //double z_scale = 0.1400;
  double z_scale = 1.20;

  int n = 5;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/ct017/test7/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    Locseg_Chain_Scale_Z(chain[i], z_scale);
  }

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test_P(chain[i], chain[j], &conn) < 10.0) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  double z_scale = 1.20;
  //double z_scale = 1.0;
  Stack *stack = Read_Stack("../data/lobster_neuron_org.tif");

  int n = 5;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/ct017/test7/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    //Locseg_Chain_Scale_Z(chain[i], z_scale);
  }
  
  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();
  ctw->z_scale = z_scale;

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test(chain[i], chain[j], stack, 1.0,
					 &conn, ctw)) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  Locseg_Chain *chain = Read_Locseg_Chain("../data/ct017/test6/chain7.bn");
  Local_Neuroseg *locseg = Locseg_Chain_Tail_Seg(chain);
  Print_Local_Neuroseg(locseg);

  Stack *stack = Read_Stack("../data/mouse_neuron_sp2.tif");
  double *profile = Local_Neuroseg_Height_Profile(locseg, stack, 1.0, 
						  11, STACK_FIT_CORRCOEF,
						  NULL);
  darray_write("../data/profile1.bn", profile, 11);
#endif

#if 0
  Locseg_Chain *chain = Read_Locseg_Chain("../data/ct017/test6/chain7.bn");
  Local_Neuroseg *locseg = Locseg_Chain_Tail_Seg(chain);
  Print_Local_Neuroseg(locseg);

  Stack *stack = Read_Stack("../data/mouse_neuron_sp2.tif");

  int n;
  double record[11];
  Locseg_Chain *chain2 = Local_Neuroseg_Push(locseg, stack, 
					     1.0, STACK_FIT_OUTER_SIGNAL, 
					     record, &n);

  Print_Locseg_Chain(chain2);

  Write_Locseg_Chain("../data/test.tb", chain2);

  return 1;

  Locseg_Chain *chain3 = Read_Locseg_Chain("../data/ct017/test6/chain6.bn");
  
  Locseg_Chain_Scale_Z(chain2, 0.14);
  Locseg_Chain_Scale_Z(chain3, 0.14);
  Neurocomp_Conn conn;
  Locseg_Chain_Connection_Test(chain2, chain3, NULL, 1.0, &conn, NULL);
  Print_Neurocomp_Conn(&conn);
#endif

#if 0
  Locseg_Chain *chain = Read_Locseg_Chain("../data/ct017/test6/chain9.bn");
  Local_Neuroseg *locseg = Locseg_Chain_Tail_Seg(chain);
  //Local_Neuroseg *locseg = Locseg_Chain_Head_Seg(chain);
  //Flip_Local_Neuroseg(locseg);

  Print_Local_Neuroseg(locseg);

  Stack *stack = Read_Stack("../data/mouse_neuron_sp2.tif");

  int n;
  double record[11];
  Locseg_Chain *chain2 = Local_Neuroseg_Push(locseg, stack, 
					     1.0, STACK_FIT_OUTER_SIGNAL, 
					     record, &n);

  Print_Locseg_Chain(chain2);

  Write_Locseg_Chain("../data/test.bn", chain2);

  return 1;

  Locseg_Chain *chain3 = Read_Locseg_Chain("../data/ct017/test6/chain9.bn");
  
  Locseg_Chain_Scale_Z(chain2, 0.14);
  Locseg_Chain_Scale_Z(chain3, 0.14);
  Neurocomp_Conn conn;
  Locseg_Chain_Connection_Test(chain3, chain2, stack, 1.0, &conn, NULL);
  Print_Neurocomp_Conn(&conn);
#endif

#if 0
  double z_scale = 0.1400;
  //double z_scale = 1.0;
  Stack *stack = Read_Stack("../data/mouse_neuron_sp2.tif");

  int n = 12;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/ct017/test6/chain%d.bn", i);
    chain[i] = Read_Locseg_Chain(file_path);
    //Locseg_Chain_Scale_Z(chain[i], z_scale);
  }
  
  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();
  ctw->z_scale = 0.14;

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test(chain[i], chain[j], stack, 1.0,
					 &conn, ctw)) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  //double z_scale = 0.32;
  //double z_scale = 1.0;
  Stack *stack = Read_Stack("../data/fly_neuron_n1.tif");

  int n = 17;
  Locseg_Chain *chain[n];
  char file_path[100];
  
  int i, j;
  
  for (i = 0; i < n; i++) {
    sprintf(file_path, "../data/fly_neuron_n1/chain%d.tb", i);
    chain[i] = Read_Locseg_Chain(file_path);
    //Locseg_Chain_Scale_Z(chain[i], z_scale);
  }
  
  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();
  ctw->resolution[0] = 0.32;
  ctw->resolution[1] = 0.32;
  ctw->resolution[2] = 1.0;

  Neurocomp_Conn conn;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i != j) {
	if (Locseg_Chain_Connection_Test(chain[i], chain[j], stack, 1.0,
					 &conn, ctw)) {
	  printf("%d -> %d \n", i, j);
	  Print_Neurocomp_Conn(&conn);
	}
      }
    }
  }
#endif

#if 0
  Locseg_Chain *chain = Read_Locseg_Chain("../data/fly_neuron_n1/chain3.bn");
  Local_Neuroseg *locseg = Locseg_Chain_Tail_Seg(chain);
  //Flip_Local_Neuroseg(locseg);
  Print_Local_Neuroseg(locseg);

  Stack *stack = Read_Stack("../data/fly_neuron_n1.tif");

  int n;
  double record[11];
  Locseg_Chain *chain2 = Local_Neuroseg_Push(locseg, stack, 
					     1.0, STACK_FIT_CORRCOEF, 
					     record, &n);

  Print_Locseg_Chain(chain2);

  Write_Locseg_Chain("../data/test.bn", chain2);

  return 1;

  Locseg_Chain *chain3 = Read_Locseg_Chain("../data/fly_neuron_n1/chain0.bn");
  
  Locseg_Chain_Scale_Z(chain2, 0.32);
  Locseg_Chain_Scale_Z(chain3, 0.32);
  Neurocomp_Conn conn;
  Locseg_Chain_Connection_Test(chain2, chain3, stack, 1.0, &conn, NULL);
  Print_Neurocomp_Conn(&conn);
#endif

  return 0;
}
Beispiel #27
0
/*
 * trace_neuron - trace neuron from given seeds
 *
 * trace_neuron [!wtr] seed_file -Dsave_dir
 *   -r: write intermediate results
 *
 */
int main(int argc, char* argv[])
{
  static char *Spec[] = {
    "[!wtr] [-canvas <string>] [-mask <string>] [-res <string>] [-minr <int>]",
    "-minlen <double>",
    " <image:string> -S<string> -D<string>",
    NULL};
  
  Process_Arguments(argc, argv, Spec, 1);
  
  char *dir = Get_String_Arg("-D");
  
  char file_path[100];
  sprintf(file_path, "%s/%s", dir, Get_String_Arg("-S"));
  printf("%s\n", file_path);

  Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(file_path);

  int idx;

  sprintf(file_path, "%s/%s.bn", dir, "max_r");
  double max_r;
  int tmp;
  if (fexist(file_path)) {
    darray_read2(file_path, &max_r, &tmp);
  } else {
    max_r = darray_max(seed->values, seed->size, &idx);
  }

  printf("%g\n", max_r);

  max_r *= 1.5;

  /*
  sprintf(file_path, "%s/%s", dir, "soma0.bn");
  if (!fexist(file_path)) {
    max_r *= 2.0;
  }
  */
   
  Set_Neuroseg_Max_Radius(max_r);

  Stack *signal = Read_Stack(Get_String_Arg("image"));

  dim_type dim[3];
  dim[0] = signal->width;
  dim[1] = signal->height;
  dim[2] = signal->depth;
  /* 
  IMatrix *chord = Make_IMatrix(dim, 3);
  
  Stack *code = Make_Stack(GREY16, 
			   signal->width, signal->height, signal->depth);
  */
  Rgb_Color color;
  Set_Color(&color, 255, 0, 0);

  Stack *canvas = NULL;

  char trace_file_path[100];
  sprintf(trace_file_path, "%s/%s", dir, Get_String_Arg("-canvas"));
  
  if (fexist(trace_file_path) == 1) {
    canvas = Read_Stack((char *) trace_file_path);
  } else {
    canvas = Copy_Stack(signal);
    Stretch_Stack_Value_Q(canvas, 0.999);
    Translate_Stack(canvas, COLOR, 1);
  }

  Stack *traced = NULL;
  
  char trace_mask_path[100];
  sprintf(trace_mask_path, "%s/%s", dir, Get_String_Arg("-mask"));

  if (fexist(trace_mask_path) == 1) {
    traced = Read_Stack((char *) trace_mask_path);
  } else {
    traced = Make_Stack(GREY, signal->width, signal->height, signal->depth);
    One_Stack(traced);
  }
  

  //Object_3d *obj = NULL;
  int seed_offset = -1;

  Neurochain *chain = NULL;

  double z_scale = 1.0;

  if (Is_Arg_Matched("-res")) {
    sprintf(file_path, "%s", Get_String_Arg("-res"));

    if (fexist(file_path)) {
      double res[3];
      int length;
      darray_read2(file_path, res, &length);
      if (res[0] != res[1]) {
	perror("Different X-Y resolutions.");
	TZ_ERROR(ERROR_DATA_VALUE);
      }
      z_scale = res[0] / res[2];
    }
  }

  //sprintf(file_path, "%s/%s", dir, Get_String_Arg("-M"));
  //Stack *stack = Read_Stack(file_path);

  tic();

  FILE *fp = NULL;
  char chain_file_path[100];
  char vrml_file_path[100];

  double min_chain_length = 25.0;

  if (Is_Arg_Matched("-minlen")) {
    min_chain_length = Get_Double_Arg("-minlen");
  }

  int *indices = iarray_malloc(seed->size);
  double *values = darray_malloc(seed->size);
  int i;

  Local_Neuroseg *locseg = (Local_Neuroseg *) 
    malloc(seed->size * sizeof(Local_Neuroseg));

  int index = 0;
  for (i = 0; i < seed->size; i++) {
    printf("-----------------------------> seed: %d / %d\n", i, seed->size);
    indices[i] = i;
    index = i;
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    double width = seed->values[index];

    chain = New_Neurochain();

    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);

    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(locseg[i].seg), width, width, 12.0, 
		 0.0, 0.0, 0.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] *= z_scale;
    
    Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER);
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    values[i] = Local_Neuroseg_Orientation_Search_C(&(locseg[i]), signal, z_scale, &fs);
  }

  darray_qsort(values, indices, seed->size);

  /*
  for (i = 0; i < seed->size; i++) {
    indices[i] = i;
  }
  darraycpy(values, seed->values, 0, seed->size);
  darray_qsort(values, indices, seed->size);
  */

  int counter = 0;

  //  for (i = seed->size - 1; i >= seed->size - 231; i--) {
  for (i = seed->size - 1; i >= 0; i--) {
    index = indices[i];

    printf("-----------------------------> seed: %d / %d\n", i, seed->size);
    
    sprintf(chain_file_path, "%s/chain%d.bn", dir, index);
    sprintf(vrml_file_path, "%s/chain%d.wrl", dir, index);

    if (fexist(chain_file_path) == 1) {
      chain = Read_Neurochain(chain_file_path);
      if (Neurochain_Geolen(chain) >= min_chain_length) {
	Write_Neurochain_Vrml(vrml_file_path, chain);
	Neurochain_Label(canvas, chain, z_scale);
	Neurochain_Erase_E(traced, chain, z_scale, 0,
			   Neurochain_Length(chain, FORWARD),
			   1.5, 0.0);
      }

      Free_Neurochain(chain);
      printf("chain exists\n");
      continue;
    }
    
    
    int x = (int) seed->points[index][0];
    int y = (int) seed->points[index][1];
    int z = (int) seed->points[index][2];

    if (*STACK_PIXEL_8(traced, x, y, z, 0) == 0) {
      printf("traced \n");
      continue;
    }

    double width = seed->values[index];

    if (width > max_r) {
      printf("too thick\n");
      continue;
    }
    
    if (Is_Arg_Matched("-minr")) {
      int max_level = (int) (width + 0.5);
      if (max_level <= Get_Int_Arg("-minr")) {
	printf("too thin\n");
	continue;
      }
    }
    /*
    seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,
				    signal->depth);
    */

    chain = New_Neurochain();
    /*
    Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, 
				max_level + 1);

    Voxel_t v;
    v[0] = x;
    v[1] = y;
    v[2] = z;

    Stack *tmp_stack = Copy_Stack(stack);
    obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, 
				       max_level);
    Free_Stack(tmp_stack);

    Print_Object_3d_Info(obj);
    
    double vec[3];
    Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale);

    double theta, psi;
    Geo3d_Vector obj_vec;
    Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]);

    Geo3d_Vector_Orientation(&obj_vec, &theta, &psi);
    */

    /*
    if (width < 3.0) {
      width += 0.5;
    }
    Set_Neuroseg(&(chain->locseg.seg), width, width, 12.0, 
		 0.0, 0.0, 0.0);

    double cpos[3];
    cpos[0] = x;
    cpos[1] = y;
    cpos[2] = z;
    cpos[2] *= z_scale;
    
    //Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_BOTTOM);
    Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_CENTER);
    Stack_Fit_Score fs;
    fs.n = 1;
    fs.options[0] = 1;
    Local_Neuroseg_Orientation_Search_C(&(chain->locseg), signal, z_scale,
					&fs); 
    //fs.options[0] = 1;
    */

    Copy_Local_Neuroseg(&(chain->locseg), &(locseg[index]));
    Neurochain *chain_head = chain;
    
    
    if (Initialize_Tracing(signal, chain, NULL, z_scale) >= MIN_SCORE) {
      if ((Neuroseg_Hit_Traced(&(chain->locseg), traced, z_scale) == FALSE) &&
	  (chain->locseg.seg.r1 < max_r) && 
	  (chain->locseg.seg.r2 < max_r)) {
	//Initialize_Tracing(signal, chain, NULL, z_scale);
	chain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 500);

	//Neurochain *chain_head = Neurochain_Head(chain);
	chain_head = Neurochain_Remove_Overlap_Segs(chain);
	chain_head = Neurochain_Remove_Turn_Ends(chain_head, 0.5);
	/*
	if (i == seed->size - 231) {
	  Print_Neurochain(chain_head);
	}
	*/

	fp = fopen(chain_file_path, "w");
	Neurochain_Fwrite(chain_head, fp);
	fclose(fp);
	if (Neurochain_Geolen(chain_head) >= min_chain_length) {
	  Write_Neurochain_Vrml(vrml_file_path, chain_head);

	  Neurochain_Erase_E(traced, chain_head, z_scale, 0,
			     Neurochain_Length(chain_head, FORWARD),
			     1.5, 0.0);
	  Neurochain_Label(canvas, chain_head, z_scale);

	  counter += Neurochain_Length(chain_head, FORWARD);
	  if (counter > 500) {
	    if (Is_Arg_Matched("-r")) {
	      Write_Stack((char *) trace_mask_path, traced);
	    }
	    
	    if (Is_Arg_Matched("-r")) {
	    Write_Stack((char *) trace_file_path, canvas);
	    }

	    counter = 0;
	  }
	}
      }
    }

    Free_Neurochain(chain_head);

    //Kill_Object_3d(obj);
  }

  Write_Stack((char *) trace_file_path, canvas);
  if (Is_Arg_Matched("-r")) {
    Write_Stack((char *) trace_mask_path, traced);
  }

  Kill_Geo3d_Scalar_Field(seed);

  printf("Time passed: %lld\n", toc());

  
  return 0;
}