Exemple #1
0
int main(int argc, char* argv[])
{ int n_rows;
  Measurements *table;
  double mean;
  
  printf("-----------------                                                             \n"
         " Classify test 2                                                              \n"
         "-----------------                                                             \n"
         "                                                                              \n"
         "  Uses a length threshold to seperate hair/microvibrissae from main whiskers. \n"
         "  A histogram method is used to measure the expected number of whiskers per   \n"
         "  frame.  A range of thresholds is examined.                                  \n"
         "--                                                                            \n");

  Process_Arguments( argc, argv, Spec, 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"));
  
  { int thresh;
    for( thresh = 0; thresh < 400; thresh ++ )
    { int count, argmax;
      Measurements_Table_Label_By_Threshold( table, n_rows, 0 /*length*/, thresh, 1/*use gt*/ );
      count = Measurements_Table_Best_Frame_Count_By_State( table, n_rows, 1, &argmax );
      printf("%4d  %3d  %3d\n", thresh, count, argmax );
    }
  }
  Free_Measurements_Table(table);
}
Exemple #2
0
int main(int argc, char * argv[])
{
  auto begin = std::chrono::high_resolution_clock::now();
  
  static char *Spec[] = { "[-r <int(20)>] [-d <int(2)>] [-l <int(1)>] [-t <int(100)>] [-hmd] [-hmr] [-mi] [-v] -in <inputFile> -out <outputFile>", NULL };
  
  ProjectionMethod::ParaSet parameter (argc,argv,Spec);
  
  std::string outputString = Get_String_Arg("-out");
  
  ProjectionMethod::ProjectionAlgorithm imgProjection (Get_String_Arg("-in"));
  imgProjection.SetParameters (parameter);
  imgProjection.ProjectImageStack();
  imgProjection.DrawProjection(outputString);
  
  if (parameter.printHeightMap == true) {
    imgProjection.DrawDownsampledHeightMap(outputString);
  }
  if (parameter.printRealHeightMap == true) {
    imgProjection.DrawInterpolatedHeightMap(outputString);
  }
  
  if (parameter.verbose == true) {
    auto end = std::chrono::high_resolution_clock::now();
    auto dur = end - begin;
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
    std::cout << "Runtime: " << ms << " ms"<< std::endl;
  }
  
  return 0;
}
Exemple #3
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;
}
Exemple #4
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;
}
Exemple #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;
}
Exemple #6
0
int main(int argc, char *argv[])
{
  static char *Spec[] = {"<input:string>", NULL};
  Process_Arguments(argc, argv, Spec, 1);


  String_Workspace *sw = New_String_Workspace();
  FILE *fp = fopen(Get_String_Arg("input"), "r");
  char *line;
  int start = 10000;
  int end = 0;

  while((line = Read_Line(fp, sw)) != NULL) {
    int value = String_First_Integer(line);
    if (value < start) {
      start = value;
    }
    if (value > end) {
      end = value;
    }
  }
  fclose(fp);

  printf("%d %d\n", start, end);

  return 0;
}
Exemple #7
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;
}
Exemple #8
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;
}
Exemple #9
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;
}
Exemple #10
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;
}
Exemple #11
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;
}
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);
}
int main(int argc, char *argv[])
{
  static char *Spec[] = {"[-outfolder <string>] [-redgreenimagefolder <string>]",
    "[-blueimagefolder <string>]", NULL};
  Process_Arguments(argc, argv, Spec, 1);

  int nredgreenimage;
  int nblueimage;
  char** redgreenfilepath = get_image_paths(Get_String_Arg("-redgreenimagefolder"), ".*\\.lsm", &nredgreenimage);
  char** bluefilepath = get_image_paths(Get_String_Arg("-blueimagefolder"), ".*\\.lsm", &nblueimage);


  if (redgreenfilepath == NULL || bluefilepath == NULL) {
    printf("no image!\n");
    return 1;
  } else if (nredgreenimage != nblueimage) {
    printf("image number don't match, abort! red: %d, blue: %d\n", nredgreenimage, nblueimage);
    return 1;
  } else {
    printf("%d images\n", nblueimage);
  }

  qsort(redgreenfilepath, nblueimage, sizeof(char*), compare_string_by_num);
  qsort(bluefilepath, nblueimage, sizeof(char*), compare_string_by_num);

  char prefix[500];
  char outfilepath[500];
  char filenamenoext[500];
  int k;
  for (k = 0; k < nblueimage; ++k) {
    strcpy(prefix, Get_String_Arg("-outfolder"));
    strcpy(filenamenoext, redgreenfilepath[k]);
    char *end = strrchr(filenamenoext, '.');
    if (end != NULL) {
      *end = '\0';
    }
    else {
      printf("something stange happens..\n");
    }
    char *start = strrchr(filenamenoext, '/');
    if (start != NULL) {
      start++;
    }
    else {
      start = filenamenoext;
    }
    if (prefix[strlen(prefix)-1]=='/') {
      sprintf(outfilepath, "%s%s.tif", prefix, start);
    } else {
      sprintf(outfilepath, "%s/%s.tif", prefix, start);
    }

    FILE* fp = open_file(outfilepath, "wb");
    fclose(fp);

    Mc_Stack* mc_stack1 = Read_Mc_Stack(redgreenfilepath[k], -1);
    Mc_Stack* mc_stack2 = Read_Mc_Stack(bluefilepath[k], -1);

    Mc_Stack* mc_stack = Combine_Mc_Stack(mc_stack1, mc_stack2);
    Write_Mc_Stack(outfilepath, mc_stack, NULL);
    printf("Write %s done!\n", outfilepath);
    Kill_Mc_Stack(mc_stack1);
    Kill_Mc_Stack(mc_stack2);
    Kill_Mc_Stack(mc_stack);
  }

  free(redgreenfilepath);
  free(bluefilepath);

  return 0;
}
Exemple #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;
}
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);
}
const char* ZArgumentProcessor::getStringArg(const char *arg, int index)
{
  return Get_String_Arg(const_cast<char*>(arg), index);
}
Exemple #17
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;
}
Exemple #18
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;
}
Exemple #19
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;
}
Exemple #20
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;
}
Exemple #21
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;
}
Exemple #22
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;
}
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;
}
Exemple #24
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;
}