static MRI * create_distance_transforms(MRI *mri_source, MRI *mri_target, MRI *mri_all_dtrans, float max_dist, GCA_MORPH *gcam) { MRI *mri_dtrans, *mri_atlas_dtrans ; int frame ; char fname[STRLEN] ; mri_all_dtrans = MRIallocSequence(mri_source->width, mri_source->height, mri_source->depth, MRI_FLOAT, NDTRANS_LABELS) ; MRIcopyHeader(mri_target, mri_all_dtrans) ; for (frame = 0 ; frame < NDTRANS_LABELS ; frame++) { printf("creating distance transform for %s, frame %d...\n", cma_label_to_name(dtrans_labels[frame]), frame) ; mri_dtrans = MRIdistanceTransform(mri_source, NULL, dtrans_labels[frame], max_dist, DTRANS_MODE_SIGNED, NULL) ; sprintf(fname, "%s.mgz", cma_label_to_name(dtrans_labels[frame])) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_dtrans, fname) ; MRIcopyFrame(mri_dtrans, mri_all_dtrans, 0, frame) ; mri_atlas_dtrans = MRIdistanceTransform(mri_target, NULL, dtrans_labels[frame], max_dist, DTRANS_MODE_SIGNED, NULL) ; MRInormalizeInteriorDistanceTransform(mri_atlas_dtrans, mri_dtrans, mri_atlas_dtrans) ; GCAMsetTargetDistancesForLabel(gcam, mri_target, mri_atlas_dtrans, dtrans_labels[frame]); MRIfree(&mri_dtrans) ; MRIfree(&mri_atlas_dtrans) ; } return(mri_all_dtrans) ; }
static int find_debug_node(GCA_MORPH *gcam, int origx, int origy, int origz) { int x, y, z, xmin, ymin, zmin ; double d, dmin ; GCA_MORPH_NODE *gcamn ; dmin = 1e10 ; xmin = ymin = zmin = 0 ; for (x = 0 ; x < gcam->width ; x++) { for (y = 0 ; y < gcam->height ; y++) { for (z = 0 ; z < gcam->depth ; z++) { gcamn = &gcam->nodes[x][y][z] ; d = sqrt(SQR(gcamn->origx-origx) + SQR(gcamn->origy-origy) + SQR(gcamn->origz-origz)) ; if (d < dmin) { dmin = d ; xmin = x ; ymin = y ; zmin = z ; } } } } gcamn = &gcam->nodes[xmin][ymin][zmin] ; printf("Talairach voxel (%d, %d, %d) maps to node (%d, %d, %d) %s --> (%2.1f, %2.1f, %2.1f)\n", origx, origy, origz, xmin, ymin, zmin, cma_label_to_name(gcamn->label), gcamn->x, gcamn->y, gcamn->z) ; return(NO_ERROR) ; }
/*---------------------------------------------------------------------- Parameters: Description: ----------------------------------------------------------------------*/ static int get_option(int argc, char *argv[]) { int nargs = 0 ; char *option ; option = argv[1] + 1 ; /* past '-' */ if (strcmp("cras", option) == 0) cras = 1; else if (strcmp("scaleup", option) == 0) scaleup_flag = 1 ; else if (strcmp("segmentation", option) == 0) { segmentation_flag = atoi(argv[2]) ; nargs = 1 ; fprintf(stderr,"using segmentation %d (%s) as label...\n", segmentation_flag, cma_label_to_name(segmentation_flag)) ; } else if (strcmp("coords", option) == 0) { coords = 1 ; fprintf(stderr,"printing out coordinates with values\n") ; } else if (strcmp("erode", option) == 0) { erode = atoi(argv[2]) ; nargs = 1; fprintf(stderr,"eroding segmentation label %d times (must specify label with -segmentaiton)\n", erode); } else { switch (toupper(*option)) { case 'S': surface_dir = argv[2] ; hemi = argv[3] ; printf("sampling from midpoint of cortical ribbon in %s (hemi=%s)\n", surface_dir, hemi) ; nargs = 2 ; break ; case 'Q': quiet = 1 ; break ; case 'A': annot_prefix = argv[2] ; nargs = 1 ; fprintf(stderr,"reading annotation file, and outputting with prefix %s ...\n", annot_prefix) ; break ; case 'L': log_fname = argv[2] ; nargs = 1 ; fprintf(stderr, "logging results to %s\n", log_fname) ; break ; case 'U': usage_exit(0) ; break ; default: fprintf(stderr, "unknown option %s\n", argv[1]) ; exit(1) ; break ; } } return(nargs) ; }
void LayerVolumeTrack::UpdateData() { if (!m_volumeSource->GetEmbeddedColorTable()) { cerr << "Did not find color table in track volume.\n"; m_ctabStripped = CTABdeepCopy(this->GetProperty()->GetLUTCTAB()); } else m_ctabStripped = CTABdeepCopy(m_volumeSource->GetEmbeddedColorTable()); if (m_ctabStripped) { MRI* mri = m_volumeSource->GetMRI(); QList<int> list; for (int i = 0; i < mri->nframes; i++) list << mri->frames[i].label; int nTotalCount; int nValid = 0; CTABgetNumberOfTotalEntries( m_ctabStripped, &nTotalCount ); for ( int i = 0; i < nTotalCount; i++ ) { CTABisEntryValid( m_ctabStripped, i, &nValid ); if (nValid) { if (list.contains(i)) { // update name QString name = mri->frames[list.indexOf(i)].name; if (name.isEmpty()) name = cma_label_to_name(i); strcpy(m_ctabStripped->entries[i]->name, qPrintable(name)); } else { // remove this entry free(m_ctabStripped->entries[i]); m_ctabStripped->entries[i] = 0; } } } } RebuildActors(); }
/*---------------------------------------------------------------------- Parameters: Description: ----------------------------------------------------------------------*/ static int get_option(int argc, char *argv[]) { int nargs = 0 ; char *option ; option = argv[1] + 1 ; /* past '-' */ if (!stricmp(option, "-help")) print_help() ; else if (!stricmp(option, "-version")) print_version() ; else if (!stricmp(option, "sdir")) { strcpy(sdir, argv[2]) ; nargs = 1 ; printf("using %s as SUBJECTS_DIR\n", sdir) ; } else if (!stricmp(option, "label")) { label_index = atoi(argv[2]) ; nargs = 1 ; printf("using label %s (%d) and writing output in label format\n", cma_label_to_name(label_index), label_index) ; } else if (!stricmp(option, "surf")) { surf_name = argv[2] ; nargs = 1 ; printf("using %s as surface name\n", surf_name) ; } else if (!stricmp(option, "mask")) { mask_fname = argv[2] ; mask_val = atoi(argv[3]) ; nargs = 2 ; printf("using %d as a mask in %s\n", mask_val, mask_fname) ; } else if (!stricmp(option, "vol2surf")) { sample_from_vol_to_surf = 1 ; printf("sampling from volume to surface...\n") ; } else if (!stricmp(option, "close")) { nclose = atoi(argv[2]) ; printf("applying %dth order morphological close to label\n", nclose) ; nargs = 1 ; } else if (!stricmp(option, "fix")) { fix_topology = atoi(argv[2]) ; printf("fixing topology of all labels smaller " "than %d vertices\n",fix_topology); nargs = 1 ; } else if (!stricmp(option, "replace")) { replace_label = atoi(argv[2]) ; nargs = 1 ; printf("replacing label %s (%d) with deeper ones\n", cma_label_to_name(replace_label), replace_label) ; } else if (!stricmp(option, "trans")) { if (ntrans >= MAX_TRANS) ErrorExit(ERROR_NOMEMORY, "%s: too many translations (%d)\n", Progname,ntrans); trans_in[ntrans] = atof(argv[2]) ; trans_out[ntrans] = atof(argv[3]) ; nargs = 2 ; printf("translating %s (%d) to %s (%d)\n", cma_label_to_name(trans_in[ntrans]), trans_in[ntrans], cma_label_to_name(trans_out[ntrans]), trans_out[ntrans]) ; ntrans++ ; } else if (!stricmp(option, "projmm") || !stricmp(option, "proj")) { proj_mm = atof(argv[2]) ; nargs = 1 ; printf("projecting %2.2f mm along surface normal\n", proj_mm) ; } else if (!stricmp(option, "projfrac")) { proj_frac = atof(argv[2]) ; nargs = 1 ; printf("projecting %2.2f %% along surface normal\n", proj_frac) ; } else if (!stricmp(option, "file")) { translation_fname = argv[2] ; nargs = 1 ; printf("using %s as translation fname\n", sdir) ; } else if (!stricmp(option, "ct")) { color_table_fname = argv[2] ; nargs = 1 ; printf("embedding color table %s into output annot file\n", color_table_fname) ; translation_fname = color_table_fname ; } else switch (toupper(*option)) { case 'V': if (argc==2) { print_help(); exit(1); } Gdiag_no = atoi(argv[2]) ; nargs = 1 ; break ; case 'F': mode_filter = atoi(argv[2]) ; nargs = 1 ; printf("applying mode filter %d times to parcellation\n", mode_filter) ; break ; case 'A': avgs = atoi(argv[2]) ; nargs = 1 ; printf("smoothing surface %d times\n", avgs) ; break ; case 'W': wsize = atoi(argv[2]) ; nargs = 1 ; printf("using window size=%d for sampling\n", wsize) ; break ; case 'T': thickness_name = argv[2] ; nargs = 1 ; printf("using thickness file %s\n", thickness_name) ; break ; case 'U': if (argc==2) { print_help(); exit(1); } unknown_label = atoi(argv[2]) ; printf("changing largest connected unknown region to label %d\n", unknown_label) ; nargs = 1 ; break ; default: fprintf(stderr, "unknown option %s\n", argv[1]) ; exit(1) ; break ; } return(nargs) ; }
int main(int argc, char *argv[]) { char **av, *in_fname, *out_fname ; int ac, nargs, i, label ; MRI *mri_in, *mri_out, *mri_kernel, *mri_smoothed ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_extract_label.c,v 1.13 2011/03/02 00:04:15 nicks Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 4) usage_exit() ; in_fname = argv[1] ; out_fname = argv[argc-1] ; printf("reading volume from %s...\n", in_fname) ; mri_in = MRIread(in_fname) ; if (!mri_in) ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname, in_fname) ; if (out_like_fname) { MRI *mri_tmp = MRIread(out_like_fname) ; if (!mri_tmp) ErrorExit (ERROR_NOFILE, "%s: could not read template volume from %s", out_like_fname) ; mri_out = MRIalloc(mri_tmp->width, mri_tmp->height, mri_tmp->depth, mri_tmp->type) ; /* MRIcopyHeader(mri_tmp, mri_out) ;*/ MRIfree(&mri_tmp) ; } else mri_out = MRIclone(mri_in, NULL) ; for (i = 2 ; i < argc-1 ; i++) { label = atoi(argv[i]) ; printf("extracting label %d (%s)\n", label, cma_label_to_name(label)) ; extract_labeled_image(mri_in, transform, label, mri_out) ; } if (!FZERO(sigma)) { printf("smoothing extracted volume...\n") ; mri_kernel = MRIgaussian1d(sigma, 10*sigma) ; mri_smoothed = MRIconvolveGaussian(mri_out, NULL, mri_kernel) ; MRIfree(&mri_out) ; mri_out = mri_smoothed ; } /* removed for gcc3.3 * vsprintf(out_fname, out_fname, (va_list) &label) ; */ if (dilate > 0) { int i ; printf("dilating output volume %d times...\n", dilate) ; for (i = 0 ; i < dilate ; i++) MRIdilate(mri_out, mri_out) ; } if (erode > 0) { int i ; printf("eroding output volume %d times...\n", erode) ; for (i = 0 ; i < erode ; i++) MRIerode(mri_out, mri_out) ; } printf("writing output to %s.\n", out_fname) ; MRIwrite(mri_out, out_fname) ; if (exit_none_found && (nvoxels == 0)) { printf("No voxels with specified label were found!\n"); exit(1); } exit(0) ; return(0) ; /* for ansi */ }
/*---------------------------------------------------------------------- Parameters: Description: ----------------------------------------------------------------------*/ static int get_option(int argc, char *argv[]) { int nargs = 0 ; char *option ; option = argv[1] + 1 ; /* past '-' */ if (!stricmp(option, "SPACING")) { spacing = atof(argv[2]) ; nargs = 1 ; printf("spacing pdfs every %2.1f mm\n", spacing) ; } else if (!stricmp(option, "NODE_SPACING")) { parms.node_spacing = atof(argv[2]) ; nargs = 1 ; printf("spacing nodes every %2.1f mm\n", parms.node_spacing) ; } else if (!stricmp(option, "BINARIZE")) { binarize = 1 ; binarize_in = atoi(argv[2]) ; binarize_out = atoi(argv[3]) ; nargs = 2 ; printf("binarizing segmentation values, setting input %d to output %d\n", binarize_in, binarize_out) ; } else if (!stricmp(option, "NOMRF")) { gca_flags |= GCA_NO_MRF ; printf("not computing MRF statistics...\n") ; } else if (!stricmp(option, "MASK")) { mask_fname = argv[2] ; nargs = 1 ; printf("using MR volume %s to mask input volume...\n", mask_fname) ; } else if (!stricmp(option, "DEBUG_NODE")) { Ggca_x = atoi(argv[2]) ; Ggca_y = atoi(argv[3]) ; Ggca_z = atoi(argv[4]) ; nargs = 3 ; printf("debugging node (%d, %d, %d)\n", Ggca_x,Ggca_y,Ggca_z) ; } else if (!stricmp(option, "DEBUG_VOXEL")) { Gx = atoi(argv[2]) ; Gy = atoi(argv[3]) ; Gz = atoi(argv[4]) ; nargs = 3 ; printf("debugging voxel (%d, %d, %d)\n", Gx,Gy,Gz) ; } else if (!stricmp(option, "DEBUG_LABEL")) { Ggca_label = atoi(argv[2]) ; nargs = 1 ; printf("debugging label %s (%d)\n", cma_label_to_name(Ggca_label), Ggca_label) ; } else if (!stricmp(option, "DEBUG_NBR")) { Ggca_nbr_label = atoi(argv[2]) ; nargs = 1 ; printf("debugging nbr label %s (%d)\n", cma_label_to_name(Ggca_nbr_label), Ggca_nbr_label) ; } else if (!stricmp(option, "INSERT")) { insert_fname = argv[2] ; insert_label = atoi(argv[3]) ; nargs = 2 ; printf("inserting non-zero vals from %s as label %d...\n", insert_fname,insert_label); } else if (!stricmp(option, "T1")) { strcpy(T1_name, argv[2]) ; nargs = 1 ; printf("reading T1 data from subject's mri/%s directory\n", T1_name) ; } else if (!stricmp(option, "PARC_DIR") || !stricmp(option, "SEG_DIR") || !stricmp(option, "SEG") || !stricmp(option, "SEGMENTATION")) { seg_dir = argv[2] ; nargs = 1 ; printf("reading segmentation from subject's mri/%s directory\n", seg_dir) ; } else if (!stricmp(option, "XFORM")) { xform_name = argv[2] ; nargs = 1 ; printf("reading xform from %s\n", xform_name) ; } else if (!stricmp(option, "NOXFORM")) { xform_name = NULL ; printf("disabling application of xform...\n") ; } else if (!stricmp(option, "SDIR")) { strcpy(subjects_dir, argv[2]) ; nargs = 1 ; printf("using %s as subjects directory\n", subjects_dir) ; } else if (!stricmp(option, "SMOOTH")) { smooth = atof(argv[2]) ; if (smooth <= 0 || smooth > 1) ErrorExit(ERROR_BADPARM, "%s: smoothing parameter %2.1f must be in [0,1]\n", Progname, smooth) ; nargs = 1 ; printf("imposing %2.1f smoothing on conditional statistics\n", smooth) ; } else switch (toupper(*option)) { case 'S': scale = atof(argv[2]) ; printf("scaling all volumes by %2.3f after reading...\n", scale) ; nargs = 1 ; break ; case 'A': navgs = atoi(argv[2]) ; printf("applying %d mean filters to classifiers after training\n",navgs); nargs = 1 ; break ; case 'H': histo_fname = argv[2] ; nargs = 1 ; printf("writing histogram of classes/voxel to %s\n", histo_fname) ; break; case 'V': Gdiag_no = atoi(argv[2]) ; nargs = 1 ; break ; case '?': case 'U': usage_exit(0) ; break ; default: fprintf(stderr, "unknown option %s\n", argv[1]) ; exit(1) ; break ; } return(nargs) ; }
static GCA_SAMPLE * find_control_points(GCA *gca, GCA_SAMPLE *gcas_total, int total_samples, int *pnorm_samples, int nregions, int label, MRI *mri_in, TRANSFORM *transform, double min_prior, double ctl_point_pct) { int i, j, *ordered_indices, nsamples, xmin, ymin, zmin, xmax, ymax, zmax, xv,yv,zv, x, y, z, xi, yi, zi, region_samples, used_in_region, prior_wsize=5, image_wsize=3, histo_peak, n, nbins ; GCA_SAMPLE *gcas, *gcas_region, *gcas_norm ; double means[MAX_GCA_INPUTS], vars[MAX_GCA_INPUTS], val, nsigma ; HISTOGRAM *histo, *hsmooth ; GC1D *gc ; float fmin, fmax ; MRI *mri_T1 = NULL ; if (label == Gdiag_no) DiagBreak() ; MRIvalRange(mri_in, &fmin, &fmax) ; nbins = (int)(fmax-fmin+1); histo = HISTOalloc(nbins) ; hsmooth = HISTOalloc(nbins) ; for (nsamples = i = 0 ; i < total_samples ; i++) { if (gcas_total[i].label != label) continue ; nsamples++ ; } *pnorm_samples = 0 ; printf("found %d control points for structure...\n", nsamples) ; if (nsamples == 0) { DiagBreak() ; return(NO_ERROR) ; } gcas = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; gcas_region = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; gcas_norm = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ; if (!gcas || !gcas_region || !gcas_norm) ErrorExit (ERROR_NOMEMORY, "find_control_points: could not allocate %d samples\n",nsamples); for (j = i = 0 ; i < total_samples ; i++) { if (gcas_total[i].label != label) continue ; memmove(&gcas[j], &gcas_total[i], sizeof(GCA_SAMPLE)) ; j++ ; } ordered_indices = (int *)calloc(nsamples, sizeof(int)) ; gcas_bounding_box(gcas, nsamples, &xmin, &ymin, &zmin, &xmax, &ymax, &zmax, label) ; printf("bounding box (%d, %d, %d) --> (%d, %d, %d)\n", xmin, ymin, zmin, xmax, ymax, zmax) ; for (x = 0 ; x < nregions ; x++) { for (y = 0 ; y < nregions ; y++) { for (z = 0 ; z < nregions ; z++) { /* only process samples in this region */ nsigma = 1.0 ; do { for (region_samples = i = 0 ; i < nsamples ; i++) { xi = (int)(nregions*(gcas[i].x - xmin) / (xmax-xmin+1)) ; yi = (int)(nregions*(gcas[i].y - ymin) / (ymax-ymin+1)) ; zi = (int)(nregions*(gcas[i].z - zmin) / (zmax-zmin+1)) ; if ((xi < 0 || xi >= nregions) || (yi < 0 || yi >= nregions) || (zi < 0 || zi >= nregions)) DiagBreak() ; xv = gcas[i].x ; yv = gcas[i].y ; zv = gcas[i].z ; if (xi != x || yi != y || zi != z || gcas[i].prior < min_prior) continue ; if (xv == Gx && yv == Gy && zv == Gz) DiagBreak() ; if (sqrt(SQR(xv-Gx)+SQR(yv-Gy)+SQR(zv-Gz)) < 2) DiagBreak() ; if (min_region_prior(gca, gcas[i].xp, gcas[i].yp, gcas[i].zp,prior_wsize, label) < min_prior) continue ; if (uniform_region(gca, mri_in, transform, xv, yv, zv, image_wsize, &gcas[i], nsigma) == 0) continue ; memmove(&gcas_region[region_samples], &gcas[i], sizeof(GCA_SAMPLE)) ; region_samples++ ; if (gcas[i].x == Gx && gcas[i].y == Gy && gcas[i].z == Gz) DiagBreak() ; } nsigma *= 1.1 ; } while (region_samples < 8 && nsigma < 3) ; if (region_samples < 8)/* can't reliably estimate statistics */ continue ; if (DIAG_VERBOSE_ON) printf("\t%d total samples found in region (%d, %d, %d)\n", region_samples,x, y,z) ; /* compute mean and variance of label within this region */ for (n = 0 ; n < mri_in->nframes ; n++) { HISTOclear(histo, histo) ; histo->bin_size = 1 ; for (means[n] = vars[n] = 0.0, i = 0 ; i < region_samples ; i++) { MRIsampleVolumeFrame (mri_in, gcas_region[i].x,gcas_region[i].y,gcas_region[i].z, n, &val) ; if (FZERO(val)) { if (i < (region_samples-1)) memmove(&gcas_region[i], &gcas_region[i+1], (region_samples-(i+1))*sizeof(GCA_SAMPLE)); i-- ; region_samples-- ; continue ; } histo->counts[(int)val]++ ; means[n] += val ; vars[n] += (val*val) ; } HISTOsmooth(histo, hsmooth, 2) ; histo_peak = HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins) ; if (histo_peak < 0) /* couldn't find a valid peak? */ break ; for (means[n] = vars[n] = 0.0, i = 0 ; i < region_samples ; i++) { if (gcas_region[i].label < 0) continue ; MRIsampleVolumeFrame (mri_in, gcas_region[i].x, gcas_region[i].y, gcas_region[i].z, n, &val) ; means[n] += val ; vars[n] += (val*val) ; } means[n] /= (double)region_samples ; vars[n] = vars[n] / (double)region_samples - means[n]*means[n] ; means[n] = histo_peak ; if (DIAG_VERBOSE_ON) printf("\tlabel %s[%d]: %2.1f +- %2.1f\n", cma_label_to_name(label), n, means[n], sqrt(vars[n])) ; } /* ignore GCA mean and variance - use image instead (otherwise bias field will mess us up) */ for (i = 0 ; i < region_samples ; i++) { int r ; for (r = 0 ; r < gca->ninputs ; r++) gcas_region[i].means[r] = means[r] ; /* gcas_region[i].var = var ;*/ } GCAcomputeLogSampleProbability (gca, gcas_region, mri_in, transform, region_samples) ; GCArankSamples (gca, gcas_region, region_samples, ordered_indices) ; GCAremoveOutlyingSamples (gca, gcas_region, mri_in, transform, region_samples, 2.0) ; for (used_in_region = i = 0 ; i < region_samples ; i++) { j = ordered_indices[i] ; if (gcas_region[j].label != label) /* it was an outlier */ continue ; memmove (&gcas_norm[*pnorm_samples], &gcas_region[j], sizeof(GCA_SAMPLE)) ; (*pnorm_samples)++ ; used_in_region++ ; } if ((used_in_region <= 0) && region_samples>0) { j = ordered_indices[0] ; /* gcas_region[j].label = label ;*/ printf("forcing use of sample %d @ (%d, %d, %d)\n", j, gcas_region[j].x, gcas_region[j].y, gcas_region[j].z) ; memmove(&gcas_norm[*pnorm_samples], &gcas_region[j], sizeof(GCA_SAMPLE)) ; (*pnorm_samples)++ ; used_in_region++ ; } if (DIAG_VERBOSE_ON) printf("\t%d samples used in region\n", used_in_region) ; } } } /* put gca means back into samples */ for (i = 0 ; i < *pnorm_samples ; i++) { gc = GCAfindPriorGC(gca, gcas_norm[i].xp, gcas_norm[i].yp, gcas_norm[i].zp, gcas_norm[i].label) ; if (gc) { int r, c, v ; for (v = r = 0 ; r < gca->ninputs ; r++) { for (c = r ; c < gca->ninputs ; c++, v++) { gcas_norm[i].means[v] = gc->means[v] ; gcas_norm[i].covars[v] = gc->covars[v] ; } } } } HISTOfree(&histo) ; HISTOfree(&hsmooth) ; free(gcas_region) ; free(gcas) ; if (mri_T1) MRIfree(&mri_T1) ; return(gcas_norm) ; }
int main(int argc, char *argv[]) { char *gca_fname, *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ; MRI *mri_in, *mri_norm = NULL, *mri_tmp, *mri_ctrl = NULL ; GCA *gca ; int ac, nargs, nsamples, msec, minutes, seconds; int i, struct_samples, norm_samples = 0, n, input, ninputs ; struct timeb start ; GCA_SAMPLE *gcas, *gcas_norm = NULL, *gcas_struct ; TRANSFORM *transform = NULL ; char cmdline[CMD_LINE_LEN], line[STRLEN], *cp, subject[STRLEN], sdir[STRLEN], base_name[STRLEN] ; FILE *fp ; make_cmd_version_string (argc, argv, "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $", "$Name: stable5 $", cmdline); /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_cal_normalize.c,v 1.2.2.1 2011/08/31 00:32:41 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; setRandomSeed(-1L) ; Progname = argv[0] ; DiagInit(NULL, NULL, NULL) ; ErrorInit(NULL, NULL, NULL) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 6) ErrorExit (ERROR_BADPARM, "usage: %s [<options>] <longitudinal time point file> <in vol> <atlas> <transform file> <out vol> \n", Progname) ; in_fname = argv[2] ; gca_fname = argv[3] ; xform_fname = argv[4] ; out_fname = argv[5] ; transform = TransformRead(xform_fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ; if (read_ctrl_point_fname) { mri_ctrl = MRIread(read_ctrl_point_fname) ; if (mri_ctrl == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read precomputed control points from %s", Progname, read_ctrl_point_fname) ; } TimerStart(&start) ; printf("reading atlas from '%s'...\n", gca_fname) ; fflush(stdout) ; gca = GCAread(gca_fname) ; if (gca == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open GCA %s.\n",Progname, gca_fname) ; GCAregularizeConditionalDensities(gca, .5) ; FileNamePath(argv[1], sdir) ; cp = strrchr(sdir, '/') ; if (cp) { strcpy(base_name, cp+1) ; *cp = 0 ; // remove last component of path, which is base subject name } ninputs = 0 ; fp = fopen(argv[1], "r") ; if (fp == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read time point file %s", argv[1]) ; do { cp = fgetl(line, STRLEN-1, fp) ; if (cp != NULL && strlen(cp) > 0) { subjects[ninputs] = (char *)calloc(strlen(cp)+1, sizeof(char)) ; strcpy(subjects[ninputs], cp) ; ninputs++ ; } } while (cp != NULL && strlen(cp) > 0) ; fclose(fp) ; printf("processing %d timepoints in SUBJECTS_DIR %s...\n", ninputs, sdir) ; for (input = 0 ; input < ninputs ; input++) { sprintf(subject, "%s.long.%s", subjects[input], base_name) ; printf("reading subject %s - %d of %d\n", subject, input+1, ninputs) ; sprintf(fname, "%s/%s/mri/%s", sdir, subject, in_fname) ; mri_tmp = MRIread(fname) ; if (!mri_tmp) ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s", Progname, fname) ; MRImakePositive(mri_tmp, mri_tmp) ; if (mri_tmp && ctrl_point_fname && !mri_ctrl) { mri_ctrl = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth,MRI_FLOAT, nregions*2) ; // labels and means MRIcopyHeader(mri_tmp, mri_ctrl) ; } if (input == 0) { mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, mri_tmp->type, ninputs) ; if (!mri_in) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate input volume %dx%dx%dx%d", mri_tmp->width,mri_tmp->height,mri_tmp->depth,ninputs) ; MRIcopyHeader(mri_tmp, mri_in) ; } if (mask_fname) { int i ; MRI *mri_mask ; mri_mask = MRIread(mask_fname) ; if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n", Progname, mask_fname) ; for (i = 1 ; i < WM_MIN_VAL ; i++) MRIreplaceValues(mri_mask, mri_mask, i, 0) ; MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ; MRIfree(&mri_mask) ; } MRIcopyFrame(mri_tmp, mri_in, 0, input) ; MRIfree(&mri_tmp) ; } MRIaddCommandLine(mri_in, cmdline) ; GCAhistoScaleImageIntensitiesLongitudinal(gca, mri_in, 1) ; { int j ; gcas = GCAfindAllSamples(gca, &nsamples, NULL, 1) ; printf("using %d sample points...\n", nsamples) ; GCAcomputeSampleCoords(gca, mri_in, gcas, nsamples, transform) ; if (sample_fname) GCAtransformAndWriteSamples (gca, mri_in, gcas, nsamples, sample_fname, transform) ; for (j = 0 ; j < 1 ; j++) { for (n = 1 ; n <= nregions ; n++) { for (norm_samples = i = 0 ; i < NSTRUCTURES ; i++) { if (normalization_structures[i] == Gdiag_no) DiagBreak() ; printf("finding control points in %s....\n", cma_label_to_name(normalization_structures[i])) ; gcas_struct = find_control_points(gca, gcas, nsamples, &struct_samples, n, normalization_structures[i], mri_in, transform, min_prior, ctl_point_pct) ; discard_unlikely_control_points(gca, gcas_struct, struct_samples, mri_in, transform, cma_label_to_name(normalization_structures[i])) ; if (mri_ctrl && ctrl_point_fname) // store the samples copy_ctrl_points_to_volume(gcas_struct, struct_samples, mri_ctrl, n-1) ; if (i) { GCA_SAMPLE *gcas_tmp ; gcas_tmp = gcas_concatenate(gcas_norm, gcas_struct, norm_samples, struct_samples) ; free(gcas_norm) ; norm_samples += struct_samples ; gcas_norm = gcas_tmp ; } else { gcas_norm = gcas_struct ; norm_samples = struct_samples ; } } printf("using %d total control points " "for intensity normalization...\n", norm_samples) ; if (normalized_transformed_sample_fname) GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples, normalized_transformed_sample_fname, transform) ; mri_norm = GCAnormalizeSamplesAllChannels(mri_in, gca, gcas_norm, file_only ? 0 :norm_samples, transform, ctl_point_fname, bias_sigma) ; if (Gdiag & DIAG_WRITE) { char fname[STRLEN] ; sprintf(fname, "norm%d.mgz", n) ; printf("writing normalized volume to %s...\n", fname) ; MRIwrite(mri_norm, fname) ; sprintf(fname, "norm_samples%d.mgz", n) ; GCAtransformAndWriteSamples(gca, mri_in, gcas_norm, norm_samples, fname, transform) ; } MRIcopy(mri_norm, mri_in) ; /* for next pass through */ MRIfree(&mri_norm) ; } } } // now do cross-time normalization to bring each timepoint closer to the mean at each location { MRI *mri_frame1, *mri_frame2, *mri_tmp ; double rms_before, rms_after ; int i ; mri_tmp = MRIcopy(mri_in, NULL) ; mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ; mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ; rms_before = MRIrmsDiff(mri_frame1, mri_frame2) ; printf("RMS before = %2.2f\n", rms_before) ; MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; for (i = 50 ; i <= 50 ; i += 25) { MRIcopy(mri_tmp, mri_in) ; normalize_timepoints_with_samples(mri_in, gcas_norm, norm_samples, i) ; mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ; mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ; rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ; MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; printf("RMS after (%d) = %2.2f\n", i, rms_after) ; } } { MRI *mri_frame1, *mri_frame2 ; double rms_after ; int i ; mri_tmp = MRIcopy(mri_in, NULL) ; for (i = 10 ; i <= 10 ; i += 10) { MRIcopy(mri_tmp, mri_in) ; normalize_timepoints(mri_in, 2.0, i) ; mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ; mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ; rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ; MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; printf("RMS after intensity cohering = %2.2f\n", rms_after) ; } } for (input = 0 ; input < ninputs ; input++) { sprintf(fname, "%s/%s.long.%s/mri/%s", sdir, subjects[input], base_name, out_fname) ; printf("writing normalized volume to %s...\n", fname) ; if (MRIwriteFrame(mri_in, fname, input) != NO_ERROR) ErrorExit(ERROR_BADFILE, "%s: could not write normalized volume to %s",Progname, fname); } if (ctrl_point_fname) { printf("writing control points to %s\n", ctrl_point_fname) ; MRIwrite(mri_ctrl, ctrl_point_fname) ; MRIfree(&mri_ctrl) ; } MRIfree(&mri_in) ; printf("freeing GCA...") ; if (gca) GCAfree(&gca) ; printf("done.\n") ; msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("normalization took %d minutes and %d seconds.\n", minutes, seconds) ; if (diag_fp) fclose(diag_fp) ; exit(0) ; return(0) ; }
int main(int argc, char *argv[]) { MRIS *mris; char *in_orig_fname=NULL, *in_seg_fname=NULL,*out_fname=NULL; MRI *mri_orig=NULL,*mri_seg=NULL,*mri_out=NULL; int nargs,n; char fname[512]; Progname=argv[0]; fprintf(stderr,"\n"); MRI_TOPOLOGY_PARMSdefault(&parms); for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (parms.tesselation_mode==-1) parms.tesselation_mode=parms.connectivity; if (argc<4) { fprintf(stderr, "\nUsage: %s options input_orig_file input_segmented_file output_folder\n", Progname); exit(1); }; in_orig_fname=argv[argc-3]; in_seg_fname = argv[argc-2]; out_fname = argv[argc-1]; fprintf(stderr,"************************************************************" "\nThe input orig volume is %s" "\nThe input segmented volume is %s" "\nThe output volume is %s" "\nIf this is incorrect, please exit quickly the program (Ctl-C)\n",in_orig_fname,in_seg_fname,out_fname); for (n=0;n<parms.nlabels;n++) fprintf(stderr,"label = %d: %s \n",parms.labels[n],cma_label_to_name(parms.labels[n])); if (parms.using_gca_maps) fprintf(stderr,"mixing parameters: alpha=%1.3f , beta=%1.3f \n",parms.alpha,parms.beta); else { parms.beta=1.0f; parms.alpha=1.0f; } fprintf(stderr,"connectivity = %d\n",parms.connectivity); mri_orig=MRIread(in_orig_fname); if (!mri_orig && parms.using_gca_maps) Error("orig volume: orig volume could not be read\n"); mri_seg=MRIread(in_seg_fname); if (!mri_seg) Error("segmented volume: segmented volume could not be read\n"); //check euler characteristic of initial surface if (parms.initial_surface_file) { int i,j,k,val,euler,pnvertices, pnfaces, pnedges; MRI *mri_tmp; mri_tmp=MRIclone(mri_seg,NULL); for (k=0;k<mri_seg->depth;k++) for (j=0;j<mri_seg->height;j++) for (i=0;i<mri_seg->width;i++) for (n=0;n<parms.nlabels;n++) { val=MRIgetVoxVal(mri_seg,i,j,k, 0); if (val==parms.labels[n]) { MRIsetVoxVal(mri_tmp,i,j,k,0,1); break; } } mris=MRIScreateSurfaceFromVolume(mri_tmp,1,parms.connectivity); euler=MRIScomputeEulerNumber(mris,&pnvertices,&pnfaces,&pnedges); fprintf(stderr,"\ninitial euler characteristic = %d, %d vertices, %d faces, %d edges" ,euler,pnvertices,pnfaces,pnedges); MRISwrite(mris,parms.initial_surface_file); MRISfree(&mris); MRIfree(&mri_tmp); } mri_out=MRIcorrectTopology(mri_orig,mri_seg,NULL,&parms); if (parms.nlabels == 1) { MRI *mri_tmp ; // turn off all voxels that are going to be on in the output MRImask(mri_seg, mri_out, mri_seg, 1, 0) ; /* whatever ones are left are now incorrect and should be labeled something else */ resegment_erased_voxels(mri_orig, mri_seg, mri_seg, parms.labels[0]) ; MRIreplaceValues(mri_out, mri_out, 1, parms.labels[0]) ; mri_tmp = MRIcopy(mri_seg, NULL) ; MRIcopyLabel(mri_out, mri_tmp, parms.labels[0]) ; MRIfree(&mri_out) ; mri_out = mri_tmp ; // check_volume(mri_save, mri_out, parms.labels[0]) ; } MRIwrite(mri_out,out_fname); ////TEMPORARY VALIDATION STUFF ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// #if 0 //validation of the algo { FILE *f; MRIS *mristb[20],*mrisr; int n,i,j,k,depth,height,width,count,count2; int tab[20]={4,43,51,12,52,13,54,18,53,17,49,10,50,11};//,6,7,10,11,12,13,17,18,43,44,45,46,49,50,51,52,53,54}; MRI *mri_val=MRIclone(parms.mri_seg,NULL); parms.nlabels=1; depth=parms.mri_seg->depth; height=parms.mri_seg->height; width=parms.mri_seg->width; for (n=0;n<14;n++) { MRIfree(&parms.mri_output); MRIfree(&parms.mri_bin); MRIfree(&parms.mri_dist); MRIfree(&parms.mri_fcost); MRIfree(&parms.mri_bcost); MRIfree(&parms.mri_fprior); MRIfree(&parms.mri_bprior); MRIfree(&parms.mri_labeled); segmentationFree(&parms.F_Bseg); segmentationFree(&parms.F_Rseg); segmentationFree(&parms.B_Bseg); segmentationFree(&parms.B_Rseg); CCSfree(&parms.F_Bccs); CCSfree(&parms.F_Rccs); CCSfree(&parms.B_Bccs); CCSfree(&parms.B_Rccs); parms.labels[0]=tab[n]; MRIcorrectTopology(parms.mri_orig,parms.mri_seg,&parms.mri_output,mris ,parms.labels,parms.nblabels,parms.f_c,parms); MRISwrite(*mris,"./tmp"); mristb[n]=MRISread("./tmp"); #if 0 count=0; count2=0; for (k=0;k<depth;k++) for (j=0;j<height;j++) for (i=0;i<width;i++) { if (MRIvox(parms.mri_seg,i,j,k)==parms.labels[0]) count2++; if (MRIvox(parms.mri_output,i,j,k)==1) { MRIvox(mri_val,i,j,k)++; if (MRIvox(parms.mri_seg,i,j,k)!=parms.labels[0]) count++; } else if (MRIvox(parms.mri_seg,i,j,k)==parms.labels[0]) count++; } fprintf(stderr,"\n yeh %d %d %f \n",count,count2,100.*count/count2); sprintf(fname,"./label%d",tab[n]); f=fopen(fname,"a+"); fprintf(f,"\n %d %d %f ",count,count2,(float)100.*count/count2); fclose(f); #endif #if 0 sprintf(fname,"./surf%d",n); MRISwrite(mristb[n],fname); MRISsmoothSurface2(mristb[n],5,0.5,0); MRISsmoothSurface2(mristb[n],5,0.25,2); MRISsmoothSurface2(mristb[n],10,0.05,5); sprintf(fname,"./surfsmooth%d",n); mristb[n]->type=MRIS_TRIANGULAR_SURFACE;//MRIS_BINARY_QUADRANGLE_FILE; MRISwrite(mristb[n],fname); MRISsetNeighborhoodSize(mristb[n],3) ; MRIScomputeMetricProperties(mristb[n]) ; MRIScomputeSecondFundamentalForm(mristb[n]) ; MRISuseMeanCurvature(mristb[n]); MRISaverageCurvatures(mristb[n],2) ; MRISnormalizeCurvature(mristb[n], NORM_MEAN) ; sprintf(fname,"./curv%d",n); MRISwriteCurvature(mristb[n],fname); #endif } #if 0 mrisr=MRISconcatenateQuadSurfaces(n,mristb); mrisr->type=MRIS_TRIANGULAR_SURFACE; MRISwrite(mrisr,"./lh.ZURFACE"); // for(k=0;k<mrisr->nvertices;k++) // mrisr->vertices[k].curv=0.3; //MRISnormalizeCurvature(mrisr, NORM_MEAN) ; MRISwriteCurvature(mrisr,"./ZURFACE_CURVATURE"); for (k=0;k<mrisr->nvertices;k++) mrisr->vertices[k].curv=mrisr->vertices[k].val; MRISwriteCurvature(mrisr,"./ZURFACE_VAL"); #endif n=0; count=0; for (k=0;k<depth;k++) for (j=0;j<height;j++) for (i=0;i<width;i++) { if (MRIgetVoxVal(mri_val,i,j,k,0)>=1) { n++; if (MRIsetVoxVal(mri_val,i,j,k,0)>1) count++; } } // sprintf(fname,"./labeltotal"); /// f=fopen(fname,"a+"); //fprintf(f,"\n %s %d %d %f ",in_seg_fname,count,n,(float)100.*count/n); //fclose(f); #if 0 MRIwrite(mri_val,"/tmp/tmp"); #endif fprintf(stderr,"\n WE HAVE %d %d %f \n",count,n,100.*count/n); } #endif ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// if (parms.final_surface_file) { int euler,pnvertices, pnfaces, pnedges; mris=MRIScreateSurfaceFromVolume(mri_out,1,parms.connectivity); euler=MRIScomputeEulerNumber(mris,&pnvertices,&pnfaces,&pnedges); fprintf(stderr,"\nfinal euler characteristic = %d, %d vertices, %d faces, %d edges" ,euler,pnvertices,pnfaces,pnedges); sprintf(fname,"%s",parms.final_surface_file); MRISwrite(mris,fname); #if 0 MRISsmoothSurface(mris,7,0.2); strcat(fname,"_smooth"); MRISwrite(mris,fname); if (parms.fit) { sprintf(fname,parms.surfname); strcat(fname,"_fit"); MRISmatchSurfaceToLabel(parms.mris,parms.mri_output,1,NULL,NULL,parms.f_c); MRISwrite(parms.mris,fname); } #endif MRISfree(&mris); } if (mri_out) MRIfree(&mri_out); if (mri_orig) MRIfree(&mri_orig); if (mri_seg) MRIfree(&mri_seg); fprintf(stderr,"\n"); return NO_ERROR; }
/*---------------------------------------------------------------------- Parameters: Description: ----------------------------------------------------------------------*/ static int get_option(int argc, char *argv[]) { static int first_input = 1 ; int nargs = 0 ; char *option ; option = argv[1] + 1 ; /* past '-' */ if (!stricmp(option, "GRADIENT")) { parms.use_gradient = 1 ; ninputs += 3 ; /* components of the gradient */ } else if (!stricmp(option, "MAX_RATIO")) { max_wm_wmsa_ratio = atof(argv[2]) ; nargs = 1 ; printf("using %2.1f as max wm/wmsa ratio for number of training samples\n", max_wm_wmsa_ratio) ; } else if (!stricmp(option, "CONFORM")) { conform = atoi(argv[2]) ; nargs = 1 ; printf("%sassuming input volumes are conformed\n", conform ? "" : "NOT ") ; } else if (!stricmp(option, "MAKE_UCHAR")) { make_uchar = atoi(argv[2]) ; nargs = 1 ; printf("%smaking input volumes UCHAR\n", make_uchar ? "" : "NOT ") ; } else if (!stricmp(option, "TRAINING_FRACTION")) { parms.training_fraction = atof(argv[2]) ; nargs = 1 ; printf("setting training_fraction = %2.6f\n", parms.training_fraction) ; } else if (!stricmp(option, "WMSA")) { wmsa_fname = argv[2] ; nargs = 1 ; printf("reading white matter signal abnormalities from %s\n", wmsa_fname) ; } else if (!stricmp(option, "INPUT")) { if (first_input) { ninputs-- ; first_input = 0 ; } input_names[ninputs++] = argv[2] ; nargs = 1 ; printf("input[%d] = %s\n", ninputs-1, input_names[ninputs-1]) ; } else if (!stricmp(option, "BINARIZE")) { binarize = 1 ; binarize_in = atoi(argv[2]) ; binarize_out = atoi(argv[3]) ; nargs = 2 ; printf("binarizing segmentation values, setting input %d to output %d\n", binarize_in, binarize_out) ; } else if (!stricmp(option, "MASK")) { mask_fname = argv[2] ; nargs = 1 ; printf("using MR volume %s to mask input volume...\n", mask_fname) ; } else if (!stricmp(option, "DEBUG_NODE")) { Ggca_x = atoi(argv[2]) ; Ggca_y = atoi(argv[3]) ; Ggca_z = atoi(argv[4]) ; nargs = 3 ; printf("debugging node (%d, %d, %d)\n", Ggca_x,Ggca_y,Ggca_z) ; } else if (!stricmp(option, "DEBUG_VOXEL")) { Gx = atoi(argv[2]) ; Gy = atoi(argv[3]) ; Gz = atoi(argv[4]) ; nargs = 3 ; printf("debugging voxel (%d, %d, %d)\n", Gx,Gy,Gz) ; } else if (!stricmp(option, "DEBUG_LABEL")) { Ggca_label = atoi(argv[2]) ; nargs = 1 ; printf("debugging label %s (%d)\n", cma_label_to_name(Ggca_label), Ggca_label) ; } else if (!stricmp(option, "INSERT")) { insert_fname = argv[2] ; insert_label = atoi(argv[3]) ; nargs = 2 ; printf("inserting non-zero vals from %s as label %d...\n", insert_fname,insert_label); } else if (!stricmp(option, "ctab")) { printf("reading color table from %s and embedding in .gca file", argv[2]) ; ctab = CTABreadASCII(argv[2]) ; if (ctab == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read color table from %s", Progname,argv[2]); nargs = 1 ; } else if (!stricmp(option, "T1")) { strcpy(T1_name, argv[2]) ; nargs = 1 ; printf("reading T1 data from subject's mri/%s directory\n", T1_name) ; } else if (!stricmp(option, "PARC_DIR") || !stricmp(option, "SEG_DIR") || !stricmp(option, "SEG") || !stricmp(option, "SEGMENTATION")) { seg_dir = argv[2] ; nargs = 1 ; printf("reading segmentation from subject's mri/%s directory\n", seg_dir) ; } else if (!stricmp(option, "XFORM")) { xform_name = argv[2] ; nargs = 1 ; printf("reading xform from %s\n", xform_name) ; } else if (!stricmp(option, "NOXFORM")) { xform_name = NULL ; printf("disabling application of xform...\n") ; } else if (!stricmp(option, "check")) { do_sanity_check = 1; printf("will conduct sanity-check of labels...\n") ; } else if (!stricmp(option, "check_and_fix")) { do_sanity_check = 1; do_fix_badsubjs = 1; printf("will conduct sanity-check of labels and write corrected " "volume to seg_fixed.mgz...\n") ; } else if (!stricmp(option, "SDIR")) { strcpy(subjects_dir, argv[2]) ; nargs = 1 ; printf("using %s as subjects directory\n", subjects_dir) ; } else if (!stricmp(option, "NTREES")) { parms.ntrees = atoi(argv[2]) ; nargs = 1 ; printf("using %d trees in random forest classifier\n", parms.ntrees) ; } else if (!stricmp(option, "MAX_DEPTH")) { parms.max_depth = atoi(argv[2]) ; nargs = 1 ; printf("using %d max tree depth in random forest classifier\n", parms.max_depth) ; } else if (!stricmp(option, "WMSA_WHALF")) { wmsa_whalf = atoi(argv[2]) ; nargs = 1 ; printf("only examing voxels that wmsa occurred within %d voxels of\n", wmsa_whalf) ; } else if (!stricmp(option, "SMOOTH")) { smooth = atof(argv[2]) ; if (smooth <= 0 || smooth > 1) ErrorExit(ERROR_BADPARM, "%s: smoothing parameter %2.1f must be in [0,1]\n", Progname, smooth) ; nargs = 1 ; printf("imposing %2.1f smoothing on conditional statistics\n", smooth) ; } else if (!stricmp(option, "NBRS")) { only_nbrs = 1 ; printf("training RF using voxels that neighbor both a wmsa and a non-wmsa\n") ; } else switch (toupper(*option)) { case 'G': single_classifier_flag = 1 ; gca_name = argv[2] ; nargs = 1 ; printf("training a single classifier instead of an array using gca %s\n", gca_name) ; break ; case 'T': wm_thresh = atof(argv[2]) ; nargs = 1 ; printf("thresholding wm priors at %f to build training set\n", wm_thresh) ; break ; case 'F': force_inputs = 1 ; printf("forcing use of inputs even if acquisition parameters don't match\n"); break ; case 'S': scale = atof(argv[2]) ; printf("scaling all volumes by %2.3f after reading...\n", scale) ; nargs = 1 ; break ; case 'L': log_file_name = argv[2] ; printf("logging out of bag accuracy to %s\n", log_file_name) ; nargs = 1 ; break ; case 'A': navgs = atoi(argv[2]) ; printf("applying %d mean filters to classifiers after training\n",navgs); nargs = 1 ; break ; case '?': case 'U': usage_exit(0) ; break ; case 'W': parms.wsize = atoi(argv[2]) ; nargs = 1 ; printf("using window size = %d for RFA\n", parms.wsize) ; break ; default: fprintf(stderr, "unknown option %s\n", argv[1]) ; exit(1) ; break ; } return(nargs) ; }
/* * check * * conduct a sanity check of particular labels, most importantly * hippocampus, that such labels do not exist in talairach coords * where they are known not to belong (indicating a bad manual edit) */ static int check(MRI *mri_seg, char *subjects_dir, char *subject_name) { int x, y, z, label, errors=0; Real xw=0.0, yw=0.0, zw=0.0; // RAS coords Real xmt=0.0, ymt=0.0, zmt=0.0; // MNI tal coords float xt=0.0, yt=0.0, zt=0.0; // 'real' tal coords MRI *mri_fixed = NULL; float max_xtal_l_hippo = -1000; float max_xtal_l_caudate = -1000; float max_xtal_l_amygdala = -1000; float max_xtal_l_putamen = -1000; float max_xtal_l_pallidum = -1000; float min_xtal_r_hippo = 1000; float min_xtal_r_caudate = 1000; float min_xtal_r_amygdala = 1000; float min_xtal_r_putamen = 1000; float min_xtal_r_pallidum = 1000; printf("checking labels in subject %s...\n",subject_name); if (do_fix_badsubjs) { mri_fixed = MRIcopy(mri_seg,NULL); } if (NULL == mri_seg->linear_transform) { ErrorExit(ERROR_BADFILE, "ERROR: mri_ca_train: talairach.xfm not found in %s!\n" "Run mri_add_xform_to_header to add to volume.\n", seg_dir); } // now conduct checks for voxels in locations where they shouldnt be for (x = 0 ; x < mri_seg->width ; x++) { for (y = 0 ; y < mri_seg->height ; y++) { for (z = 0 ; z < mri_seg->depth ; z++) { /* * rules: * - no label should have a voxel coord < 6 or > 249 * - no left or right hippo labels with z tal coord > 15 * - no left hippo, caudate, amydala, putamen or pallidum * labels with x tal coord > 5 (or right, with x tal coord < -5) */ label = MRIgetVoxVal(mri_seg, x, y, z, 0) ; int proper_label = label; // used for making corrections if (label != Unknown) { // note: these won't be caught if -mask brainmask.mgz is included // on the command-line, since voxels outside of brainmask get // labelled as Unknown. if ((x < 6) || (y < 6) || (z < 6) || (x > 249) || (y > 249) || (z > 249)) { printf ("ERROR: %s: found label outside of brain: " "%d %d %d\n", cma_label_to_name(label),x,y,z); fflush(stdout) ; errors++; proper_label = Unknown; } } if ((label == Left_Hippocampus) || (label == Right_Hippocampus) || (label == Left_Caudate) || (label == Right_Caudate) || (label == Left_Amygdala) || (label == Right_Amygdala) || (label == Left_Putamen) || (label == Right_Putamen) || (label == Left_Pallidum) || (label == Right_Pallidum) || (label == Left_Inf_Lat_Vent) || (label == Right_Inf_Lat_Vent)) { // the 'if' statement above spares some cpu cycles in having to // calculate the coord transform for every voxel, ie these 3 lines: MRIvoxelToWorld(mri_seg, x, y, z, &xw, &yw, &zw) ; transform_point(mri_seg->linear_transform, xw, yw, zw, &xmt, &ymt, &zmt);// get mni tal coords FixMNITal(xmt,ymt,zmt, &xt,&yt,&zt); // get 'real' tal coords switch (label) { case Left_Hippocampus: if (zt > 15) { printf ("ERROR: %s: " "%d %d %d, tal x=%f, y=%f, *** z=%f > 15 ***\n", cma_label_to_name(label),x,y,z,xt,yt,zt); fflush(stdout) ; errors++; } // no break (check xt) case Left_Caudate: case Left_Amygdala: case Left_Putamen: case Left_Pallidum: case Left_Inf_Lat_Vent: if (xt > 5) { printf ("ERROR: %s: " "%d %d %d, tal *** x=%f > 5 ***, y=%f, z=%f\n", cma_label_to_name(label), x,y,z,xt,yt,zt); fflush(stdout) ; errors++; if (label == Left_Hippocampus) proper_label = Right_Hippocampus; else if (label == Left_Caudate) proper_label = Right_Caudate; else if (label == Left_Amygdala) proper_label = Right_Amygdala; else if (label == Left_Putamen) proper_label = Right_Putamen; else if (label == Left_Pallidum) proper_label = Right_Pallidum; else if (label == Left_Inf_Lat_Vent) proper_label = Right_Inf_Lat_Vent; } break; case Right_Hippocampus: if (zt > 15) { printf ("ERROR: %s: " "%d %d %d, tal x=%f, y=%f, *** z=%f > 15 ***\n", cma_label_to_name(label),x,y,z,xt,yt,zt); fflush(stdout) ; errors++; } // no break (check xt) case Right_Caudate: case Right_Amygdala: case Right_Putamen: case Right_Pallidum: case Right_Inf_Lat_Vent: if (xt < -5) { printf ("ERROR: %s: " "%d %d %d, tal *** x=%f < -5 ***, y=%f, z=%f\n", cma_label_to_name(label), x,y,z,xt,yt,zt); fflush(stdout) ; errors++; if (label == Right_Hippocampus) proper_label = Left_Hippocampus; else if (label == Right_Caudate) proper_label = Left_Caudate; else if (label == Right_Amygdala) proper_label = Left_Amygdala; else if (label == Right_Putamen) proper_label = Left_Putamen; else if (label == Right_Pallidum) proper_label = Left_Pallidum; else if (label == Right_Inf_Lat_Vent) proper_label = Left_Inf_Lat_Vent; } break; default: break ; } /* * collect stats on positioning of structures. * used to determine reasonable boundaries. */ switch (label) { case Left_Hippocampus: if (xt > max_xtal_l_hippo) max_xtal_l_hippo = xt; break; case Left_Caudate: if (xt > max_xtal_l_caudate) max_xtal_l_caudate = xt; break; case Left_Amygdala: if (xt > max_xtal_l_amygdala) max_xtal_l_amygdala = xt; break; case Left_Putamen: if (xt > max_xtal_l_putamen) max_xtal_l_putamen = xt; break; case Left_Pallidum: if (xt > max_xtal_l_pallidum) max_xtal_l_pallidum = xt; break; case Right_Hippocampus: if (xt < min_xtal_r_hippo) min_xtal_r_hippo = xt; break; case Right_Caudate: if (xt < min_xtal_r_caudate) min_xtal_r_caudate = xt; break; case Right_Amygdala: if (xt < min_xtal_r_amygdala) min_xtal_r_amygdala = xt; break; case Right_Putamen: if (xt < min_xtal_r_putamen) min_xtal_r_putamen = xt; break; case Right_Pallidum: if (xt < min_xtal_r_pallidum) min_xtal_r_pallidum = xt; break; default: break ; } } /* * if -check_and_fix is being used, then mod our fixed volume */ if (do_fix_badsubjs && (label != proper_label)) { MRIsetVoxVal(mri_fixed, x, y, z, 0, proper_label) ; } } } } // stats used to determine optimal boundaries printf("max_xtal_l_hippo = %4.1f\n",max_xtal_l_hippo); printf("max_xtal_l_caudate = %4.1f\n",max_xtal_l_caudate); printf("max_xtal_l_amygdala = %4.1f\n",max_xtal_l_amygdala); printf("max_xtal_l_putamen = %4.1f\n",max_xtal_l_putamen); printf("max_xtal_l_pallidum = %4.1f\n",max_xtal_l_pallidum); printf("min_xtal_r_hippo = %4.1f\n",min_xtal_r_hippo); printf("min_xtal_r_caudate = %4.1f\n",min_xtal_r_caudate); printf("min_xtal_r_amygdala = %4.1f\n",min_xtal_r_amygdala); printf("min_xtal_r_putamen = %4.1f\n",min_xtal_r_putamen); printf("min_xtal_r_pallidum = %4.1f\n",min_xtal_r_pallidum); if ( do_fix_badsubjs && errors) { char fname[STRLEN]; sprintf(fname, "%s/%s/mri/seg_fixed.mgz", subjects_dir, subject_name); printf("Writing corrected volume to %s\n",fname); MRIwrite(mri_fixed,fname); MRIfree(&mri_fixed); } fflush(stdout); return(errors) ; }
int FCDcomputeThicknessLabels(FCD_DATA *fcd, double thickness_thresh, double sigma, int size_thresh) { MRI *mri_lh, *mri_rh, *mri_lh_diff, *mri_rh_diff ; int niter, vno, s ; MRI_SEGMENTATION *mriseg ; fcdFreeLabels(fcd) ; // free old ones if they exist niter = SIGMA_TO_SURFACE_SMOOTH_STEPS(sigma) ; // do LH mri_lh = MRIclone(fcd->lh_thickness_on_lh, NULL) ; mri_rh = MRIclone(fcd->lh_thickness_on_lh, NULL) ; exec_progress_callback(1, 8, 0, 1) ; MRISwriteFrameToValues(fcd->mris_lh, fcd->lh_thickness_on_lh, 0) ; MRISaverageVals(fcd->mris_lh, niter) ; MRISreadFrameFromValues(fcd->mris_lh, mri_lh, 0) ; exec_progress_callback(2, 8, 0, 1) ; MRISwriteFrameToValues(fcd->mris_lh, fcd->rh_thickness_on_lh, 0) ; MRISaverageVals(fcd->mris_lh, niter) ; MRISreadFrameFromValues(fcd->mris_lh, mri_rh, 0) ; mri_lh_diff = MRIsubtract(mri_lh, mri_rh, NULL) ; // lh minus rh on lh MRIfree(&mri_lh); MRIfree(&mri_rh) ; // do RH mri_lh = MRIclone(fcd->lh_thickness_on_rh, NULL) ; mri_rh = MRIclone(fcd->lh_thickness_on_rh, NULL) ; exec_progress_callback(3, 8, 0, 1) ; MRISwriteFrameToValues(fcd->mris_rh, fcd->lh_thickness_on_rh, 0) ; MRISaverageVals(fcd->mris_rh, niter) ; MRISreadFrameFromValues(fcd->mris_rh, mri_lh, 0) ; exec_progress_callback(4, 8, 0, 1) ; MRISwriteFrameToValues(fcd->mris_rh, fcd->rh_thickness_on_rh, 0) ; MRISaverageVals(fcd->mris_rh, niter) ; MRISreadFrameFromValues(fcd->mris_rh, mri_rh, 0) ; mri_rh_diff = MRIsubtract(mri_rh, mri_lh, NULL) ; // lh minus rh on rh MRIfree(&mri_lh); MRIfree(&mri_rh) ; MRIclear(fcd->mri_thickness_increase) ; MRIclear(fcd->mri_thickness_decrease) ; exec_progress_callback(5, 8, 0, 1) ; // process left hemisphere #if 1 #ifdef HAVE_OPENMP #pragma omp parallel for shared(fcd, mri_lh_diff, Gdiag_no, thickness_thresh) schedule(static,1) #endif #endif for (vno = 0 ; vno < fcd->mris_lh->nvertices ; vno++) { double d ; float val, val2, thickness; int base_label ; VERTEX *v ; v = &fcd->mris_lh->vertices[vno] ; if (v->ripflag) { continue ; } thickness = MRIgetVoxVal(fcd->lh_thickness_on_lh, vno, 0, 0, 0) ; if (vno == Gdiag_no) { DiagBreak() ; } val = MRIgetVoxVal(mri_lh_diff, vno, 0, 0, 0) ; if (fabs(val) < thickness_thresh) { continue ; } for (d = 0, base_label = 0 ; d < thickness ; d += 0.25) { double xv, yv, zv; double xs = v->x+d*v->nx ; double ys = v->y+d*v->ny ; double zs = v->z+d*v->nz ; MRISsurfaceRASToVoxel(fcd->mris_lh, fcd->mri_thickness_increase, xs, ys, zs, &xv, &yv, &zv) ; int xvi = nint(xv) ; int yvi = nint(yv) ; int zvi = nint(zv) ; int label = MRIgetVoxVal(fcd->mri_aparc, xvi, yvi, zvi, 0) ; if (IS_WM(label) == 0 && label >= MIN_CORTICAL_PARCELLATION && label != ctx_lh_unknown) { if (label != base_label) { if (base_label) { break ; } } else { base_label = label ; } if (val >= 0) { val2 = MRIgetVoxVal(fcd->mri_thickness_increase, xvi, yvi, zvi, 0) ; // check another thread already populated this voxel if (val > val2) { MRIsetVoxVal(fcd->mri_thickness_increase, xvi, yvi, zvi, 0, val) ; } } else { val2 = MRIgetVoxVal(fcd->mri_thickness_decrease, xvi, yvi, zvi, 0) ; // check if another thread already populated this voxel if (val < val2) { MRIsetVoxVal(fcd->mri_thickness_decrease, xvi, yvi, zvi, 0, val) ; } } } } } exec_progress_callback(6, 8, 0, 1) ; // now do right hemisphere #if 1 #ifdef HAVE_OPENMP #pragma omp parallel for shared(fcd, mri_rh_diff, Gdiag_no, thickness_thresh) schedule(static,1) #endif #endif for (vno = 0 ; vno < fcd->mris_rh->nvertices ; vno++) { double d ; float val, val2, thickness; int base_label ; VERTEX *v ; v = &fcd->mris_rh->vertices[vno] ; if (v->ripflag) { continue ; } if (vno == Gdiag_no) { DiagBreak() ; } val = MRIgetVoxVal(mri_rh_diff, vno, 0, 0, 0) ; if (fabs(val) < thickness_thresh) { continue ; } thickness = MRIgetVoxVal(fcd->rh_thickness_on_rh, vno, 0, 0, 0) ; for (d = 0, base_label = 0; d < thickness ; d += 0.25) { double xv, yv, zv; double xs = v->x+d*v->nx ; double ys = v->y+d*v->ny ; double zs = v->z+d*v->nz ; MRISsurfaceRASToVoxel(fcd->mris_rh, fcd->mri_thickness_increase, xs, ys, zs, &xv, &yv, &zv) ; int xvi = nint(xv) ; int yvi = nint(yv) ; int zvi = nint(zv) ; int label = MRIgetVoxVal(fcd->mri_aparc, xvi, yvi, zvi, 0) ; if (IS_WM(label) == 0 && label >= MIN_CORTICAL_PARCELLATION && label != ctx_rh_unknown) { if (label != base_label) { if (base_label) { break ; } } else { base_label = label ; } if (val >= 0) { val2 = MRIgetVoxVal(fcd->mri_thickness_increase, xvi, yvi, zvi, 0) ; if (val > val2) { MRIsetVoxVal(fcd->mri_thickness_increase, xvi, yvi, zvi, 0, val) ; } } else { val2 = MRIgetVoxVal(fcd->mri_thickness_decrease, xvi, yvi, zvi, 0) ; if (val < val2) { MRIsetVoxVal(fcd->mri_thickness_decrease, xvi, yvi, zvi, 0, val) ; } } } } } exec_progress_callback(7, 8, 0, 1) ; mriseg = MRIsegment(fcd->mri_thickness_increase, thickness_thresh, 1e10) ; MRIeraseSmallSegments(mriseg, fcd->mri_thickness_increase, thickness_thresh) ; MRIsegmentFree(&mriseg) ; MRIclose(fcd->mri_thickness_increase, fcd->mri_thickness_increase) ; mriseg = MRIsegment(fcd->mri_thickness_increase, thickness_thresh, 1e10) ; MRIremoveSmallSegments(mriseg, size_thresh) ; printf("segmenting volume at threshold %2.1f with %d " "smoothing iters yields %d segments\n", thickness_thresh, niter,mriseg->nsegments) ; fflush(stdout) ; exec_progress_callback(8, 8, 0, 1) ; fcd->nlabels = mriseg->nsegments ; for (s = 0 ; s < mriseg->nsegments ; s++) { int label ; fcd->labels[s] = MRIsegmentToLabel(mriseg, fcd->mri_thickness_increase, s) ; label = most_frequent_label(fcd->mri_aparc, &mriseg->segments[s]) ; strcpy(fcd->labels[s]->name, cma_label_to_name(label)) ; } sort_labels(fcd) ; MRIadd(fcd->mri_thickness_increase, fcd->mri_thickness_decrease, fcd->mri_thickness_difference); for (s = 0 ; s < mriseg->nsegments ; s++) { printf("%s: %2.3fmm\n", fcd->label_names[s], fcd->labels[s]->avg_stat) ; fflush(stdout) ; } MRIfree(&mri_lh_diff) ; MRIfree(&mri_rh_diff) ; MRIsegmentFree(&mriseg) ; return(fcd->nlabels) ; }