static int replaceLabels(MRI *mri_seg) { int i ; for (i = 0 ; i < sizeof(output_labels)/sizeof(output_labels[0]) ; i++) MRIreplaceValues(mri_seg, mri_seg, input_labels[i], output_labels[i]) ; return(NO_ERROR) ; }
int main(int argc, char *argv[]) { char *in_fname, *out_fname, **av, *xform_fname, fname[STRLEN] ; MRI *mri_in, *mri_tmp ; int ac, nargs, msec, minutes, seconds; int input, ninputs ; struct timeb start ; 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_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $", "$Name: $", cmdline); /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_fuse_intensity_images.c,v 1.2 2011/06/02 14:05:10 fischl Exp $", "$Name: $"); 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 < 5) ErrorExit (ERROR_BADPARM, "usage: %s [<options>] <longitudinal time point file> <in vol> <transform file> <out vol> \n", Progname) ; in_fname = argv[2] ; xform_fname = argv[3] ; out_fname = argv[4] ; transform = TransformRead(xform_fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read transform from %s", Progname, xform_fname) ; TimerStart(&start) ; 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", Progname, 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 (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) ; // try to bring the images closer to each other at each voxel where they seem to come from the same distribution { MRI *mri_frame1, *mri_frame2 ; double rms_after ; mri_frame1 = MRIcopyFrame(mri_in, NULL, 0, 0) ; mri_frame2 = MRIcopyFrame(mri_in, NULL, 1, 0) ; rms_after = MRIrmsDiff(mri_frame1, mri_frame2) ; printf("RMS before intensity cohering = %2.2f\n", rms_after) ; MRIfree(&mri_frame1) ; MRIfree(&mri_frame2) ; if (0) normalize_timepoints(mri_in, 2.0, cross_time_sigma) ; else normalize_timepoints_with_parzen_window(mri_in, cross_time_sigma) ; 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 (sigma=%2.2f)\n", rms_after, cross_time_sigma) ; } 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); } MRIfree(&mri_in) ; 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[]) { char **av, *hemi, *subject_name, *cp, fname[STRLEN]; char *parc_name, *annot_name ; int ac, nargs, vno, i ; MRI_SURFACE *mris ; MRI *mri_parc ; VERTEX *v ; double d ; Real x, y, z, xw, yw, zw ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mris_sample_parc.c,v 1.31 2016/12/11 14:33:38 fischl 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() ; subject_name = argv[1] ; hemi = argv[2] ; parc_name = argv[3] ; annot_name = argv[4] ; if (strlen(sdir) == 0) /* if not specified explicitly as option */ { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ; strcpy(sdir, cp) ; } if (parc_name[0] == '/') // full path specified strcpy(fname, parc_name) ; else sprintf(fname, "%s/%s/mri/%s", sdir, subject_name, parc_name) ; printf("reading parcellation volume from %s...\n", fname) ; mri_parc = MRIread(fname) ; if (!mri_parc) ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s", Progname, fname) ; if (mask_fname) { MRI *mri_mask, *mri_tmp ; mri_tmp = MRIread(mask_fname) ; if (mri_tmp == NULL) ErrorExit(ERROR_BADPARM, "%s: could not load mask volume %s", Progname, mask_fname) ; mri_mask = MRIclone(mri_tmp, NULL) ; MRIcopyLabel(mri_tmp, mri_mask, mask_val) ; MRIdilate(mri_mask, mri_mask) ; MRIdilate(mri_mask, mri_mask) ; MRIdilate(mri_mask, mri_mask) ; MRIdilate(mri_mask, mri_mask) ; MRIfree(&mri_tmp) ; mri_tmp = MRIclone(mri_parc, NULL) ; MRIcopyLabeledVoxels(mri_parc, mri_mask, mri_tmp, mask_val) ; MRIfree(&mri_parc) ; mri_parc = mri_tmp ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_parc, "p.mgz") ; MRIfree(&mri_mask) ; } for (i = 0 ; i < ntrans ; i++) { MRIreplaceValues(mri_parc, mri_parc, trans_in[i], trans_out[i]) ; } sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ; printf("reading input surface %s...\n", fname) ; mris = MRISread(fname) ; if (!mris) ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s", Progname, fname) ; MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ; MRIScomputeMetricProperties(mris) ; if (avgs > 0) MRISaverageVertexPositions(mris, avgs) ; if (FZERO(proj_mm)) { if (MRISreadCurvatureFile(mris, thickness_name) != NO_ERROR) ErrorExit(ERROR_NOFILE, "%s: could not read thickness file %s", Progname, thickness_name) ; } if (color_table_fname) { mris->ct = CTABreadASCII(color_table_fname) ; if (mris->ct == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read color file %s", Progname, color_table_fname) ; } if (sample_from_vol_to_surf) // sample from volume to surface */ { MRIsampleParcellationToSurface(mris, mri_parc) ; } else /* sample from surface to volume */ { for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->ripflag) continue ; if (vno == Gdiag_no) DiagBreak() ; if (!FZERO(proj_mm)) d = proj_mm ; else d = v->curv*proj_frac ; /* halfway out */ x = v->x+d*v->nx ; y = v->y+d*v->ny ; z = v->z+d*v->nz ; MRIsurfaceRASToVoxel(mri_parc, x, y, z, &xw, &yw, &zw) ; v->annotation = v->val = MRIfindNearestNonzero(mri_parc, wsize, xw, yw, zw, ((float)wsize-1)/2) ; if (v->val == 0xffffffff) DiagBreak() ; } } if (replace_label) replace_vertices_with_label(mris, mri_parc, replace_label, proj_mm); if (unknown_label >= 0) { LABEL **labels, *label ; int nlabels, i, biggest_label, most_vertices, nzero ; #define TMP_LABEL 1000 for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->annotation == 0) { v->annotation = TMP_LABEL; nzero++ ; } } printf("%d unknown vertices found\n", nzero) ; MRISsegmentAnnotated(mris, &labels, &nlabels, 10) ; most_vertices = 0 ; biggest_label = -1 ; for (i = 0 ; i < nlabels ; i++) { label = labels[i] ; if (mris->vertices[label->lv[0].vno].annotation == TMP_LABEL) { if (label->n_points > most_vertices) { biggest_label = i ; most_vertices = label->n_points ; } } } if (biggest_label >= 0) { label = labels[biggest_label] ; printf("replacing label # %d with %d vertices " "(vno=%d) with label %d\n", biggest_label, label->n_points, label->lv[0].vno, unknown_label) ; for (i = 0 ; i < label->n_points ; i++) { v = &mris->vertices[label->lv[i].vno] ; v->annotation = v->val = unknown_label ; } } for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->annotation == TMP_LABEL) { v->annotation = 0; nzero++ ; } } printf("after replacement, %d unknown vertices found\n", nzero) ; MRISmodeFilterZeroVals(mris) ; /* get rid of the rest of the unknowns by mode filtering */ for (i = 0 ; i < nlabels ; i++) LabelFree(&labels[i]) ; free(labels) ; } MRIScopyValsToAnnotations(mris) ; if (fix_topology != 0) fix_label_topology(mris, fix_topology) ; if (mode_filter) { printf("mode filtering sample labels...\n") ; #if 0 MRISmodeFilterZeroVals(mris) ; #else MRISmodeFilterVals(mris, mode_filter) ; #endif for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->ripflag) continue ; v->annotation = v->val ; } } /* this will fill in the v->annotation field from the v->val ones */ translate_indices_to_annotations(mris, translation_fname) ; if (label_index >= 0) { int index ; LABEL *area ; printf("writing label to %s...\n", annot_name) ; MRISclearMarks(mris) ; for (vno = 0 ; vno < mris->nvertices ; vno++) { if (vno == Gdiag_no) DiagBreak() ; v = &mris->vertices[vno] ; if (v->annotation > 0) DiagBreak() ; CTABfindAnnotation(mris->ct, v->annotation, &index); if (index == label_index) v->marked = 1 ; } area = LabelFromMarkedSurface(mris) ; if (nclose > 0) { LabelDilate(area, mris, nclose, CURRENT_VERTICES) ; LabelErode(area, mris, nclose) ; } LabelWrite(area, annot_name) ; } else { printf("writing annotation to %s...\n", annot_name) ; MRISwriteAnnotation(mris, annot_name) ; } /* MRISreadAnnotation(mris, fname) ;*/ exit(0) ; return(0) ; /* for ansi */ }
static int replace_vertices_with_label(MRI_SURFACE *mris, MRI *mri, int label, double proj_mm) { int vno, new_label, num=0 ; VERTEX *v ; double d, x, y, z, xw, yw, zw ; MRI *mri_tmp ; mri_tmp = MRIreplaceValues(mri, NULL, label, 0) ; for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->ripflag || v->annotation != label) continue ; if (vno == Gdiag_no) DiagBreak() ; #define MAX_SEARCH_LEN 6 // mm if (proj_mm > 0) { for (d = proj_mm ; d <= MAX_SEARCH_LEN ; d += proj_mm) { x = v->x+d*v->nx ; y = v->y+d*v->ny ; z = v->z+d*v->nz ; MRIsurfaceRASToVoxel(mri, x, y, z, &xw, &yw, &zw) ; // new_label = (int)MRIfindNearestNonzero(mri, wsize, xw, yw, zw, ((float)wsize-1)/2) ; new_label = (int)MRIfindNearestNonzero(mri_tmp, wsize, xw, yw, zw, -1) ; if (new_label != label) { v->annotation = v->val = new_label ; num++ ; break ; } } } else { for (d = proj_mm ; d >= -MAX_SEARCH_LEN ; d += proj_mm) { x = v->x+d*v->nx ; y = v->y+d*v->ny ; z = v->z+d*v->nz ; MRIsurfaceRASToVoxel(mri, x, y, z, &xw, &yw, &zw) ; new_label = (int)MRIfindNearestNonzero(mri_tmp, wsize, xw, yw, zw, ((float)wsize-1)/2) ; if (new_label != label && new_label > 0) { v->annotation = v->val = new_label ; num++ ; break ; } } } if (v->val == label) // couldn't find a new label for it - replace it with 0 to mark it for later reprocessing { v->val = v->annotation = 0 ; if (vno == Gdiag_no) printf("replacing vertex %d label %d with 0 for later processing\n", vno, Gdiag_no) ; } } MRIfree(&mri_tmp) ; printf("%d vertex labels replaced\n", num) ; return(NO_ERROR) ; }
/*---------------------------------------------------------------------- Parameters: Description: ----------------------------------------------------------------------*/ int main(int argc, char *argv[]) { char **av, *subject_name, *cp, *hemi, *surf_name, *annot_name, fname[STRLEN], *name ; int ac, nargs, msec, minutes, label, seconds, i ; double area, total_area ; struct timeb start ; MRIS *mris ; FILE *log_fp ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mris_compute_overlap.c,v 1.6 2011/03/02 00:04:30 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; TimerStart(&start) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 3) usage_exit(1) ; subject_name = argv[1] ; hemi = argv[2] ; surf_name = argv[3] ; annot_name = argv[4] ; if (strlen(sdir) == 0) { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit (ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in env or cmd line", Progname) ; strcpy(sdir, cp) ; } sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ; mris = MRISread(fname) ; if (!mris) ErrorExit (ERROR_NOFILE, "%s: could not read surface from %s", Progname,fname) ; MRIScomputeMetricProperties(mris) ; #if 0 if (in_label >= 0) MRIreplaceValues(mri, mri, in_label, out_label) ; #endif if (compute_pct) total_area = mris->total_area ; else total_area = 1 ; if (MRISreadAnnotation(mris, annot_name) != NO_ERROR) ErrorExit (ERROR_NOFILE, "%s: could not read annot file %s", Progname, annot_name) ; for (i = 5 ; i < argc ; i++) { label = atoi(argv[i]) ; name = annotation_to_name(index_to_annotation(label), NULL) ; printf("processing label %s (%d)...\n", name, label) ; area = MRISannotArea(mris, label) ; if (log_fname) { char fname[STRLEN] ; sprintf(fname, log_fname, label) ; printf("logging to %s...\n", fname) ; log_fp = fopen(fname, "a+") ; if (!log_fp) ErrorExit(ERROR_BADFILE, "%s: could not open %s for writing", Progname, fname) ; } else log_fp = NULL ; if (compute_pct) { printf("%2.3f mm^2 in label %d (%s), " "%%%2.6f of total cortical area (%2.2f)\n", area, label, name, 100.0*(float)area/(float)total_area, total_area) ; if (log_fp) { fprintf(log_fp,"%2.6f\n", 100.0*area/(float)total_area) ; fclose(log_fp) ; } } else { printf("%2.0f mm^2 in label %s (%d)\n", area, name, label) ; if (log_fp) { fprintf(log_fp,"%f\n", area) ; fclose(log_fp) ; } } } msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; if (DIAG_VERBOSE_ON) printf("area calculation took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
int main(int argc, char *argv[]) { char **av, fname[STRLEN], *out_fname, *subject_name, *cp ; int ac, nargs, i, n, noint = 0, options ; int msec, minutes, seconds, nsubjects, input ; struct timeb start ; GCA *gca ; MRI *mri_seg, *mri_tmp, *mri_inputs ; TRANSFORM *transform ; LTA *lta; GCA_BOUNDARY *gcab ; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; TimerStart(&start) ; parms.use_gradient = 0 ; spacing = 8 ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_gcab_train.c,v 1.4 2011/03/16 20:23:33 fischl Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; // parse command line args ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } printf("reading gca from %s\n", argv[1]) ; gca = GCAread(argv[1]) ; if (!gca) exit(Gerror) ; if (!strlen(subjects_dir)) /* hasn't been set on command line */ { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment", Progname); strcpy(subjects_dir, cp) ; if (argc < 4) usage_exit(1) ; } // options parsed. subjects and gca name remaining out_fname = argv[argc-1] ; nsubjects = argc-3 ; for (options = i = 0 ; i < nsubjects ; i++) { if (argv[i+1][0] == '-') { nsubjects-- ; options++ ; } } printf("training on %d subject and writing results to %s\n", nsubjects, out_fname) ; n = 0 ; gcab = GCABalloc(gca, 8, 0, 30, 10, target_label); strcpy(gcab->gca_fname, argv[1]) ; // going through the subject one at a time for (nargs = i = 0 ; i < nsubjects+options ; i++) { subject_name = argv[i+2] ; ////////////////////////////////////////////////////////////// printf("***************************************" "************************************\n"); printf("processing subject %s, %d of %d...\n", subject_name,i+1-nargs, nsubjects); if (stricmp(subject_name, "-NOINT") == 0) { printf("not using intensity information for subsequent subjects...\n"); noint = 1 ; nargs++ ; continue ; } else if (stricmp(subject_name, "-INT") == 0) { printf("using intensity information for subsequent subjects...\n"); noint = 0 ; nargs++ ; continue ; } // reading this subject segmentation sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, seg_dir) ; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "Reading segmentation from %s...\n", fname) ; mri_seg = MRIread(fname) ; if (!mri_seg) ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s", Progname, fname) ; if ((mri_seg->type != MRI_UCHAR) && (mri_seg->type != MRI_FLOAT)) { ErrorExit (ERROR_NOFILE, "%s: segmentation file %s is not type UCHAR or FLOAT", Progname, fname) ; } if (binarize) { int j ; for (j = 0 ; j < 256 ; j++) { if (j == binarize_in) MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ; else MRIreplaceValues(mri_seg, mri_seg, j, 0) ; } } if (insert_fname) { MRI *mri_insert ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, insert_fname) ; mri_insert = MRIread(fname) ; if (mri_insert == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s for insertion", Progname, insert_fname) ; MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ; MRIcopyLabel(mri_insert, mri_seg, insert_label) ; MRIfree(&mri_insert) ; } replaceLabels(mri_seg) ; MRIeraseBorderPlanes(mri_seg, 1) ; for (input = 0 ; input < gca->ninputs ; input++) { //////////// set the gca type ////////////////////////////// // is this T1/PD training? // how can we allow flash data training ??????? // currently checks the TE, TR, FA to be the same for all inputs // thus we cannot allow flash data training. //////////////////////////////////////////////////////////// sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name,input_names[input]); if (DIAG_VERBOSE_ON) printf("reading co-registered input from %s...\n", fname) ; fprintf(stderr, " reading input %d: %s\n", input, fname); mri_tmp = MRIread(fname) ; if (!mri_tmp) ErrorExit (ERROR_NOFILE, "%s: could not read image from file %s", Progname, fname) ; // input check 1 if (getSliceDirection(mri_tmp) != MRI_CORONAL) { ErrorExit (ERROR_BADPARM, "%s: must be in coronal direction, but it is not\n", fname); } // input check 2 if (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1) { ErrorExit (ERROR_BADPARM, "%s: must have 1mm voxel size, but have (%f, %f, %f)\n", fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize); } // input check 3 is removed. now we can handle c_(ras) != 0 case // input check 4 if (i == 0) { TRs[input] = mri_tmp->tr ; FAs[input] = mri_tmp->flip_angle ; TEs[input] = mri_tmp->te ; } else if (!FEQUAL(TRs[input],mri_tmp->tr) || !FEQUAL(FAs[input],mri_tmp->flip_angle) || !FEQUAL(TEs[input], mri_tmp->te)) ErrorExit (ERROR_BADPARM, "%s: subject %s input volume %s: sequence parameters " "(%2.1f, %2.1f, %2.1f)" "don't match other inputs (%2.1f, %2.1f, %2.1f)", Progname, subject_name, fname, mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te, TRs[input], DEGREES(FAs[input]), TEs[input]) ; // first time do the following if (input == 0) { int nframes = gca->ninputs ; /////////////////////////////////////////////////////////// mri_inputs = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, mri_tmp->type, nframes) ; if (!mri_inputs) ErrorExit (ERROR_NOMEMORY, "%s: could not allocate input volume %dx%dx%dx%d", mri_tmp->width, mri_tmp->height, mri_tmp->depth,nframes) ; MRIcopyHeader(mri_tmp, mri_inputs) ; } // -mask option //////////////////////////////////////////// if (mask_fname) { MRI *mri_mask ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, mask_fname); printf("reading volume %s for masking...\n", fname) ; mri_mask = MRIread(fname) ; if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n", Progname, fname) ; MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ; MRIfree(&mri_mask) ; } MRIcopyFrame(mri_tmp, mri_inputs, 0, input) ; MRIfree(&mri_tmp) ; }// end of inputs per subject ///////////////////////////////////////////////////////// // xform_name is given, then we can use the consistent c_(r,a,s) for gca ///////////////////////////////////////////////////////// if (xform_name) { // we read talairach.xfm which is a RAS-to-RAS sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, subject_name, xform_name) ; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) printf("INFO: reading transform file %s...\n", fname); if (!FileExists(fname)) { fprintf(stderr,"ERROR: cannot find transform file %s\n",fname); exit(1); } transform = TransformRead(fname); if (!transform) ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s", Progname, fname); modify_transform(transform, mri_inputs, gca); // Here we do 2 things // 1. modify gca direction cosines to // that of the transform destination (both linear and non-linear) // 2. if ras-to-ras transform, // then change it to vox-to-vox transform (linear case) // modify transform to store inverse also TransformInvert(transform, mri_inputs) ; // verify inverse lta = (LTA *) transform->xform; } else { GCAreinit(mri_inputs, gca); // just use the input value, since dst = src volume transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ; } //////////////////////////////////////////////////////////////////// // train gca //////////////////////////////////////////////////////////////////// // segmentation is seg volume // inputs is the volumes of all inputs // transform is for this subject // noint is whether to use intensity information or not GCABtrain(gcab, mri_inputs, mri_seg, transform, target_label) ; MRIfree(&mri_seg) ; MRIfree(&mri_inputs) ; TransformFree(&transform) ; } GCABcompleteTraining(gcab) ; if (smooth > 0) { printf("regularizing conditional densities with smooth=%2.2f\n", smooth) ; GCAregularizeConditionalDensities(gca, smooth) ; } if (navgs) { printf("applying mean filter %d times to conditional densities\n", navgs) ; GCAmeanFilterConditionalDensities(gca, navgs) ; } printf("writing trained GCAB to %s...\n", out_fname) ; if (GCABwrite(gcab, out_fname) != NO_ERROR) ErrorExit (ERROR_BADFILE, "%s: could not write gca to %s", Progname, out_fname) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRI *mri ; mri = GCAbuildMostLikelyVolume(gca, NULL) ; MRIwrite(mri, "m.mgz") ; MRIfree(&mri) ; } if (histo_fname) { FILE *fp ; int histo_counts[10000], xn, yn, zn, max_count ; GCA_NODE *gcan ; memset(histo_counts, 0, sizeof(histo_counts)) ; fp = fopen(histo_fname, "w") ; if (!fp) ErrorExit(ERROR_BADFILE, "%s: could not open histo file %s", Progname, histo_fname) ; max_count = 0 ; for (xn = 0 ; xn < gca->node_width; xn++) { for (yn = 0 ; yn < gca->node_height ; yn++) { for (zn = 0 ; zn < gca->node_depth ; zn++) { gcan = &gca->nodes[xn][yn][zn] ; if (gcan->nlabels < 1) continue ; if (gcan->nlabels == 1 && IS_UNKNOWN(gcan->labels[0])) continue ; histo_counts[gcan->nlabels]++ ; if (gcan->nlabels > max_count) max_count = gcan->nlabels ; } } } max_count = 20 ; for (xn = 1 ; xn < max_count ; xn++) fprintf(fp, "%d %d\n", xn, histo_counts[xn]) ; fclose(fp) ; } GCAfree(&gca) ; msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("classifier array training took %d minutes" " and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
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; }
MRI * MRIfindBrightNonWM(MRI *mri_T1, MRI *mri_wm) { int width, height, depth, x, y, z, nlabeled, nwhite, xk, yk, zk, xi, yi, zi; BUFTYPE val, wm ; MRI *mri_labeled, *mri_tmp ; mri_labeled = MRIclone(mri_T1, NULL) ; width = mri_T1->width ; height = mri_T1->height ; depth = mri_T1->depth ; for (z = 0 ; z < depth ; z++) { for (y = 0 ; y < height ; y++) { for (x = 0 ; x < width ; x++) { val = MRIgetVoxVal(mri_T1, x, y, z, 0) ; wm = MRIgetVoxVal(mri_wm, x, y, z, 0) ; if (x == 110 && y == 125 && z == 172) /* T1=148 */ { DiagBreak() ; } /* not white matter and bright (e.g. eye sockets) */ if ((wm < WM_MIN_VAL) && (val > 125)) { nwhite = 0 ; for (xk = -1 ; xk <= 1 ; xk++) { xi = mri_T1->xi[x+xk] ; for (yk = -1 ; yk <= 1 ; yk++) { yi = mri_T1->yi[y+yk] ; for (zk = -1 ; zk <= 1 ; zk++) { zi = mri_T1->zi[z+zk] ; if (MRIgetVoxVal(mri_wm, xi, yi, zi, 0) >= WM_MIN_VAL) { nwhite++ ; } } } } #define MIN_WHITE ((3*3*3-1)/2) if (nwhite < MIN_WHITE) { MRIsetVoxVal(mri_labeled, x, y, z, 0, BRIGHT_LABEL) ; } } } } } /* find all connected voxels that are above 115 */ MRIdilateThreshLabel(mri_labeled, mri_T1, NULL, BRIGHT_LABEL, 10,115); MRIclose(mri_labeled, mri_labeled) ; /* expand once more to all neighboring voxels that are bright. At worst we will erase one voxel of white matter. */ mri_tmp = MRIdilateThreshLabel(mri_labeled, mri_T1, NULL, BRIGHT_LABEL,1,100); MRIxor(mri_labeled, mri_tmp, mri_tmp, 1, 255) ; MRIreplaceValues(mri_tmp, mri_tmp, 1, BRIGHT_BORDER_LABEL) ; MRIunion(mri_tmp, mri_labeled, mri_labeled) ; #if 0 fprintf(stderr, "selectively smoothing volume....\n") ; MRIsoapBubbleLabel(mri_T1, mri_labeled, mri_T1, BRIGHT_LABEL, 200) ; #endif if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_labeled, "label.mgh") ; } /* MRIwrite(mri_tmp, "tmp.mgh") ;*/ nlabeled = MRIvoxelsInLabel(mri_labeled, BRIGHT_LABEL) ; fprintf(stderr, "%d bright non-wm voxels segmented.\n", nlabeled) ; MRIfree(&mri_tmp) ; return(mri_labeled) ; }
MRI * MRIfillVentricles(MRI *mri_src, MRI *mri_dst) { int width, height, depth, x, y, z, xk, yk, xi, yi, nfilled, total, s ; MRI *mri_filled, *mri_ventricles = NULL ; MRI_SEGMENTATION *mriseg ; MRI_SEGMENT *mseg ; Real xt, yt, zt ; if (!mri_dst) { mri_dst = MRIclone(mri_src, NULL) ; } width = mri_src->width ; height = mri_src->height ; depth = mri_src->depth ; MRIcopy(mri_src, mri_dst) ; mri_filled = MRIcopy(mri_src, NULL) ; MRIreplaceValues(mri_filled, mri_filled, VENTRICLE_FILL, VENTRICLE_FILL-1) ; /* first fill each coronal slice starting from a background seed */ for (z = 0 ; z < depth ; z++) { total = 0 ; do { nfilled = 0 ; MRIsetVoxVal(mri_filled, 0, 0, z, 0, VENTRICLE_FILL) ; for (y = 0 ; y < height ; y++) { for (x = 0 ; x < width ; x++) { if (MRIgetVoxVal(mri_filled, x, y, z, 0) == VENTRICLE_FILL) { for (yk = -1 ; yk <= 1 ; yk++) { yi = mri_src->yi[y+yk] ; for (xk = -1 ; xk <= 1 ; xk++) { xi = mri_src->xi[x+xk] ; if (!MRIgetVoxVal(mri_filled, xi, yi, z, 0)) { nfilled++ ; MRIsetVoxVal(mri_filled, xi, yi, z, 0, VENTRICLE_FILL) ; } } } } } } total += nfilled ; } while (nfilled > 0) ; } MRIcomplement(mri_filled, mri_filled) ; MRIreplaceValues(mri_filled, mri_filled, 1, VENTRICLE_FILL) ; mriseg = MRIsegment(mri_filled, 1, 255) ; fprintf(stderr, "%d segments found...\n", mriseg->nsegments) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_filled, "exterior_filled.mgh") ; } for (s = 0 ; s < mriseg->nsegments ; s++) { mseg = &mriseg->segments[s] ; if (mseg->nvoxels < 100 || mseg->z1-mseg->z0 < 7) { continue ; } MRIvoxelToTalairach(mri_src, mseg->cx, mseg->cy, mseg->cz, &xt, &yt, &zt); fprintf(stderr, "added segment %d, nvox=%d, bbox [%d:%d, %d:%d, %d:%d]\n" "\tc = %2.1f, %2.1f, %2.1f (tal = %2.1f, %2.1f, %2.1f)\n", s, mseg->nvoxels, mseg->x0, mseg->x1, mseg->y0,mseg->y1,mseg->z0, mseg->z1, mseg->cx, mseg->cy, mseg->cz, xt, yt, zt) ; mri_ventricles = MRIsegmentToImage(mri_filled, mri_ventricles, mriseg, s) ; } MRIfree(&mri_filled) ; MRIsegmentFree(&mriseg) ; /* remove voxels close to the midline so that the cc can still be found */ for (z = 0 ; z < depth ; z++) { for (y = 0 ; y < height ; y++) { for (x = 0 ; x < width ; x++) { MRIvoxelToTalairach(mri_src, x, y, z, &xt, &yt, &zt); if (fabs(xt) < 5) { MRIsetVoxVal(mri_ventricles, x, y, z, 0, 0) ; } } } } if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) { MRIwrite(mri_ventricles, "ventricles.mgh") ; } MRIunion(mri_ventricles, mri_dst, mri_dst) ; MRIfree(&mri_ventricles) ; return(mri_dst) ; }
int main(int argc, char *argv[]) { char **av, fname[STRLEN], *out_fname, *subject_name, *cp, *tp1_name, *tp2_name ; char s1_name[STRLEN], s2_name[STRLEN], *sname ; int ac, nargs, i, n, options, max_index ; int msec, minutes, seconds, nsubjects, input ; struct timeb start ; MRI *mri_seg, *mri_tmp, *mri_in ; TRANSFORM *transform ; // int counts ; int t; RANDOM_FOREST *rf = NULL ; GCA *gca = NULL ; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; TimerStart(&start) ; parms.width = parms.height = parms.depth = DEFAULT_VOLUME_SIZE ; parms.ntrees = 10 ; parms.max_depth = 10 ; parms.wsize = 1 ; parms.training_size = 100 ; parms.training_fraction = .5 ; parms.feature_fraction = 1 ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_rf_long_train.c,v 1.5 2012/06/15 12:22:28 fischl Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; // parse command line args ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (!strlen(subjects_dir)) /* hasn't been set on command line */ { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment", Progname); strcpy(subjects_dir, cp) ; } if (argc < 3) usage_exit(1) ; // options parsed. subjects, tp1 and tp2 and rf name remaining out_fname = argv[argc-1] ; nsubjects = (argc-2)/3 ; for (options = i = 0 ; i < nsubjects ; i++) { if (argv[i+1][0] == '-') { nsubjects-- ; options++ ; } } printf("training on %d subject and writing results to %s\n", nsubjects, out_fname) ; // rf_inputs can be T1, PD, ...per subject if (parms.nvols == 0) parms.nvols = ninputs ; /* gca reads same # of inputs as we read from command line - not the case if we are mapping to flash */ n = 0 ; ////////////////////////////////////////////////////////////////// // set up gca direction cosines, width, height, depth defaults gca = GCAread(gca_name) ; if (gca == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read GCA from %s", Progname, gca_name) ; ///////////////////////////////////////////////////////////////////////// // weird way options and subject name are mixed here ///////////////////////////////////////////////////////// // first calculate mean //////////////////////////////////////////////////////// // going through the subject one at a time max_index = nsubjects+options ; nargs = 0 ; mri_in = NULL ; #ifdef HAVE_OPENMP subject_name = NULL ; sname = NULL ; t = 0 ; // counts = 0 ; would be private input = 0 ; transform = NULL ; tp1_name = tp2_name = NULL ; mri_tmp = mri_seg = NULL ; #pragma omp parallel for firstprivate(tp1_name, tp2_name, mri_in,mri_tmp, input, xform_name, transform, subjects_dir, force_inputs, conform, Progname, mri_seg, subject_name, s1_name, s2_name, sname, t, fname) shared(mri_inputs, transforms, mri_segs,argv) schedule(static,1) #endif for (i = 0 ; i < max_index ; i++) { subject_name = argv[3*i+1] ; tp1_name = argv[3*i+2] ; tp2_name = argv[3*i+3] ; sprintf(s1_name, "%s_%s.long.%s_base", subject_name, tp1_name, subject_name) ; sprintf(s2_name, "%s_%s.long.%s_base", subject_name, tp2_name, subject_name) ; ////////////////////////////////////////////////////////////// printf("***************************************" "************************************\n"); printf("processing subject %s, %d of %d (%s and %s)...\n", subject_name,i+1-nargs, nsubjects, s1_name,s2_name); for (t = 0 ; t < 2 ; t++) { sname = t == 0 ? s1_name : s2_name; // reading this subject segmentation sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, seg_dir) ; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "Reading segmentation from %s...\n", fname) ; mri_seg = MRIread(fname) ; if (!mri_seg) ErrorExit(ERROR_NOFILE, "%s: could not read segmentation file %s", Progname, fname) ; if ((mri_seg->type != MRI_UCHAR) && (make_uchar != 0)) { MRI *mri_tmp ; mri_tmp = MRIchangeType(mri_seg, MRI_UCHAR, 0, 1,1); MRIfree(&mri_seg) ; mri_seg = mri_tmp ; } if (wmsa_fname) { MRI *mri_wmsa ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname, wmsa_fname) ; printf("reading WMSA labels from %s...\n", fname) ; mri_wmsa = MRIread(fname) ; if (mri_wmsa == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read WMSA file %s", fname) ; MRIbinarize(mri_wmsa, mri_wmsa, 1, 0, WM_hypointensities) ; MRIcopyLabel(mri_wmsa, mri_seg, WM_hypointensities) ; lateralize_hypointensities(mri_seg) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON ) { char s[STRLEN] ; sprintf(s, "%s/%s/mri/seg_%s", subjects_dir, subject_name, wmsa_fname) ; MRIwrite(mri_seg, s) ; } } if (binarize) { int j ; for (j = 0 ; j < 256 ; j++) { if (j == binarize_in) MRIreplaceValues(mri_seg, mri_seg, j, binarize_out) ; else MRIreplaceValues(mri_seg, mri_seg, j, 0) ; } } if (insert_fname) { MRI *mri_insert ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, insert_fname) ; mri_insert = MRIread(fname) ; if (mri_insert == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s for insertion", Progname, insert_fname) ; MRIbinarize(mri_insert, mri_insert, 1, 0, insert_label) ; MRIcopyLabel(mri_insert, mri_seg, insert_label) ; MRIfree(&mri_insert) ; } replaceLabels(mri_seg) ; MRIeraseBorderPlanes(mri_seg, 1) ; //////////////////////////////////////////////////////////// if (DIAG_VERBOSE_ON) fprintf(stderr, "Gather all input volumes for the subject %s.\n", subject_name); // inputs must be coregistered // note that inputs are T1, PD, ... per subject (same TE, TR, FA) for (input = 0 ; input < ninputs ; input++) { //////////// set the gca type ////////////////////////////// // is this T1/PD training? // how can we allow flash data training ??????? // currently checks the TE, TR, FA to be the same for all inputs // thus we cannot allow flash data training. //////////////////////////////////////////////////////////// sprintf(fname, "%s/%s/mri/%s", subjects_dir, sname,input_names[input]); if (DIAG_VERBOSE_ON) printf("reading co-registered input from %s...\n", fname) ; fprintf(stderr, " reading input %d: %s\n", input, fname); mri_tmp = MRIread(fname) ; if (!mri_tmp) ErrorExit (ERROR_NOFILE, "%s: could not read image from file %s", Progname, fname) ; // input check 1 if (getSliceDirection(mri_tmp) != MRI_CORONAL) { ErrorExit (ERROR_BADPARM, "%s: must be in coronal direction, but it is not\n", fname); } // input check 2 if (conform && (mri_tmp->xsize != 1 || mri_tmp->ysize != 1 || mri_tmp->zsize != 1)) { ErrorExit (ERROR_BADPARM, "%s: must have 1mm voxel size, but have (%f, %f, %f)\n", fname, mri_tmp->xsize, mri_tmp->ysize, mri_tmp->ysize); } // input check 3 is removed. now we can handle c_(ras) != 0 case // input check 4 if (i == 0) { TRs[input] = mri_tmp->tr ; FAs[input] = mri_tmp->flip_angle ; TEs[input] = mri_tmp->te ; } else if ((force_inputs == 0) && (!FEQUAL(TRs[input],mri_tmp->tr) || !FEQUAL(FAs[input],mri_tmp->flip_angle) || !FEQUAL(TEs[input], mri_tmp->te))) ErrorExit (ERROR_BADPARM, "%s: subject %s input volume %s: sequence parameters " "(%2.1f, %2.1f, %2.1f)" "don't match other inputs (%2.1f, %2.1f, %2.1f)", Progname, subject_name, fname, mri_tmp->tr, DEGREES(mri_tmp->flip_angle), mri_tmp->te, TRs[input], DEGREES(FAs[input]), TEs[input]) ; // first time do the following if (input == 0) { int nframes = ninputs ; /////////////////////////////////////////////////////////// mri_in = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, mri_tmp->type, nframes) ; 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,nframes) ; MRIcopyHeader(mri_tmp, mri_in) ; } // -mask option //////////////////////////////////////////// if (mask_fname) { MRI *mri_mask ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, mask_fname); printf("reading volume %s for masking...\n", fname) ; mri_mask = MRIread(fname) ; if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not open mask volume %s.\n", Progname, fname) ; MRImask(mri_tmp, mri_mask, mri_tmp, 0, 0) ; MRIfree(&mri_mask) ; } MRIcopyFrame(mri_tmp, mri_in, 0, input) ; MRIfree(&mri_tmp) ; }// end of inputs per subject ///////////////////////////////////////////////////////// // xform_name is given, then we can use the consistent c_(r,a,s) for gca ///////////////////////////////////////////////////////// if (xform_name) { // we read talairach.xfm which is a RAS-to-RAS sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, sname, xform_name) ; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) printf("INFO: reading transform file %s...\n", fname); if (!FileExists(fname)) { fprintf(stderr,"ERROR: cannot find transform file %s\n",fname); exit(1); } transform = TransformRead(fname); if (!transform) ErrorExit(ERROR_NOFILE, "%s: could not read transform from file %s", Progname, fname); // modify_transform(transform, mri_in, gca); // Here we do 2 things // 1. modify gca direction cosines to // that of the transform destination (both linear and non-linear) // 2. if ras-to-ras transform, // then change it to vox-to-vox transform (linear case) // modify transform to store inverse also TransformInvert(transform, mri_in) ; } else { // GCAreinit(mri_in, gca); // just use the input value, since dst = src volume transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ; } ///////////////////////////////////////////////////////// if (do_sanity_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) int errs = check(mri_seg, subjects_dir, subject_name); if (errs) { printf( "ERROR: mri_ca_train: possible bad training data! subject:\n" "\t%s/%s\n\n", subjects_dir, subject_name); fflush(stdout) ; sanity_check_badsubj_count++; } } mri_segs[i][t] = mri_seg ; mri_inputs[i][t] = mri_in ; transforms[i][t] = transform ; } } rf = train_rforest(mri_inputs, mri_segs, transforms, nsubjects, gca, &parms, wm_thresh,wmsa_whalf, 2) ; printf("writing random forest to %s\n", out_fname) ; if (RFwrite(rf, out_fname) != NO_ERROR) ErrorExit (ERROR_BADFILE, "%s: could not write rf to %s", Progname, out_fname) ; msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("classifier array training took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
int main(int argc, char *argv[]) { char **av, *cp ; int ac, nargs, i, dof, no_transform, which, sno = 0, nsubjects = 0 ; MRI *mri=0, *mri_mean = NULL, *mri_std=0, *mri_T1=0,*mri_binary=0,*mri_dof=NULL, *mri_priors = NULL ; char *subject_name, *out_fname, fname[STRLEN] ; /* LTA *lta;*/ MRI *mri_tmp=0 ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_make_template.c,v 1.26 2011/03/02 00:04:22 nicks Exp $", "$Name: stable5 $"); 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 (!strlen(subjects_dir)) { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM,"%s: SUBJECTS_DIR not defined in environment.\n", Progname) ; strcpy(subjects_dir, cp) ; } if (argc < 3) usage_exit(1) ; out_fname = argv[argc-1] ; no_transform = first_transform ; if (binary_name) /* generate binarized volume with priors and */ { /* separate means and variances */ for (which = BUILD_PRIORS ; which <= OFF_STATS ; which++) { /* for each subject specified on cmd line */ for (dof = 0, i = 1 ; i < argc-1 ; i++) { if (*argv[i] == '-') /* don't do transform for next subject */ { no_transform = 1 ; continue ; } dof++ ; subject_name = argv[i] ; if (which != BUILD_PRIORS) { sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_T1 = MRIread(fname) ; if (!mri_T1) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s", Progname,fname); } sprintf(fname, "%s/%s/mri/%s",subjects_dir,subject_name,binary_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_binary = MRIread(fname) ; if (!mri_binary) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s", Progname,fname); /* only count voxels which are mostly labeled */ MRIbinarize(mri_binary, mri_binary, WM_MIN_VAL, 0, 100) ; if (transform_fname && no_transform-- <= 0) { sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, subject_name, transform_fname) ; fprintf(stderr, "reading transform %s...\n", fname) ; //////////////////////////////////////////////////////// #if 1 { TRANSFORM *transform ; transform = TransformRead(fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ; mri_tmp = TransformApply(transform, mri_T1, NULL) ; TransformFree(&transform) ; } #else lta = LTAreadEx(fname); if (lta == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n", Progname, fname) ; /* LTAtransform() runs either MRIapplyRASlinearTransform() for RAS2RAS or MRIlinearTransform() for Vox2Vox. */ /* MRIlinearTransform() calls MRIlinearTransformInterp() */ mri_tmp = LTAtransform(mri_T1, NULL, lta); MRIfree(&mri_T1) ; mri_T1 = mri_tmp ; LTAfree(<a); lta = NULL; #endif if (DIAG_VERBOSE_ON) fprintf(stderr, "transform application complete.\n") ; } if (which == BUILD_PRIORS) { mri_priors = MRIupdatePriors(mri_binary, mri_priors) ; } else { if (!mri_mean) { mri_dof = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_UCHAR) ; mri_mean = MRIalloc(mri_T1->width, mri_T1->height,mri_T1->depth,MRI_FLOAT); mri_std = MRIalloc(mri_T1->width,mri_T1->height,mri_T1->depth,MRI_FLOAT); if (!mri_mean || !mri_std) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n", Progname) ; } if (DIAG_VERBOSE_ON) fprintf(stderr, "updating mean and variance estimates...\n") ; if (which == ON_STATS) { MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof, 90, 100, mri_mean, mri_std) ; fprintf(stderr, "T1 = %d, binary = %d, mean = %2.1f\n", (int)MRIgetVoxVal(mri_T1, 141,100,127,0), MRIvox(mri_binary, 141,100,127), MRIFvox(mri_mean, 141,100,127)) ; } else /* computing means and vars for off */ MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof, 0, WM_MIN_VAL-1, mri_mean, mri_std) ; MRIfree(&mri_T1) ; } MRIfree(&mri_binary) ; } if (which == BUILD_PRIORS) { mri = MRIcomputePriors(mri_priors, dof, NULL) ; MRIfree(&mri_priors) ; fprintf(stderr, "writing priors to %s...\n", out_fname) ; } else { MRIcomputeMaskedMeansAndStds(mri_mean, mri_std, mri_dof) ; mri_mean->dof = dof ; fprintf(stderr, "writing T1 means with %d dof to %s...\n", mri_mean->dof, out_fname) ; if (!which) MRIwrite(mri_mean, out_fname) ; else MRIappend(mri_mean, out_fname) ; MRIfree(&mri_mean) ; fprintf(stderr, "writing T1 variances to %s...\n", out_fname); if (dof <= 1) MRIreplaceValues(mri_std, mri_std, 0, 1) ; mri = mri_std ; } if (!which) MRIwrite(mri, out_fname) ; else MRIappend(mri, out_fname) ; MRIfree(&mri) ; } } else { /* for each subject specified on cmd line */ if (xform_mean_fname) { m_xform_mean = MatrixAlloc(4,4,MATRIX_REAL) ; /* m_xform_covariance = MatrixAlloc(12,12,MATRIX_REAL) ;*/ } dof = 0; for (i = 1 ; i < argc-1 ; i++) { if (*argv[i] == '-') { /* don't do transform for next subject */ no_transform = 1 ; continue ; } dof++ ; subject_name = argv[i] ; sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name); fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ; mri_T1 = MRIread(fname) ; if (!mri_T1) ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",Progname,fname); check_mri(mri_T1) ; if (binarize) MRIbinarize(mri_T1, mri_T1, binarize, 0, 1) ; if (erode) { int i ; printf("eroding input %d times\n", erode) ; for (i = 0 ; i < erode ; i++) MRIerode(mri_T1, mri_T1) ; } if (open) { int i ; printf("opening input %d times\n", open) ; for (i = 0 ; i < open ; i++) MRIerode(mri_T1, mri_T1) ; for (i = 0 ; i < open ; i++) MRIdilate(mri_T1, mri_T1) ; } check_mri(mri_T1) ; if (transform_fname) { sprintf(fname, "%s/%s/mri/transforms/%s", subjects_dir, subject_name, transform_fname) ; fprintf(stderr, "reading transform %s...\n", fname) ; //////////////////////////////////////////////////////// #if 1 { TRANSFORM *transform ; transform = TransformRead(fname) ; if (transform == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ; mri_tmp = TransformApply(transform, mri_T1, NULL) ; if (DIAG_VERBOSE_ON) MRIwrite(mri_tmp, "t1.mgz") ; TransformFree(&transform) ; } #else lta = LTAreadEx(fname); if (lta == NULL) ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n", Progname, fname) ; printf("transform matrix -----------------------\n"); MatrixPrint(stdout,lta->xforms[0].m_L); /* LTAtransform() runs either MRIapplyRASlinearTransform() for RAS2RAS or MRIlinearTransform() for Vox2Vox. */ /* MRIlinearTransform() calls MRIlinearTransformInterp() */ mri_tmp = LTAtransform(mri_T1, NULL, lta); printf("----- -----------------------\n"); LTAfree(<a); #endif MRIfree(&mri_T1); mri_T1 = mri_tmp ; // reassign pointers if (DIAG_VERBOSE_ON) fprintf(stderr, "transform application complete.\n") ; } if (!mri_mean) { mri_mean = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ; mri_std = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ; if (!mri_mean || !mri_std) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n", Progname) ; // if(transform_fname == NULL){ if (DIAG_VERBOSE_ON) printf("Copying geometry\n"); MRIcopyHeader(mri_T1,mri_mean); MRIcopyHeader(mri_T1,mri_std); // } } check_mri(mri_mean) ; if (!stats_only) { if (DIAG_VERBOSE_ON) fprintf(stderr, "updating mean and variance estimates...\n") ; MRIaccumulateMeansAndVariances(mri_T1, mri_mean, mri_std) ; } check_mri(mri_mean) ; if (DIAG_VERBOSE_ON) MRIwrite(mri_mean, "t2.mgz") ; MRIfree(&mri_T1) ; no_transform = 0; } /* end loop over subjects */ if (xform_mean_fname) { FILE *fp ; VECTOR *v = NULL, *vT = NULL ; MATRIX *m_vvT = NULL ; int rows, cols ; nsubjects = sno ; fp = fopen(xform_covariance_fname, "w") ; if (!fp) ErrorExit(ERROR_NOFILE, "%s: could not open covariance file %s", Progname, xform_covariance_fname) ; fprintf(fp, "nsubjects=%d\n", nsubjects) ; MatrixScalarMul(m_xform_mean, 1.0/(double)nsubjects, m_xform_mean) ; printf("means:\n") ; MatrixPrint(stdout, m_xform_mean) ; MatrixAsciiWrite(xform_mean_fname, m_xform_mean) ; /* subtract the mean from each transform */ rows = m_xform_mean->rows ; cols = m_xform_mean->cols ; for (sno = 0 ; sno < nsubjects ; sno++) { MatrixSubtract(m_xforms[sno], m_xform_mean, m_xforms[sno]) ; v = MatrixReshape(m_xforms[sno], v, rows*cols, 1) ; vT = MatrixTranspose(v, vT) ; m_vvT = MatrixMultiply(v, vT, m_vvT) ; if (!m_xform_covariance) m_xform_covariance = MatrixAlloc(m_vvT->rows, m_vvT->cols,MATRIX_REAL) ; MatrixAdd(m_vvT, m_xform_covariance, m_xform_covariance) ; MatrixAsciiWriteInto(fp, m_xforms[sno]) ; } MatrixScalarMul(m_xform_covariance, 1.0/(double)nsubjects, m_xform_covariance) ; printf("covariance:\n") ; MatrixPrint(stdout, m_xform_covariance) ; MatrixAsciiWriteInto(fp, m_xform_covariance) ; fclose(fp) ; if (stats_only) exit(0) ; } MRIcomputeMeansAndStds(mri_mean, mri_std, dof) ; check_mri(mri_mean) ; check_mri(mri_std) ; mri_mean->dof = dof ; if (smooth) { MRI *mri_kernel, *mri_smooth ; printf("applying smoothing kernel\n") ; mri_kernel = MRIgaussian1d(smooth, 100) ; mri_smooth = MRIconvolveGaussian(mri_mean, NULL, mri_kernel) ; MRIfree(&mri_kernel) ; MRIfree(&mri_mean) ; mri_mean = mri_smooth ; } fprintf(stderr, "\nwriting T1 means with %d dof to %s...\n", mri_mean->dof, out_fname) ; MRIwrite(mri_mean, out_fname) ; MRIfree(&mri_mean) ; if (dof <= 1) /* can't calculate variances - set them to reasonable val */ { // src dst MRIreplaceValues(mri_std, mri_std, 0, 1) ; } if (!novar) { // mri_std contains the variance here (does it?? I don't think so -- BRF) if (!var_fname) { fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", out_fname); MRIappend(mri_std, out_fname) ; } else { fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", var_fname); MRIwrite(mri_std, var_fname) ; } } MRIfree(&mri_std) ; if (mri) MRIfree(&mri); } /* end if binarize */ return(0) ; }