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) ; }
MRI * MRIsadd(MRI *mri1, MRI *mri2, MRI *mri_dst) { int width, height, depth, x, y, z ; short *p1, *p2, *pdst ; width = mri1->width ; height = mri1->height ; depth = mri1->depth ; if (!mri_dst) { mri_dst = MRIalloc(width, height, depth, mri1->type) ; MRIcopyHeader(mri1, mri_dst) ; } for (z = 0 ; z < depth ; z++) { for (y = 0 ; y < height ; y++) { p1 = &MRISvox(mri1, 0, y, z) ; p2 = &MRISvox(mri2, 0, y, z) ; pdst = &MRISvox(mri_dst, 0, y, z) ; for (x = 0 ; x < width ; x++) *pdst++ = *p1++ + *p2++ ; } } return(mri_dst) ; }
static MRI * compute_bias(MRI *mri_src, MRI *mri_dst, MRI *mri_bias) { int x, y, z ; float bias, src, dst ; if (!mri_bias) mri_bias = MRIalloc (mri_src->width, mri_src->height, mri_src->depth, MRI_FLOAT) ; MRIcopyHeader(mri_src, mri_bias) ; for (x = 0 ; x < mri_src->width ; x++) { for (y = 0; y < mri_src->height ; y++) { for (z = 0 ; z < mri_src->depth ; z++) { src = MRIgetVoxVal(mri_src, x, y, z, 0) ; dst = MRIgetVoxVal(mri_dst, x, y, z, 0) ; if (FZERO(src)) { bias = 1 ; } else { bias = dst/src ; } MRIsetVoxVal(mri_bias, x, y, z, 0, bias) ; } } } return(mri_bias) ; }
static MRI * make_atrophy_map(MRI *mri_time1, MRI *mri_time2, MRI *mri_dst, TRANSFORM *transform1, TRANSFORM *transform2, int *gray_labels, int ngray, int *csf_labels, int ncsf) { int x, y, z, label1, label2, n, found, xp, yp, zp, spacing ; GCA_MORPH_NODE *gcamn1, *gcamn2 ; GCA_MORPH *gcam1, *gcam2 ; float volume ; if (mri_dst == NULL) { mri_dst = MRIalloc(mri_time1->width, mri_time1->height, mri_time1->depth, MRI_FLOAT) ; MRIcopyHeader(mri_time1, mri_dst) ; } gcam1 = (GCA_MORPH*)transform1->xform ; gcam2 = (GCA_MORPH*)transform2->xform ; spacing = gcam1->spacing ; for (x = 0 ; x < mri_time1->width ; x++) { xp = x / spacing; for (y = 0 ; y < mri_time1->height ; y++) { yp = y / spacing; for (z = 0 ; z < mri_time1->depth ; z++) { if (x == Gx && y == Gy && z == Gz) DiagBreak() ; label1 = MRIgetVoxVal(mri_time1, x, y, z, 0) ; label2 = MRIgetVoxVal(mri_time2, x, y, z, 0) ; if (label1 == label2) continue ; /* if label1 was one of the gray types and label2 one of the csf, call it atrophy */ for (found = n = 0 ; n < ngray ; n++) if (label1 == gray_labels[n]) { found = 1 ; break ; } if (found == 0) continue ; for (found = n = 0 ; n < ncsf ; n++) if (label2 == csf_labels[n]) { found = 1 ; break ; } if (found == 0) continue ; zp = z / spacing; gcamn1 = &gcam1->nodes[xp][yp][zp] ; gcamn2 = &gcam2->nodes[xp][yp][zp] ; volume = 0 ; if (FZERO(gcamn1->area) == 0) volume += gcamn1->orig_area / gcamn1->area ; if (FZERO(gcamn2->area) == 0) volume += gcamn2->orig_area / gcamn2->area ; MRIsetVoxVal(mri_dst, x, y, z, 0, volume) ; } } } return(mri_dst) ; }
static int write_snapshot(MRI *mri_target, MRI *mri_source, MATRIX *m_vox_xform, GCA_MORPH_PARMS *parms, int fno, int conform, char *in_fname) { MRI *mri_aligned ; char fname[STRLEN] ; if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) { printf("source->target vox->vox transform:\n") ; MatrixPrint(stdout, m_vox_xform) ; } if (conform || 1) { mri_aligned = MRIalloc(mri_target->width, mri_target->height, mri_target->depth,mri_source->type); MRIcopyHeader(mri_target, mri_aligned) ; MRIlinearTransformInterp(mri_source, mri_aligned, m_vox_xform, SAMPLE_NEAREST); } else { mri_aligned = MRITransformedCenteredMatrix(mri_source, mri_target, m_vox_xform) ; } if (in_fname) sprintf(fname, "%s_%s", parms->base_name, in_fname) ; else sprintf(fname, "%s_%03d", parms->base_name, fno) ; MRIwriteImageViews(mri_aligned, fname, IMAGE_SIZE) ; if (in_fname) sprintf(fname, "%s_%s.mgz", parms->base_name, in_fname) ; else sprintf(fname, "%s_%03d.mgz", parms->base_name, fno) ; printf("writing snapshot to %s...\n", fname) ; MRIwrite(mri_aligned, fname) ; MRIfree(&mri_aligned) ; { #if 0 mri_aligned = MRIsrcTransformedCentered(mri_source, mri_target, m_vox_xform, SAMPLE_NEAREST) ; #else mri_aligned = MRITransformedCenteredMatrix(mri_source, mri_target, m_vox_xform) ; #endif if (in_fname) sprintf(fname, "orig_%s_%s.mgz", parms->base_name, in_fname) ; else sprintf(fname, "orig_%s_%03d.mgz", parms->base_name, fno) ; printf("writing snapshot to %s...\n", fname) ; MRIwrite(mri_aligned, fname) ; MRIfree(&mri_aligned) ; } return(NO_ERROR) ; }
// modify transform to vox-to-vox static void modify_transform(TRANSFORM *transform, MRI *mri_inputs, GCA *gca) { LTA *lta=0; MATRIX *i_to_r=0, *r_to_i=0, *tmpmat=0, *vox2vox; MRI *mri_buf = 0; GCA_MORPH *gcam = 0; static int warned = 0; // temp buf to get the transform mri_buf = MRIallocHeader(mri_inputs->width, mri_inputs->height, mri_inputs->depth, mri_inputs->type,1); MRIcopyHeader(mri_inputs, mri_buf); ////////////////////////////////////////////////////////////////////////// // non-linear transform case ////////////////////////////////////////////////////////////////////////// if (transform->type == MORPH_3D_TYPE) { gcam = (GCA_MORPH *) transform->xform; if (gcam->atlas.valid) // means it contains the dst volume information { mri_buf->c_r = gcam->atlas.c_r; mri_buf->c_a = gcam->atlas.c_a; mri_buf->c_s = gcam->atlas.c_s; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf (stderr, "INFO: modified c_(r,a,s) using the non-linear " "transform dst value.\n"); warned = 1; } } else // this is an old 3d, I should use c_(ras) = 0 { mri_buf->c_r = 0; mri_buf->c_a = 0; mri_buf->c_s = 0; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "INFO: modified c_(r,a,s) = 0.\n"); warned = 1; } } } //////////////////////////////////////////////////////////////////////////// /// linear transform case //////////////////////////////////////////////////////////////////////////// else if (transform->type == LINEAR_VOX_TO_VOX) { lta = (LTA *) (transform->xform); // modify using the xform dst if (lta->xforms[0].dst.valid) { mri_buf->c_r = lta->xforms[0].dst.c_r; mri_buf->c_a = lta->xforms[0].dst.c_a; mri_buf->c_s = lta->xforms[0].dst.c_s; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "INFO: modified c_(r,a,s) using the xform dst.\n"); warned = 1; } } else // keep the old behavior { mri_buf->c_r = 0; mri_buf->c_a = 0; mri_buf->c_s = 0; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "INFO: modified c_(r,a,s) = 0.\n"); warned = 1; } } } else if (transform->type == LINEAR_RAS_TO_RAS) { lta = (LTA *) (transform->xform); // modify using the xform dst if (lta->xforms[0].dst.valid) { mri_buf->c_r = lta->xforms[0].dst.c_r; mri_buf->c_a = lta->xforms[0].dst.c_a; mri_buf->c_s = lta->xforms[0].dst.c_s; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf(stderr, "INFO: modified c_(r,a,s) using the xform dst\n"); warned = 1; } } // dst invalid else if (getenv("USE_AVERAGE305"))// use average_305 value // (usually ras-to-ras comes from MNI transform) { mri_buf->c_r = -0.095; mri_buf->c_a = -16.51; mri_buf->c_s = 9.75; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) { fprintf (stderr, "INFO: modified c_(r,a,s) using average_305 value\n"); fprintf (stderr, "INFO: if this is not preferred, set environment " "variable NO_AVERAGE305\n"); } warned = 1; } } else // keep old behavior { mri_buf->c_r = 0; mri_buf->c_a = 0; mri_buf->c_s = 0; if (warned == 0) { if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) fprintf (stderr, "INFO: xform.dst invalid thus modified c_(r,a,s) = 0.\n"); warned = 1; } } ///////////////////////////////////////////////////////////////// printf("INFO: original RAS-to-RAS transform\n"); MatrixPrint(stdout, lta->xforms[0].m_L); // going from vox->RAS->TalRAS i_to_r = extract_i_to_r(mri_inputs); tmpmat = MatrixMultiply(lta->xforms[0].m_L, i_to_r, NULL); r_to_i = extract_r_to_i(mri_buf); // going from TalRAS -> voxel vox2vox = MatrixMultiply(r_to_i, tmpmat,NULL ); printf("INFO: modified VOX-to-VOX transform\n"); MatrixPrint(stdout, vox2vox); // store it MatrixCopy(vox2vox, lta->xforms[0].m_L); // now mark it as vox-to-vox transform->type = LINEAR_VOX_TO_VOX; // free up memory MatrixFree(&r_to_i); MatrixFree(&i_to_r); MatrixFree(&tmpmat); MatrixFree(&vox2vox); } ///////////////////////////////////////////////////////////////// // OK now we know what the target c_(ras) should be // we reset c_(ras) value for GCA node and priors GCAreinit(mri_buf, gca); MRIfree(&mri_buf); }
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) ; }
/*---------------------------------------------------------------*/ MRI *fMRIhsynth(MRI *res, MRI *mask, int DoTNorm) { int c,r,s,f,nvox; double val; MRI *hsynth, *tvar=NULL; double *svar, svarsum, tstdvox; // Compute temporal variance at each voxel if(DoTNorm) tvar = fMRIcovariance(res, 0, -1, mask, NULL); // Compute spatial variance at each frame svar = (double *) calloc(res->nframes,sizeof(double)); svarsum = 0; for (f=0; f < res->nframes; f++) { svar[f] = 0; nvox = 0; for (c=0; c < res->width; c++) { for (r=0; r < res->height; r++) { for (s=0; s < res->depth; s++) { if(mask && MRIgetVoxVal(mask,c,r,s,0) == 0) continue; val = MRIgetVoxVal(res,c,r,s,f); if(DoTNorm){ tstdvox = sqrt(MRIgetVoxVal(tvar,c,r,s,0)); val /= tstdvox; } svar[f] += (val*val); nvox ++; } } } svar[f] /= nvox; svarsum += svar[f]; } for (f=0; f < res->nframes; f++) svar[f] /= (svarsum/res->nframes); for (f=0; f < res->nframes; f++) printf("%2d %g\n",f,svar[f]); // Synth noise that is both spatially and temporally white and gaussian hsynth = MRIrandn(res->width, res->height, res->depth, res->nframes, 0, 1, NULL); MRIcopyHeader(res,hsynth); // Scale by frame. Noise is still independent across // space and time, but it is no longer homogeneous. for (f=0; f < res->nframes; f++) { for (c=0; c < res->width; c++) { for (r=0; r < res->height; r++) { for (s=0; s < res->depth; s++) { if(mask && MRIgetVoxVal(mask,c,r,s,0) == 0) { MRIsetVoxVal(hsynth,c,r,s,f,0); continue; } val = MRIgetVoxVal(hsynth,c,r,s,f); val *= sqrt(svar[f]); MRIsetVoxVal(hsynth,c,r,s,f,val); } } } } free(svar); if(DoTNorm) MRIfree(&tvar); return(hsynth); }
int main(int argc, char *argv[]) { char **av, *in_fname; int ac, nargs, i, j, x, y, z, width, height, depth; MRI *mri_flash[MAX_IMAGES], *mri_label, *mri_mask, *mri_tmp; int msec, minutes, seconds, nvolumes, nvolumes_total ; struct timeb start ; float max_val, min_val, value; float *LDAmean1, *LDAmean2, *LDAweight; int label; double sum_white, sum_gray; int count_white, count_gray; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_ms_LDA.c,v 1.4 2011/03/02 00:04:23 nicks Exp $", "$Name: $"); 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 < 2) usage_exit(1) ; printf("command line parsing finished\n"); if (have_weight == 0 && ldaflag == 0) { printf("Use -lda option to specify two class labels to optimize CNR on \n"); usage_exit(0); } if (have_weight == 0 && label_fname == NULL) { printf("Use -label option to specify file for segmentation \n"); usage_exit(0); } if (have_weight == 1 && weight_fname == NULL) { printf("Use -weight option to specify file for input LDA weights \n") ; usage_exit(0); } if (have_weight == 1 && synth_fname == NULL) { printf("Use -synth option to specify file for output synthesized volume \n") ; usage_exit(0); } ////////////////////////////////////////////////////////////////////////////////// /*** Read in the input multi-echo volumes ***/ nvolumes = 0 ; for (i = 1 ; i < argc; i++) { in_fname = argv[i] ; printf("reading %s...\n", in_fname) ; mri_flash[nvolumes] = MRIread(in_fname) ; if (mri_flash[nvolumes] == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read volume %s", Progname, in_fname) ; /* conform will convert all data to UCHAR, which will reduce data resolution*/ printf("%s read in. \n", in_fname) ; if (conform) { printf("embedding and interpolating volume\n") ; mri_tmp = MRIconform(mri_flash[nvolumes]) ; MRIfree(&mri_flash[nvolumes]); mri_flash[nvolumes] = mri_tmp ; } /* Change all volumes to float type for convenience */ if (mri_flash[nvolumes]->type != MRI_FLOAT) { printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type); printf("Change data to float type \n"); mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1); MRIfree(&mri_flash[nvolumes]); mri_flash[nvolumes] = mri_tmp; //swap } nvolumes++ ; } printf("All data read in\n"); /////////////////////////////////////////////////////////////////////////// nvolumes_total = nvolumes ; /* all volumes read in */ for (i = 0 ; i < nvolumes ; i++) { for (j = i+1 ; j < nvolumes ; j++) { if ((mri_flash[i]->width != mri_flash[j]->width) || (mri_flash[i]->height != mri_flash[j]->height) || (mri_flash[i]->depth != mri_flash[j]->depth)) ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n", Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width, mri_flash[i]->height, mri_flash[i]->depth, mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ; } } width = mri_flash[0]->width; height = mri_flash[0]->height; depth = mri_flash[0]->depth; if (label_fname != NULL) { mri_label = MRIread(label_fname); if (!mri_label) ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n", Progname, label_fname); if ((mri_label->width != mri_flash[0]->width) || (mri_label->height != mri_flash[0]->height) || (mri_label->depth != mri_flash[0]->depth)) ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname); /* if(mri_label->type != MRI_UCHAR) ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */ } if (mask_fname != NULL) { mri_mask = MRIread(mask_fname); if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n", Progname, mask_fname); if ((mri_mask->width != mri_flash[0]->width) || (mri_mask->height != mri_flash[0]->height) || (mri_mask->depth != mri_flash[0]->depth)) ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname); if (mri_mask->type != MRI_UCHAR) ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname); } else { if (have_weight == 1) noise_threshold = - 1e20; printf("Threshold input vol1 at %g to create mask \n", noise_threshold); printf("this threshold is useful to process skull-stripped data \n"); mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR); MRIcopyHeader(mri_flash[0], mri_mask); /* Simply set mask to be 1 everywhere */ for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if ((float)MRIgetVoxVal(mri_flash[0], x, y,z,0) < noise_threshold) MRIvox(mri_mask, x, y,z) = 0; else MRIvox(mri_mask, x, y,z) = 1; } } /* Normalize input volumes */ if (normflag) { printf("Normalize input volumes to zero mean, variance 1\n"); for (i=0; i <nvolumes_total; i++) { mri_flash[i] = MRInormalizeXH(mri_flash[i], mri_flash[i], mri_mask); } printf("Normalization done.\n"); } if (0) { printf("Using both hemi-sphere by changing rh-labels\n"); for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { label = (int)MRIgetVoxVal(mri_label, x, y,z,0); if (label == 41) /* white matter */ MRIsetVoxVal(mri_label, x, y, z, 0, 2); else if (label == 42) /* gm */ MRIsetVoxVal(mri_label, x, y, z, 0, 3); } } if (debug_flag && window_flag) { /* Limit LDA to a local window */ printf("Local window size = %d\n", window_size); window_size /= 2; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIvox(mri_mask, x, y,z) == 0) continue; if (z < (Gz - window_size) || z >(Gz + window_size) || y <(Gy - window_size) || y > (Gy + window_size) || x < (Gx - window_size) || x > (Gx + window_size)) MRIvox(mri_mask, x, y,z) = 0; } } LDAmean1 = (float *)malloc(nvolumes_total*sizeof(float)); LDAmean2 = (float *)malloc(nvolumes_total*sizeof(float)); LDAweight = (float *)malloc(nvolumes_total*sizeof(float)); if (have_weight) { printf("Read in LDA weights from weight-file\n"); input_weights_to_file(LDAweight, weight_fname, nvolumes_total); } else { /* compute LDA weights */ printf("Compute LDA weights to maximize CNR for region %d and region %d\n", class1, class2); /* Compute class means */ update_LDAmeans(mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2); printf("class means computed \n"); /* Compute Fisher's LDA weights */ computeLDAweights(LDAweight, mri_flash, mri_label, mri_mask, LDAmean1, LDAmean2, nvolumes_total, class1, class2); if (weight_fname != NULL) { output_weights_to_file(LDAweight, weight_fname, nvolumes_total); } } printf("LDA weights are: \n"); for (i=0; i < nvolumes_total; i++) { printf("%g ", LDAweight[i]); } printf("\n"); if (synth_fname != NULL) { /* linear projection of input volumes to a 1D volume */ min_val = 10000.0; max_val = -10000.0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue; value = 0.0; for (i=0; i < nvolumes_total; i++) { value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i]; } // if(value < 0) value = 0; if (max_val < value) max_val = value; if (min_val > value) min_val = value; /* Borrow mri_flash[0] to store the float values first */ MRIFvox(mri_flash[0], x, y, z) = value; } printf("max_val = %g, min_val = %g \n", max_val, min_val); /* Check to make sure class1 has higher intensity than class2 */ if (have_weight == 0) { sum_white =0; count_white = 0; sum_gray = 0; count_gray = 0; for (z=0; z < depth; z++) { if (count_white > 300 && count_gray > 300) break; for (y=0; y< height; y++) { for (x=0; x < width; x++) { if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class1) { sum_white += MRIFvox(mri_flash[0], x, y, z); count_white += 1; } else if ((int)MRIgetVoxVal(mri_label, x, y,z,0) == class2) { sum_gray += MRIFvox(mri_flash[0], x, y, z); count_gray += 1; } } } } if (count_white > 1 && count_gray > 1) { if (sum_white *count_gray < sum_gray*count_white) { for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue; value = MRIFvox(mri_flash[0], x, y, z); MRIFvox(mri_flash[0], x, y, z) = max_val - value; } max_val = max_val - min_val; min_val = 0; } } } /* The following is copied to be consistent with mri_synthesize */ /* Don't know why add min_val, minus should make more sense */ for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) { MRIFvox(mri_flash[0], x, y, z) = 0; /*background always set to 0 */ continue; } /* Borrow mri_flash[0] to store the float values first */ if (shift_value > 0) { value = MRIFvox(mri_flash[0], x, y, z) + shift_value; if (value < 0) value = 0; MRIFvox(mri_flash[0], x, y, z) = value; } else if (mask_fname != NULL) MRIFvox(mri_flash[0], x, y, z) -= min_val; } MRIfree(&mri_mask); if (mri_flash[0]->type == out_type) { mri_mask = MRIcopy(mri_flash[0], mri_mask); } else { mri_mask = MRIchangeType(mri_flash[0], out_type, 0.1, 0.99, 0); } /* Scale output to [0, 255] */ if (0) { for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue; value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */ if (value > 255.0) value = 255.0; if (value < 0) value = 0; /* Borrow mri_flash[0] to store the float values first */ MRIvox(mri_mask, x, y, z) = (BUFTYPE) value; } } /* Output synthesized volume */ MRIwrite(mri_mask, synth_fname); } free(LDAmean1); free(LDAmean2); free(LDAweight); msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ; MRIfree(&mri_mask); if (label_fname) MRIfree(&mri_label); for (i=0; i < nvolumes_total; i++) { MRIfree(&mri_flash[i]); } exit(0); }
int main(int argc, char *argv[]) { char **av, *in_vol, *out_vol; int ac, nargs; MRI *mri_in, *mri_out, *mri_tmp ; LTA *lta = 0; MATRIX *i_to_r_src = 0; /* src geometry of the input LTA */ MATRIX *V_to_V = 0; /* Final voxel-to-voxel transform */ MATRIX *r_to_i_dst = 0; /* dst geometry of the input LTA */ MATRIX *m_tmp = 0; MATRIX *i_to_r_reg = 0; /* i_to_r of the volume after registration */ MATRIX *r_to_i_out = 0; /* r_to_i of the final output volume */ VOL_GEOM vgm_in; int x, y, z; double maxV, minV, value; // MATRIX *i_to_r, *r_to_i; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_transform_to_COR.c,v 1.8 2011/03/02 00:04:55 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) usage_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 < 3) usage_exit(0) ; in_vol = argv[1] ; out_vol = argv[2] ; printf("reading volume from %s...\n", in_vol) ; mri_in = MRIread(in_vol) ; if (!mri_in) ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname, in_vol) ; /* Convert mri_in to float type */ /* double would be more accurate */ if (mri_in->type != MRI_FLOAT) { printf("Input volume type is %d\n", mri_in->type); printf("Change input volume to float type for convenience and accuracy"); mri_tmp = MRIchangeType(mri_in, MRI_FLOAT, 0, 1.0, 1); MRIfree(&mri_in); mri_in = mri_tmp; //swap } /* Get input volume geometry, which is needed to compute i_to_r * and r_to_i of input volume. Note that i_to_r and r_to_i assumed * a certain prespecified c_r, c_a, c_s */ getVolGeom(mri_in, &vgm_in); maxV = -10000.0; minV = 10000.0; for (z=0; z < mri_in->depth; z++) for (y=0; y< mri_in->height; y++) for (x=0; x < mri_in->width; x++) { if (MRIFvox(mri_in, x, y, z) > maxV ) maxV = MRIFvox(mri_in, x, y,z) ; if (MRIFvox(mri_in, x, y, z) < minV ) minV = MRIFvox(mri_in, x, y,z) ; } printf("Input volume has max = %g, min =%g\n", maxV, minV); printf("Scale input volume by %g \n", scale); maxV = -10000.0; minV = 10000.0; for (z=0; z < mri_in->depth; z++) for (y=0; y< mri_in->height; y++) for (x=0; x < mri_in->width; x++) { MRIFvox(mri_in, x, y, z) *= scale; if (MRIFvox(mri_in, x, y, z) > maxV ) maxV = MRIFvox(mri_in, x, y,z) ; if (MRIFvox(mri_in, x, y, z) < minV ) minV = MRIFvox(mri_in, x, y,z) ; } printf("Input volume after scaling has max = %g, min =%g\n", maxV, minV); /* Try to compute the Voxel_to_Voxel transform from the input volume * and the registration target/reference volume! * If no registration is involved, vox_to_vox is simply identity */ /* Things become more complicated when allowing inverse transform */ if (transform_flag) { int transform_type; printf("INFO: Applying transformation from file %s...\n", transform_fname); transform_type = TransformFileNameType(transform_fname); /* Read in LTA transform file name */ if (transform_type == MNI_TRANSFORM_TYPE || transform_type == TRANSFORM_ARRAY_TYPE || transform_type == REGISTER_DAT || transform_type == FSLREG_TYPE ) { printf("Reading transform ...\n"); lta = LTAreadEx(transform_fname) ; if (!lta) ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s", Progname, transform_fname) ; if (transform_type == FSLREG_TYPE) { if (lta_src == 0 || lta_dst == 0) { fprintf(stderr, "ERROR: fslmat does not have information on the src and dst volumes\n"); fprintf(stderr, "ERROR: you must give options '-src' and '-dst' to specify the src and dst volume infos for the registration\n"); } LTAmodifySrcDstGeom(lta, lta_src, lta_dst); // add src and dst information //The following is necessary to interpret FSLMAT correctly!!! LTAchangeType(lta, LINEAR_VOX_TO_VOX); } if (lta->xforms[0].src.valid == 0) { if (lta_src == 0) { fprintf(stderr, "The transform does not have the valid src volume info.\n"); fprintf(stderr, "Either you give src volume info by option -src or\n"); fprintf(stderr, "make the transform to have the valid src info.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information } } if (lta->xforms[0].dst.valid == 0) { if (lta_dst == 0) { fprintf(stderr, "The transform does not have the valid dst volume info.\n"); fprintf(stderr, "Either you give src volume info by option -dst or\n"); fprintf(stderr, "make the transform to have the valid dst info.\n"); fprintf(stderr, "If the dst was average_305, then you can set\n"); fprintf(stderr, "environmental variable USE_AVERAGE305 true\n"); fprintf(stderr, "instead.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add dst information } } // The following procedure aims to apply an LTA computed from COR format to a volume in non-COR format, or vice versa, as long as they share the same RAS // first change to LINEAR RAS_TO_RAS using old info if (lta->type != LINEAR_RAS_TO_RAS) { LTAchangeType(lta, LINEAR_RAS_TO_RAS); } // now possiblly reset the src and dst if (lta_src != NULL) { //always trust the user LTAmodifySrcDstGeom(lta, lta_src, NULL); } if (lta_dst != NULL) { //always trust the user LTAmodifySrcDstGeom(lta, NULL, lta_dst); } if (lta->type == LINEAR_RAS_TO_RAS) { /* Convert it to VOX_TO_VOX */ /* VOXELsrc_to_VOXELdst = R2Vdst*R2Rlta*V2Rsrc */ /* Note whether the input should be identical to src or dst here depends * on whether the LTA here is the direct or inverse transform */ i_to_r_src = vg_i_to_r(<a->xforms[0].src); r_to_i_dst = vg_r_to_i(<a->xforms[0].dst); if (!r_to_i_dst || !i_to_r_src) ErrorExit(ERROR_BADFILE, "%s: failed to extract volume geometries from input LTA file",Progname); m_tmp = MatrixMultiply(lta->xforms[0].m_L, i_to_r_src, NULL); V_to_V = MatrixMultiply(r_to_i_dst, m_tmp, NULL); MatrixFree(&m_tmp); MatrixFree(&i_to_r_src); MatrixFree(&r_to_i_dst); } } else { fprintf(stderr, "unknown transform type in file %s\n", transform_fname); exit(1); } if (invert_flag) { /* Geometry of input volume should match that of the dst of the LTA */ if (MYvg_isEqual(<a->xforms[0].dst, &vgm_in) == 0) { ErrorExit(ERROR_BADFILE, "%s: dst volume of lta doesn't match that of input volume",Progname); } i_to_r_reg = vg_i_to_r(<a->xforms[0].src); if (!i_to_r_reg) ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname); m_tmp = MatrixInverse(V_to_V, NULL); if (!m_tmp) ErrorExit(ERROR_BADPARM, "%s: transform is singular!", Progname); MatrixFree(&V_to_V); V_to_V = m_tmp; } else { /* Geometry of input volume should match that of the src of the LTA */ if (MYvg_isEqual(<a->xforms[0].src, &vgm_in) == 0) { ErrorExit(ERROR_BADFILE, "%s: src volume of lta doesn't match that of input volume",Progname); } i_to_r_reg = vg_i_to_r(<a->xforms[0].dst); if (!i_to_r_reg) ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r of registered volume from LTA",Progname); } } else { /* No registration transform need be applied */ V_to_V = MatrixIdentity(4, NULL); i_to_r_reg = extract_i_to_r(mri_in); if (!i_to_r_reg) ErrorExit(ERROR_BADFILE, "%s: failed to extract i_to_r from input volume",Progname); } /* Now need to find the vox-to-vox transformation between registered volume * (or input volume itself if no registration involved) and the output * volume, either in COR format or as the out-like volume */ /* Given a volume with a certain i_to_r, we need to compute the necessary * vox-to-voxel transform to change its i_to_r to like another volume. * The vox-to-vox is equal to R2V(r_to_i)_likevol*i_to_r_current_vol. */ if (out_like_fname) { mri_tmp = MRIread(out_like_fname) ; if (!mri_tmp) ErrorExit(ERROR_NOFILE, "%s: could not read template volume from %s",out_like_fname) ; /* out_type = mri_tmp->type; */ /* specify the out-type to float initially so as not to lose accuracy * during reslicing, will change type to correct type later. */ mri_out = MRIalloc(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT) ; MRIcopyHeader(mri_tmp, mri_out) ; MRIfree(&mri_tmp); } else /* assume output is in COR format */ { mri_out = MRIalloc(256, 256, 256, MRI_FLOAT) ; /* out_type = MRI_UCHAR; */ /* Who says MRIlinearTransformInterp will change the header?? * I don't think so! */ //E/ set xyzc_ras to coronal ones.. - these'll get zorched //by MRIlinearTransformInterp() - copy again later - is there //any use in having them here now? yes, so we can pass mri_out //to the ras2vox fns. mri_out->imnr0 = 1; /* what's this? */ mri_out->imnr1 = 256; /* what's this? */ mri_out->thick = 1.0; mri_out->ps = 1.0; /* what's this? */ mri_out->xsize = mri_out->ysize = mri_out->zsize = 1.0; mri_out->xstart = mri_out->ystart = mri_out->zstart = -128.0; mri_out->xend = mri_out->yend = mri_out->zend = 128.0; mri_out->x_r =-1; mri_out->y_r = 0; mri_out->z_r = 0; mri_out->x_a = 0; mri_out->y_a = 0; mri_out->z_a = 1; mri_out->x_s = 0; mri_out->y_s =-1; mri_out->z_s = 0; /* In this case, the RAS itself is not fully determined, i.e., c_ras. * It's quite arbitrary, different values just change the final * sitting of the volume inside the RAS system. */ /* NO! The C_RAS has to be set correctly, depending which target * volume the previous Vox_to_Vox transformation assumes! * When a registration is involved, the target volume is either * the src of LTA (direct) or the dst (inverse transform). When * just change format, the target volume is the input itself!! */ if (transform_flag) { if (invert_flag) { mri_out->c_r = lta->xforms[0].src.c_r; mri_out->c_a = lta->xforms[0].src.c_a; mri_out->c_s = lta->xforms[0].src.c_s; } else { mri_out->c_r = lta->xforms[0].dst.c_r; mri_out->c_a = lta->xforms[0].dst.c_a; mri_out->c_s = lta->xforms[0].dst.c_s; } } else { mri_out->c_r = mri_in->c_r; mri_out->c_a = mri_in->c_a; mri_out->c_s = mri_in->c_s; } mri_out->ras_good_flag=1; /* What does this flag mean ? */ /* since output is just transformed input */ MRIcopyPulseParameters(mri_in, mri_out) ; } /* Compute the final input-to-output VOX_to_VOX transformation matrix */ r_to_i_out = extract_r_to_i(mri_out); m_tmp = MatrixMultiply(r_to_i_out, i_to_r_reg, NULL); V_to_V = MatrixMultiply(m_tmp, V_to_V, V_to_V); MatrixFree(&m_tmp); printf("InterpMethod = %d\n", InterpMethod); /* Modify the MyMRIlinearTr... if I want to implement my cubic-B-spline * interpolation method. Otherwise, unnecessary */ /* mri_out = MyMRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod); */ if (InterpMethod == SAMPLE_BSPLINE) mri_out = MRIlinearTransformInterpBSpline(mri_in, mri_out, V_to_V, SplineDegree); else mri_out = MRIlinearTransformInterp(mri_in, mri_out, V_to_V, InterpMethod); maxV = -10000.0; minV = 10000.0; for (z=0; z < mri_out->depth; z++) for (y=0; y< mri_out->height; y++) for (x=0; x < mri_out->width; x++) { if (MRIFvox(mri_out, x, y, z) > maxV ) maxV = MRIFvox(mri_out, x, y,z) ; if (MRIFvox(mri_out, x, y, z) < minV ) minV = MRIFvox(mri_out, x, y,z) ; } if (autoscale) { noscale = 1; /* compute histogram of output volume */ HISTOGRAM *h, *hsmooth ; float fmin, fmax, val, peak, smooth_peak; int i, nbins, bin; fmin = minV; fmax = maxV; if (fmin < 0) fmin = 0; nbins = 256 ; h = HISTOalloc(nbins) ; hsmooth = HISTOcopy(h, NULL) ; HISTOclear(h, h) ; h->bin_size = (fmax-fmin)/255.0 ; for (i = 0 ; i < nbins ; i++) h->bins[i] = (i+1)*h->bin_size ; for (z=0; z < mri_out->depth; z++) for (y=0; y< mri_out->height; y++) for (x=0; x < mri_out->width; x++) { val = MRIFvox(mri_out, x, y, z); if (val <= 0) continue; bin = nint((val - fmin)/h->bin_size); if (bin >= h->nbins) bin = h->nbins-1; else if (bin < 0) bin = 0; h->counts[bin] += 1.0; } HISTOfillHoles(h) ; HISTOsmooth(h, hsmooth, 5) ; peak = hsmooth->bins[HISTOfindHighestPeakInRegion(h, 1, h->nbins)] ; // smooth_peak = // hsmooth->bins[HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins)] ; smooth_peak = hsmooth->bins[HISTOfindLastPeak(hsmooth, 5, 0.8)] ; /* bin = nint((smooth_peak - fmin)/hsmooth->bin_size) ; printf("Highest peak has count = %d\n", (int)hsmooth->counts[bin]); bin = nint((420 - fmin)/hsmooth->bin_size) ; printf("bin at 420 has count = %d\n", (int)hsmooth->counts[bin]); */ scale = 110.0/smooth_peak; printf("peak of output volume is %g, smooth-peak is %g, multiply by %g to scale it to 110\n", peak, smooth_peak, scale); for (z=0; z < mri_out->depth; z++) for (y=0; y< mri_out->height; y++) for (x=0; x < mri_out->width; x++) { val = MRIFvox(mri_out, x, y, z); MRIFvox(mri_out, x, y, z) = val*scale; } } printf("Output volume (before type-conversion) has max = %g, min =%g\n", maxV, minV); /* Finally change type to desired */ if (mri_out->type != out_type) { printf("Change output volume to type %d\n", out_type); /* I need to modify the MIRchangeType function to make sure * it does roundoff instead of simple truncation! */ /* Note if the last flag is set to 1, then it won't do scaling and small float numbers will become zero after convert to BYTE */ if (out_type == 0 && noscale == 1) { //convert data to UCHAR mri_tmp = MRIalloc(mri_out->width, mri_out->height, mri_out->depth, out_type) ; MRIcopyHeader(mri_out, mri_tmp); for (z=0; z < mri_out->depth; z++) for (y=0; y< mri_out->height; y++) for (x=0; x < mri_out->width; x++) { value = floor(MRIgetVoxVal(mri_out, x, y, z, 0) + 0.5); if (value < 0 ) value = 0; if (value > 255) value = 255; MRIvox(mri_tmp,x,y,z) = (unsigned char)value; } } else mri_tmp = MRIchangeType(mri_out, out_type, thred_low, thred_high, noscale); MRIfree(&mri_out); mri_out = mri_tmp; //swap } MRIwrite(mri_out, out_vol) ; MRIfree(&mri_in); MRIfree(&mri_out); if (lta_src) MRIfree(<a_src); if (lta_dst) MRIfree(<a_dst); MatrixFree(&V_to_V); if (!r_to_i_out) MatrixFree(&r_to_i_out); if (!i_to_r_reg) MatrixFree(&i_to_r_reg); return(0) ; /* for ansi */ }
MRI * MRIsynthesizeWeightedVolume(MRI *mri_T1, MRI *mri_PD, float w5, float TR5, float w30, float TR30, float target_wm, float TE) { MRI *mri_dst ; int x, y, z, width, height, depth ; MRI *mri30, *mri5 ; Real val30, val5, val, min_val ; #if 0 int mri_peak, n, min_real_bin ; double mean_PD ; MRI_REGION box ; HISTOGRAM *h_mri, *h_smooth ; float x0, y0, z0, min_real_val ; #endif width = mri_T1->width ; height = mri_T1->height ; depth = mri_T1->depth ; mri_dst = MRIalloc(width, height, depth, MRI_FLOAT) ; MRIcopyHeader(mri_T1, mri_dst) ; mri30 = MRIsynthesize(mri_T1, mri_PD, NULL, NULL, TR30, RADIANS(30), TE) ; mri5 = MRIsynthesize(mri_T1, mri_PD, NULL, NULL, TR5, RADIANS(5), TE) ; #if 0 mean_PD = MRImeanFrame(mri_PD, 0) ; /* MRIscalarMul(mri_PD, mri_PD, 1000.0f/mean_PD) ;*/ h_mri = MRIhistogram(mri30, 100) ; h_smooth = HISTOsmooth(h_mri, NULL, 2) ; mri_peak = HISTOfindHighestPeakInRegion(h_smooth, 0, h_smooth->nbins) ; min_real_bin = HISTOfindNextValley(h_smooth, mri_peak) ; min_real_val = h_smooth->bins[min_real_bin] ; MRIfindApproximateSkullBoundingBox(mri30, min_real_val, &box) ; x0 = box.x+box.dx/3 ; y0 = box.y+box.dy/3 ; z0 = box.z+box.dz/2 ; printf("using (%.0f, %.0f, %.0f) as brain centroid...\n",x0, y0, z0) ; box.dx /= 4 ; box.x = x0 - box.dx/2; box.dy /= 4 ; box.y = y0 - box.dy/2; box.dz /= 4 ; box.z = z0 - box.dz/2; printf("using box (%d,%d,%d) --> (%d, %d,%d) " "to find MRI wm\n", box.x, box.y, box.z, box.x+box.dx-1,box.y+box.dy-1, box.z+box.dz-1) ; h_mri = MRIhistogramRegion(mri30, 0, NULL, &box) ; for (n = 0 ; n < h_mri->nbins-1 ; n++) if (h_mri->bins[n+1] > min_real_val) break ; HISTOclearBins(h_mri, h_mri, 0, n) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) HISTOplot(h_mri, "mri.histo") ; mri_peak = HISTOfindLastPeak(h_mri, HISTO_WINDOW_SIZE,MIN_HISTO_PCT); mri_peak = h_mri->bins[mri_peak] ; printf("before smoothing, mri peak at %d\n", mri_peak) ; h_smooth = HISTOsmooth(h_mri, NULL, 2) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) HISTOplot(h_smooth, "mri_smooth.histo") ; mri_peak = HISTOfindLastPeak(h_smooth, HISTO_WINDOW_SIZE,MIN_HISTO_PCT); mri_peak = h_mri->bins[mri_peak] ; printf("after smoothing, mri peak at %d\n", mri_peak) ; HISTOfree(&h_smooth) ; HISTOfree(&h_mri) ; #endif min_val = 0 ; for (x = 0 ; x < width ; x++) { for (y = 0 ; y < height ; y++) { for (z = 0 ; z < depth ; z++) { if (x == Gx && y == Gy && z == Gz) DiagBreak() ; MRIsampleVolumeType(mri30, x, y, z, &val30, SAMPLE_NEAREST) ; MRIsampleVolumeType(mri5, x, y, z, &val5, SAMPLE_NEAREST) ; val = w30*val30 + w5*val5 ; MRIFvox(mri_dst, x, y, z) = val ; if (val < min_val) min_val = val ; } } } for (x = 0 ; x < width ; x++) { for (y = 0 ; y < height ; y++) { for (z = 0 ; z < depth ; z++) { if (x == Gx && y == Gy && z == Gz) DiagBreak() ; MRIFvox(mri_dst, x, y, z) += min_val ; } } } MRIfree(&mri30) ; MRIfree(&mri5) ; return(mri_dst) ; }
MRI* MRIcomputeVolumeFractionFromSurface(MRI_SURFACE *mris, double acc, MRI *mri_src, MRI *mri_fractions) { const int width = mri_src->width; const int height = mri_src->height; const int depth = mri_src->depth; int x,y,z, vno; double xs, ys, zs, dist; MRIS_HASH_TABLE *mht; VERTEX *v; /* preparing the output */ printf("preparing the output\n"); if (mri_fractions == NULL) { mri_fractions = MRIalloc(width,height,depth,MRI_FLOAT); MRIcopyHeader(mri_src, mri_fractions); } MRI *mri_shell, *mri_interior; /* creating a shell from the surface */ printf("computing the shell\n"); mri_shell = MRIclone(mri_src, NULL); mri_shell = MRISshell(mri_src, mris, mri_shell, 1); /* creating an interior image from the surface */ printf("computing an interior image\n"); mri_interior = MRIclone(mri_src, NULL); MRIclear(mri_interior); mri_interior = MRISfillInterior(mris, 0.0, mri_interior); /* creating the hash table related to the surface vertices */ printf("computing the hash table\n"); mht = MHTfillVertexTableRes(mris, NULL, CURRENT_VERTICES, 10); /* looping over the nonzero elements of the shell */ printf("computing the fractions\n"); volFraction frac; octTreeVoxel V; double vox[3], vsize[3]; vsize[0] = mri_src->xsize; vsize[1] = mri_src->ysize; vsize[2] = mri_src->zsize; for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { for (z = 0; z < depth; z++) { if (MRIgetVoxVal (mri_shell, x, y, z, 0) > 125.0) { /* change of coordinates from image to surface domain */ MRIvoxelToSurfaceRAS(mri_shell, x, y, z, &xs, &ys, &zs); /* find the closest vertex to the point */ MHTfindClosestVertexGeneric(mht, mris, xs, ys, zs, 10, 2, &v, &vno, &dist); /* creating the oct tree voxel structure */ vox[0] = xs - vsize[0] / 2.0; vox[1] = ys - vsize[1] / 2.0; vox[2] = zs - vsize[2] / 2.0; V = octTreeVoxelCreate(vox,vsize); /* compute the volume fraction of this voxel */ frac = MRIcomputeVoxelFractions( V, v, acc, 1, mris); MRIsetVoxVal(mri_fractions,x,y,z,0,frac.frac); } else if(MRIgetVoxVal(mri_interior,x,y,z,0) > 0.0) MRIsetVoxVal(mri_fractions,x,y,z,0,1.0); } } } return mri_fractions; }
static MRI * MRIcomputeSurfaceDistanceProbabilities(MRI_SURFACE *mris, MRI *mri_ribbon, MRI *mri, MRI *mri_aseg) { MRI *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist, *mri_mask ; int nwhite_bins, npial_bins, x, y, z, label, i ; HISTOGRAM2D *hw, *hp ; float pdist, wdist, val ; double wval, pval ; mri_features = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_FLOAT, 2) ; MRIcopyHeader(mri, mri_features) ; mri_binary = MRIcopy(mri_ribbon, NULL) ; mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ; mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_pial_dist, "pd.mgz") ; MRIclear(mri_binary) ; MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ; MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ; MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ; mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_white_dist, "wd.mgz") ; nwhite_bins = ceil((max_white_dist - min_white_dist) / white_bin_size)+1 ; npial_bins = ceil((max_pial_dist - min_pial_dist) / pial_bin_size)+1 ; hw = HISTO2Dalloc(NBINS, nwhite_bins) ; hp = HISTO2Dalloc(NBINS, npial_bins) ; HISTO2Dinit(hw, NBINS, nwhite_bins, 0, NBINS-1, min_white_dist, max_white_dist) ; HISTO2Dinit(hp, NBINS, npial_bins, 0, NBINS-1, min_pial_dist, max_pial_dist) ; for (x = 0 ; x < mri->width ; x++) for (y = 0 ; y < mri->height ; y++) for (z = 0 ; z < mri->depth ; z++) { label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ; if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label)) continue ; pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; val = MRIgetVoxVal(mri, x, y, z, 0) ; if (pdist >= min_pial_dist && pdist <= max_pial_dist) HISTO2DaddSample(hp, val, pdist, 0, 0, 0, 0) ; if (wdist >= min_white_dist && wdist <= max_white_dist) HISTO2DaddSample(hw, val, wdist, 0, 0, 0, 0) ; } HISTO2DmakePDF(hp, hp) ; HISTO2DmakePDF(hw, hw) ; for (x = 0 ; x < mri->width ; x++) for (y = 0 ; y < mri->height ; y++) for (z = 0 ; z < mri->depth ; z++) { label = MRIgetVoxVal(mri_aseg, x, y, z, 0) ; if (IS_CEREBELLUM(label) || IS_VENTRICLE(label) || label == Brain_Stem || IS_CC(label)) continue ; pdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; wdist = MRIgetVoxVal(mri_pial_dist, x, y, z, 0) ; val = MRIgetVoxVal(mri, x, y, z, 0) ; wval = HISTO2DgetCount(hw, val, wdist); if (DZERO(wval) == 0) MRIsetVoxVal(mri_features, x, y, z, 1, -log10(wval)) ; pval = HISTO2DgetCount(hp, val, pdist); if (DZERO(pval) == 0) MRIsetVoxVal(mri_features, x, y, z, 0, -log10(pval)) ; } MRIclear(mri_binary) ; MRIbinarize(mri_ribbon, mri_binary, 1, 0, 1) ; mri_mask = MRIcopy(mri_binary, NULL) ; for (i = 0 ; i < close_order ; i++) { MRIdilate(mri_binary, mri_mask) ; MRIcopy(mri_mask, mri_binary) ; } for (i = 0 ; i < close_order ; i++) { MRIerode(mri_binary, mri_mask) ; MRIcopy(mri_mask, mri_binary) ; } MRIwrite(mri_mask, "m.mgz") ; MRImask(mri_features, mri_mask, mri_features, 0, 0) ; HISTO2Dfree(&hw) ; HISTO2Dfree(&hp) ; MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ; return(mri_features) ; }
int main(int argc, char *argv[]) { char **av; MRI *mri_T1, *mri_tmp, *mri_ctrl, *mri_in, *mri_out; MRI *mri_snr, *mri_bias; MRI *mri_mask1 = NULL; MRI *mri_mask2 = NULL; int ac, nargs; int width, height, depth, x, y, z; int mask1_set = 0; int mask2_set = 0; int i, j, k, cx, cy, cz, count; LTA *lta = 0; int transform_type; double mean, std, value, src, bias, norm; // HISTOGRAM *h; // float bin_size; // int nbins, bin_no; double mean1, std1, mean2, std2, count1, count2, slope, offset; VOL_GEOM vgtmp; LT *lt = NULL; MATRIX *m_tmp = NULL; Progname = argv[0]; nargs = handle_version_option (argc, argv, "$Id: mri_normalize_tp2.c,v 1.8 2011/03/02 00:04:23 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs ; 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(1); if (tp1_ctrl_fname == NULL || tp1_T1_fname == NULL) { printf("Use options to specify ctrl volume and T1 volume for tp1\n"); usage(1); } mri_in = MRIread(argv[1]) ; if (!mri_in) ErrorExit(ERROR_BADPARM, "%s: could not read input volume %s", Progname, argv[1]) ; mri_T1 = MRIread(tp1_T1_fname) ; if (!mri_T1) ErrorExit(ERROR_BADPARM, "%s: could not read T1 volume for tp1 %s", Progname, tp1_T1_fname) ; mri_ctrl = MRIread(tp1_ctrl_fname) ; if (!mri_ctrl) ErrorExit(ERROR_BADPARM, "%s: could not read control points volume for tp1 %s", Progname, tp1_ctrl_fname) ; if ((mri_in->width != mri_T1->width) || (mri_in->height != mri_T1->height) || (mri_in->depth != mri_T1->depth) || (mri_in->width != mri_ctrl->width) || (mri_in->height != mri_ctrl->height) || (mri_in->depth != mri_ctrl->depth) ) ErrorExit (ERROR_BADPARM, "%s: three input volumes have different sizes \n", Progname); if (mask1_fname) { mri_mask1 = MRIread(mask1_fname) ; if (!mri_mask1) ErrorExit(ERROR_BADPARM, "%s, could not read mask volume for tp1 %s", Progname, mask1_fname); mask1_set = 1; if ((mri_mask1->width != mri_in->width) || (mri_mask1->height != mri_in->height) || (mri_mask1->depth != mri_in->depth)) ErrorExit (ERROR_BADPARM, "%s: mask volumes have different sizes than other volumes \n", Progname); } if (mask2_fname) { mri_mask2 = MRIread(mask2_fname) ; if (!mri_mask2) ErrorExit (ERROR_BADPARM, "%s, could not read mask volume for tp2 %s", Progname, mask2_fname); mask2_set = 1; if ((mri_mask2->width != mri_T1->width) || (mri_mask2->height != mri_T1->height) || (mri_mask2->depth != mri_T1->depth) ) ErrorExit (ERROR_BADPARM, "%s: mask volumes have different sizes than other volumes \n", Progname); } width = mri_in->width ; height = mri_in->height ; depth = mri_in->depth ; //nbins = 200; //h = HISTOalloc(nbins); mri_out = MRIclone(mri_in, NULL) ; /* Read LTA transform and apply it to mri_ctrl */ if (xform_fname != NULL) { // read transform transform_type = TransformFileNameType(xform_fname); if (transform_type == MNI_TRANSFORM_TYPE || transform_type == TRANSFORM_ARRAY_TYPE || transform_type == REGISTER_DAT || transform_type == FSLREG_TYPE ) { printf("Reading transform ...\n"); lta = LTAreadEx(xform_fname) ; if (!lta) ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s", Progname, xform_fname) ; if (transform_type == FSLREG_TYPE) { if (lta_src == 0 || lta_dst == 0) { fprintf (stderr, "ERROR: fslmat does not have information " "on the src and dst volumes\n"); fprintf (stderr, "ERROR: you must give options '-lta_src' and " "'-lta_dst' to specify the src and dst volume infos\n"); } LTAmodifySrcDstGeom (lta, lta_src, lta_dst); // add src and dst information LTAchangeType(lta, LINEAR_VOX_TO_VOX); //this is necessary } if (lta->xforms[0].src.valid == 0) { if (lta_src == 0) { fprintf (stderr, "The transform does not have the valid src volume info.\n"); fprintf (stderr, "Either you give src volume info by option -lta_src or\n"); fprintf(stderr, "make the transform to have the valid src info.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information // getVolGeom(lta_src, <->src); } } if (lta->xforms[0].dst.valid == 0) { if (lta_dst == 0) { fprintf (stderr, "The transform does not have the valid dst volume info.\n"); fprintf (stderr, "Either you give src volume info by option -lta_dst or\n"); fprintf (stderr, "make the transform to have the valid dst info.\n"); fprintf (stderr, "If the dst was average_305, then you can set\n"); fprintf (stderr, "environmental variable USE_AVERAGE305 true\n"); fprintf (stderr, "without giving the dst volume for RAS-to-RAS transform.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add dst information } } } else { ErrorExit (ERROR_BADPARM, "transform is not of MNI, nor Register.dat, nor FSLMAT type"); } if (invert) { m_tmp = lta->xforms[0].m_L ; lta->xforms[0].m_L = MatrixInverse(lta->xforms[0].m_L, NULL) ; MatrixFree(&m_tmp) ; lt = <a->xforms[0]; if (lt->dst.valid == 0 || lt->src.valid == 0) { fprintf (stderr, "WARNING:***********************************************\n"); fprintf (stderr, "WARNING: dst volume infor is invalid. " "Most likely produce wrong inverse.\n"); fprintf (stderr, "WARNING:***********************************************\n"); } copyVolGeom(<->dst, &vgtmp); copyVolGeom(<->src, <->dst); copyVolGeom(&vgtmp, <->src); } // LTAchangeType(lta, LINEAR_VOX_TO_VOX); /* apply lta to the ctrl volume */ mri_tmp = MRIalloc(mri_ctrl->width, mri_ctrl->height, mri_ctrl->depth, mri_ctrl->type) ; MRIcopyHeader(mri_in, mri_tmp) ; // this function doesn't do NEAREST at all!! // I found the bug, in LTAtransformInterp() mri_tmp = LTAtransformInterp(mri_ctrl, mri_tmp, lta, SAMPLE_NEAREST); MRIfree(&mri_ctrl); mri_ctrl = mri_tmp; if (mask1_fname != NULL && mask2_fname == NULL) { printf("map mask for tp1 to get mask for tp2 ...\n"); mri_mask2 = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, mri_mask1->type) ; MRIcopyHeader(mri_in, mri_mask2) ; mri_mask2 = LTAtransformInterp(mri_mask1, mri_mask2, lta, SAMPLE_NEAREST); mask2_set = 1; if (debug_flag) MRIwrite(mri_mask2, "mri_mask2.mgz"); } else if (mask2_fname != NULL && mask1_fname == NULL) { printf("map mask for tp2 to get mask for tp1 ...\n"); //need to invert lta first m_tmp = lta->xforms[0].m_L ; lta->xforms[0].m_L = MatrixInverse(lta->xforms[0].m_L, NULL) ; MatrixFree(&m_tmp) ; lt = <a->xforms[0]; copyVolGeom(<->dst, &vgtmp); copyVolGeom(<->src, <->dst); copyVolGeom(&vgtmp, <->src); mri_mask1 = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, mri_mask2->type) ; MRIcopyHeader(mri_T1, mri_mask1) ; mri_mask1 = LTAtransformInterp(mri_mask2, mri_mask1, lta, SAMPLE_NEAREST); mask1_set = 1; if (debug_flag) MRIwrite(mri_mask1, "mri_mask1.mgz"); } if (lta_src) MRIfree(<a_src); if (lta_dst) MRIfree(<a_dst); if (lta) LTAfree(<a); } /* if (xform_fname != NULL) */ if (debug_flag) { // MRIwrite(mri_snr, "snr.mgz"); MRIwrite(mri_ctrl, "ctrl.mgz"); } if (mask1_set == 0) { //create mask1 mri_mask1 = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_UCHAR) ; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) { MRIvox(mri_mask1,x,y,z) = 0; } else MRIvox(mri_mask1,x,y,z) = 1; } } if (mask2_set == 0) { //create mask2 mri_mask2 = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_UCHAR) ; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) { MRIvox(mri_mask2,x,y,z) = 0; } else MRIvox(mri_mask2,x,y,z) = 1; } } #if 0 /* compute the mean and std of T1 volume */ /* Using only high SNR points */ mri_snr = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ; MRIcopyHeader(mri_T1, mri_snr) ; h->bin_size = bin_size = 0.5; for (bin_no = 0; bin_no < nbins; bin_no++) h->bins[bin_no] = (bin_no)*bin_size; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) { MRIFvox(mri_snr,x,y,z) = 0; continue; } mean = 0; std = 0; count = 0; for (i=-1; i<=1; i++) for (j=-1; j<=1; j++) for (k=-1;k<=1;k++) { cx = x+i; cy = y+j, cz = z+k; if (cx < 0 || cx >= width || cy < 0 || cy >= height || cz < 0 || cz >= depth) continue; count++; value = MRIgetVoxVal(mri_T1, cx, cy, cz, 0); mean += value; std += value*value; } mean /= (count + 1e-30); std /= (count + 1e-30); std = std - mean *mean; if (std <= 0) std = 0; value = mean/sqrt(std); MRIFvox(mri_snr,x,y,z) = value; bin_no = nint((float)value/(float)bin_size); if (bin_no >= nbins) bin_no = nbins - 1; h->counts[bin_no]++; } for (num = 0.0f, b = h->nbins - 1; b >= 1; b --) { num += h->counts[b]; if (num > 20000) /* this may make me only use WM points, is it good to use only WM to compute scale of intensity?? */ break; } printf("using SNR threshold %2.3f at bin %d\n", h->bins[b], b); mean1 = 0; std1 = 0; count1 = 0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_T1, x, y, z, 0) < noise_threshold) { continue; } value = MRIFvox(mri_snr,x,y,z); if (value < h->bins[b]) continue; value = MRIgetVoxVal(mri_T1, x, y, z, 0); count1++; mean1 += value; std1 += value*value; } MRIfree(&mri_snr); #else printf("compute mean and std of tp1 volume within masked area...\n"); mean1 = 0; std1 = 0; count1 = 0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_mask1, x, y, z, 0) <= 1e-30) { continue; } value = MRIgetVoxVal(mri_T1, x, y, z, 0); count1++; mean1 += value; std1 += value*value; } #endif mean1 /= (count1 + 1e-30); std1 /= (count1 + 1e-30); std1 = std1 - mean1*mean1; if (std1 <= 0) printf("warning: negative std for T1 volume. \n"); else printf("mean and variance for tp1 volume are %g and %g\n", mean1, std1); printf("now compute SNR and stats for input volume ... \n"); mri_snr = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ; MRIcopyHeader(mri_in, mri_snr) ; //HISTOclear(h,h); //h->bin_size = bin_size = 0.5; //for (bin_no = 0; bin_no < nbins; bin_no++) // h->bins[bin_no] = (bin_no)*bin_size; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) { MRIFvox(mri_snr,x,y,z) = 0; continue; } mean = 0; std = 0; count = 0; for (i=-1; i<=1; i++) for (j=-1; j<=1; j++) for (k=-1;k<=1;k++) { cx = x+i; cy = y+j, cz = z+k; if (cx < 0 || cx >= width || cy < 0 || cy >= height || cz < 0 || cz >= depth) continue; count++; value = MRIgetVoxVal(mri_in, cx, cy, cz, 0); mean += value; std += value*value; } mean /= (count + 1e-30); std /= (count + 1e-30); std = std - mean *mean; if (std <= 0) std = 0; value = mean/sqrt(std); MRIFvox(mri_snr,x,y,z) = value; //bin_no = nint((float)value/(float)bin_size); //if (bin_no >= nbins) bin_no = nbins - 1; //h->counts[bin_no]++; } #if 0 for (num = 0.0f, b = h->nbins - 1; b >= 1; b --) { num += h->counts[b]; if (num > 20000) /* this may make me only use WM points, is it good to use only WM to compute scale of intensity?? */ break; } printf("using SNR threshold %2.3f at bin %d\n", h->bins[b], b); mean2 = 0; std2 = 0; count2 = 0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) { continue; } value = MRIFvox(mri_snr,x,y,z); if (value >= h->bins[b]) { count2++; mean2 += value; std2 += value*value; } } #else printf("compute mean and std of tp2 volume within masked area\n"); /* somehow mri_watershed seems to leave some unzero voxels around image border, so I will skip image boundaries no, that's not a problem of most recent mri_watershed; something wrong previously */ mean2 = 0; std2 = 0; count2 = 0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_mask2, x, y, z, 0) <= 1e-30) { continue; } value = MRIgetVoxVal(mri_in, x, y, z, 0); count2++; mean2 += value; std2 += value*value; } #endif mean2 /= (count2 + 1e-30); std2 /= (count2 + 1e-30); std2 = std2 - mean2*mean2; if (std2 <= 0) printf("warning: negative std for input volume. \n"); else printf("mean and variance for input tp2 volume are %g and %g\n", mean2, std2); //compute intensity scale slope = sqrt(std1/std2); offset = mean1 - slope*mean2; printf("scale input volume by %g x + %g\n", slope, offset); // first change mri_in to FLOAT type mri_tmp = MRIchangeType(mri_in, MRI_FLOAT, 0, 1.0, 1); MRIfree(&mri_in); mri_in = mri_tmp; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { value = MRIFvox(mri_in, x, y, z); MRIFvox(mri_in, x, y, z) = value*slope + offset; } // printf("compute SNR map of tp2 volume\n"); //already done above // mri_snr = MRIalloc(mri_ctrl->width, // mri_ctrl->height, mri_ctrl->depth, MRI_FLOAT) ; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIgetVoxVal(mri_in, x, y, z, 0) < noise_threshold) { // MRIFvox(mri_snr,x,y,z) = 0; continue; } value = MRIFvox(mri_snr,x,y,z); if (value < 20) MRIvox(mri_ctrl, x, y, z) = 0; else if (MRIvox(mri_ctrl, x, y, z) > 0) { MRIvox(mri_ctrl, x, y, z) = 1; } } if (debug_flag) { MRIwrite(mri_snr, "snr.mgz"); // MRIwrite(mri_ctrl, "ctrl.mgz"); } // SNR >= 20 seems a good threshold // Now use ctrl points to normalize tp2 printf("normalize tp2...\n"); mri_bias = MRIbuildBiasImage(mri_in, mri_ctrl, NULL, bias_sigma) ; for (z = 0 ; z < depth ; z++) { for (y = 0 ; y < height ; y++) { for (x = 0 ; x < width ; x++) { src = MRIgetVoxVal(mri_in, x, y, z, 0) ; bias = MRIgetVoxVal(mri_bias, x, y, z, 0) ; if (!bias) /* should never happen */ norm = (float)src ; else norm = (float)src * 110.0 / (float)bias ; if (norm > 255.0f && mri_out->type == MRI_UCHAR) norm = 255.0f ; else if (norm < 0.0f && mri_out->type == MRI_UCHAR) norm = 0.0f ; MRIsetVoxVal(mri_out, x, y, z, 0, norm) ; } } } printf("writing normalized volume to %s...\n", argv[2]) ; MRIwrite(mri_out, argv[2]); MRIfree(&mri_in); MRIfree(&mri_bias); MRIfree(&mri_out); MRIfree(&mri_T1); MRIfree(&mri_ctrl); MRIfree(&mri_snr); //HISTOfree(&h); exit(0); } /* end main() */
static int write_surface_warp_into_volume(MRI_SURFACE *mris, MRI *mri, int niter) { int vno, xvi, yvi, zvi, frame ; VERTEX *v ; double dx, dy, dz, xv, yv, zv, xv1, yv1, zv1 ; MRI *mri_weights, *mri_ctrl, *mri_frame ; float wt ; mri_weights = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_FLOAT, 1) ; mri_ctrl = MRIallocSequence(mri->width, mri->height, mri->depth, MRI_UCHAR, 1) ; MRIcopyHeader(mri, mri_weights) ; MRIcopyHeader(mri, mri_ctrl) ; // build a 3 frame volume with the voxel-coords warp (dx, dy, dz) in frames 0, 1 and 2 respectively for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (v->ripflag) continue ; MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xv, &yv, &zv) ; MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv1, &yv1, &zv1) ; dx = xv1-xv ; dy = yv1-yv ; dz = zv1-zv ; xvi = nint(xv) ; yvi = nint(yv) ; zvi = nint(zv) ; if (vno == Gdiag_no) { printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f), " "dx=(%2.0f, %2.0f, %2.0f)\n", vno, xv1, yv1, zv1, xv, yv, zv, dx, dy, dz) ; DiagBreak() ; } if (xvi < 0 || xvi >= mri->width || yv < 0 || yv >= mri->height || zv < 0 || zv >= mri->depth) { continue ; } MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 0, dx) ; MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 1, dy) ; MRIinterpolateIntoVolumeFrame(mri, xv, yv, zv, 2, dz) ; MRIinterpolateIntoVolume(mri_weights, xv, yv, zv, 1.0) ; } #if 0 // set boundary conditions in the edge planes to be 0 warping for (xvi = 0 ; xvi < mri->width ; xvi++) for (yvi = 0 ; yvi < mri->height ; yvi++) { MRIsetVoxVal(mri_ctrl, xvi, yvi, 0, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, xvi, yvi, 0, 0, 0) ; MRIsetVoxVal(mri, xvi, yvi, 0, 1, 0) ; MRIsetVoxVal(mri, xvi, yvi, 0, 2, 0) ; MRIsetVoxVal(mri_ctrl, xvi, yvi, mri->depth-1, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 0, 0) ; MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 1, 0) ; MRIsetVoxVal(mri, xvi, yvi, mri->depth-1, 2, 0) ; } for (xvi = 0 ; xvi < mri->width ; xvi++) for (zvi = 0 ; zvi < mri->depth ; zvi++) { MRIsetVoxVal(mri_ctrl, xvi, 0, zvi, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, xvi, 0, zvi, 0, 0) ; MRIsetVoxVal(mri, xvi, 0, zvi, 1, 0) ; MRIsetVoxVal(mri, xvi, 0, zvi, 2, 0) ; MRIsetVoxVal(mri_ctrl, xvi, mri->height-1, zvi, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 0, 0) ; MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 1, 0) ; MRIsetVoxVal(mri, xvi, mri->height-1, zvi, 2, 0) ; } for (yvi = 0 ; yvi < mri->width ; yvi++) for (zvi = 0 ; zvi < mri->depth ; zvi++) { MRIsetVoxVal(mri_ctrl, 0, yvi, zvi, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, 0, yvi, zvi, 0, 0) ; MRIsetVoxVal(mri, 0, yvi, zvi, 1, 0) ; MRIsetVoxVal(mri, 0, yvi, zvi, 2, 0) ; MRIsetVoxVal(mri_ctrl, mri->width-1, yvi, zvi, 0, CONTROL_MARKED) ; MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 0, 0) ; MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 1, 0) ; MRIsetVoxVal(mri, mri->width-1, yvi, zvi, 2, 0) ; } #endif // normalize the warp field using a weighted average of all vertices that map to every voxel for (xvi = 0 ; xvi < mri->width ; xvi++) for (yvi = 0 ; yvi < mri->height ; yvi++) for (zvi = 0 ; zvi < mri->depth ; zvi++) { if (xvi == Gx && yvi == Gy && zvi == Gz) DiagBreak() ; wt = MRIgetVoxVal(mri_weights, xvi, yvi, zvi, 0) ; dx = MRIgetVoxVal(mri, xvi, yvi, zvi, 0) ; dy = MRIgetVoxVal(mri, xvi, yvi, zvi, 1) ; dz = MRIgetVoxVal(mri, xvi, yvi, zvi, 2) ; if (FZERO(wt)) continue ; dx /= wt ; dy /= wt ; dz /= wt ; MRIsetVoxVal(mri, xvi, yvi, zvi, 0, dx) ; MRIsetVoxVal(mri, xvi, yvi, zvi, 1, dy) ; MRIsetVoxVal(mri, xvi, yvi, zvi, 2, dz) ; MRIsetVoxVal(mri_ctrl, xvi, yvi, zvi, 0, CONTROL_MARKED) ; // it is a control point } if (Gdiag & DIAG_WRITE) { MRIwrite(mri, "warp0.mgz") ; MRIwrite(mri_ctrl, "ctrl.mgz") ; } for (frame = 0 ; frame < mri->nframes ; frame++) { printf("interpolating frame %d\n", frame+1) ; mri_frame = MRIcopyFrame(mri, NULL, frame, 0) ; MRIbuildVoronoiDiagram(mri_frame, mri_ctrl, mri_frame) ; MRIsoapBubble(mri_frame, mri_ctrl, mri_frame, niter, mri_frame->xsize*.05) ; #if 0 { int x, y, z ; float val ; for (x = 0 ; x < mri_frame->width ; x++) for (y = 0 ; y < mri_frame->height ; y++) for (z = 0 ; z < mri_frame->depth ; z++) { val = MRIgetVoxVal(mri_frame, x, y, z, 0) ; switch (frame) { default: case 0: val += x ; break ; case 1: val += y ; break ; case 2: val += z ; break ; } MRIsetVoxVal(mri_frame, x, y, z, 0, val) ; } } #endif MRIcopyFrame(mri_frame, mri, 0, frame) ; MRIfree(&mri_frame) ; } MRIfree(&mri_weights) ; MRIfree(&mri_ctrl) ; return(NO_ERROR) ; }
int main(int argc, char *argv[]) { char **av, *in_fname; int ac, nargs, i, j, x, y, z, width, height, depth; MRI *mri_flash[MAX_IMAGES], *mri_label, *mri_mask; int index; int msec, minutes, seconds, nvolumes, nvolumes_total ; struct timeb start ; float max_val, min_val, value; float *LDAweight = NULL; float **LDAmeans = NULL; /* Centroid for each considered class */ float *classSize =NULL; /* relative size of each class */ MATRIX **SWs; /* Within class scatter-matrix for each considered class */ MATRIX *AdjMatrix; /* Adjacency matrix of all classes */ FILE *fp; int num_classes; double cnr; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_ms_compute_CNR.c,v 1.10 2011/03/02 00:04:55 nicks Exp $", "$Name: $"); 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 < 2) usage_exit(1) ; printf("command line parsing finished\n"); if (label_fname == NULL) { printf("Use -label option to specify file for segmentation \n"); usage_exit(0); } if (have_weight == 1 && weight_fname == NULL) { printf("Use -weight option to specify file for input LDA weights \n") ; usage_exit(0); } if (have_weight == 1 && synth_fname == NULL) { printf("Use -synth option to specify file for output synthesized volume \n") ; usage_exit(0); } if (ldaflag) { MINLABEL = MIN(class1, class2); MAXLABEL = MAX(class1, class2); } num_classes = MAXLABEL - MINLABEL + 1; printf("Total of %d classes considered in LDA training\n", num_classes); if (num_classes <= 1) { printf("Need to specify at least two classes to evaluate CNR\n"); usage_exit(0); } ////////////////////////////////////////////////////////////////////////////////// /*** Read in the input multi-echo volumes ***/ nvolumes = 0 ; for (i = 1 ; i < argc; i++) { in_fname = argv[i] ; printf("reading %s...\n", in_fname) ; mri_flash[nvolumes] = MRIread(in_fname) ; if (mri_flash[nvolumes] == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read volume %s", Progname, in_fname) ; /* conform will convert all data to UCHAR, which will reduce data resolution*/ printf("%s read in. \n", in_fname) ; if (conform) { MRI *mri_tmp ; printf("embedding and interpolating volume\n") ; mri_tmp = MRIconform(mri_flash[nvolumes]) ; mri_flash[nvolumes] = mri_tmp ; } /* Change all volumes to float type for convenience */ if (mri_flash[nvolumes]->type != MRI_FLOAT) { printf("Volume %d type is %d\n", nvolumes+1, mri_flash[nvolumes]->type); MRI *mri_tmp; printf("Change data to float type \n"); mri_tmp = MRIchangeType(mri_flash[nvolumes], MRI_FLOAT, 0, 1.0, 1); MRIfree(&mri_flash[nvolumes]); mri_flash[nvolumes] = mri_tmp; //swap } nvolumes++ ; } printf("All data read in\n"); /////////////////////////////////////////////////////////////////////////// nvolumes_total = nvolumes ; /* all volumes read in */ for (i = 0 ; i < nvolumes ; i++) { for (j = i+1 ; j < nvolumes ; j++) { if ((mri_flash[i]->width != mri_flash[j]->width) || (mri_flash[i]->height != mri_flash[j]->height) || (mri_flash[i]->depth != mri_flash[j]->depth)) ErrorExit(ERROR_BADPARM, "%s:\nvolumes %d (type %d) and %d (type %d) don't match (%d x %d x %d) vs (%d x %d x %d)\n", Progname, i, mri_flash[i]->type, j, mri_flash[j]->type, mri_flash[i]->width, mri_flash[i]->height, mri_flash[i]->depth, mri_flash[j]->width, mri_flash[j]->height, mri_flash[j]->depth) ; } } width = mri_flash[0]->width; height = mri_flash[0]->height; depth = mri_flash[0]->depth; if (label_fname != NULL) { mri_label = MRIread(label_fname); if (!mri_label) ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n", Progname, label_fname); if ((mri_label->width != mri_flash[0]->width) || (mri_label->height != mri_flash[0]->height) || (mri_label->depth != mri_flash[0]->depth)) ErrorExit(ERROR_BADPARM, "%s: label volume size doesn't match data volumes\n", Progname); /* if(mri_label->type != MRI_UCHAR) ErrorExit(ERROR_BADPARM, "%s: label volume is not UCHAR type \n", Progname); */ } if (mask_fname != NULL) { mri_mask = MRIread(mask_fname); if (!mri_mask) ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s\n", Progname, mask_fname); if ((mri_mask->width != mri_flash[0]->width) || (mri_mask->height != mri_flash[0]->height) || (mri_mask->depth != mri_flash[0]->depth)) ErrorExit(ERROR_BADPARM, "%s: mask volume size doesn't macth data volumes\n", Progname); if (mri_mask->type != MRI_UCHAR) ErrorExit(ERROR_BADPARM, "%s: mask volume is not UCHAR type \n", Progname); } else { mri_mask = MRIalloc(mri_flash[0]->width, mri_flash[0]->height, mri_flash[0]->depth, MRI_UCHAR); MRIcopyHeader(mri_flash[0], mri_mask); /* Simply set mask to be 1 everywhere */ for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { MRIvox(mri_mask, x, y,z) = 1; } } if (debug_flag && window_flag) { /* Limit LDA to a local window */ printf("Local window size = %d\n", window_size); window_size /= 2; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (MRIvox(mri_mask, x, y,z) == 0) continue; if (z < (Gz - window_size) || z >(Gz + window_size) || y <(Gy - window_size) || y > (Gy + window_size) || x < (Gx - window_size) || x > (Gx + window_size)) MRIvox(mri_mask, x, y,z) = 0; } } LDAweight = (float *)calloc(nvolumes_total, sizeof(float)); /* Allocate memory */ LDAmeans = (float **)malloc(num_classes*sizeof(float *)); SWs = (MATRIX **)malloc(num_classes*sizeof(MATRIX *)); classSize = (float *)malloc(num_classes*sizeof(float)); for (i=0; i< num_classes; i++) { LDAmeans[i] = (float *)malloc(nvolumes_total*sizeof(float)); SWs[i] = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL); if (SWs[i] == NULL || LDAmeans[i] == NULL) ErrorExit(ERROR_BADPARM, "%s: unable to allocate required memory \n", Progname); } if (ldaflag) { AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL); /* The diagnoal entries of AdjMatrix is set to zero initially */ for (i=1; i <= num_classes;i++) for (j=i; j <= num_classes; j++) { AdjMatrix->rptr[i][j] = 0.0; AdjMatrix->rptr[j][i] = 0.0; } AdjMatrix->rptr[class1-MINLABEL +1][class2-MINLABEL+1] = 1.0; AdjMatrix->rptr[class1-MINLABEL +1][class1-MINLABEL+1] = 1.0; AdjMatrix->rptr[class2-MINLABEL +1][class2-MINLABEL+1] = 1.0; AdjMatrix->rptr[class2-MINLABEL +1][class1-MINLABEL+1] = 1.0; } else if (MINLABEL <=2 && MAXLABEL >= 76) { printf("Manually set adjacent matrix \n"); AdjMatrix = (MATRIX *)MatrixAlloc(num_classes, num_classes, MATRIX_REAL); /* The diagnoal entries of AdjMatrix is set to zero initially */ for (i=1; i <= num_classes;i++) for (j=i; j <= num_classes; j++) { AdjMatrix->rptr[i][j] = 0.0; AdjMatrix->rptr[j][i] = 0.0; } for (index = 0; index < CNR_pairs; index++) { i = ilist[index] - MINLABEL; j = jlist[index] - MINLABEL; AdjMatrix->rptr[i+1][j+1] = 1.0; AdjMatrix->rptr[j+1][i+1] = 1.0; } /* left-hemisphere */ /* AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0; AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[5+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[4+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[18+1-MINLABEL][2+1-MINLABEL] = 1.0; AdjMatrix->rptr[18+1-MINLABEL][3+1-MINLABEL] = 1.0; AdjMatrix->rptr[18+1-MINLABEL][5+1-MINLABEL] = 1.0; AdjMatrix->rptr[18+1-MINLABEL][4+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][4+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][12+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][2+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0; */ /* right-hemisphere */ /* AdjMatrix->rptr[53+1-MINLABEL][41+1-MINLABEL] = 1.0; AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0; AdjMatrix->rptr[53+1-MINLABEL][42+1-MINLABEL] = 1.0; AdjMatrix->rptr[53+1-MINLABEL][44+1-MINLABEL] = 1.0; AdjMatrix->rptr[53+1-MINLABEL][43+1-MINLABEL] = 1.0; AdjMatrix->rptr[54+1-MINLABEL][41+1-MINLABEL] = 1.0; AdjMatrix->rptr[54+1-MINLABEL][42+1-MINLABEL] = 1.0; AdjMatrix->rptr[54+1-MINLABEL][44+1-MINLABEL] = 1.0; AdjMatrix->rptr[54+1-MINLABEL][43+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][43+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][51+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][41+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0; for(i=1; i < num_classes;i++) for(j=i+1; j <= num_classes; j++){ if(AdjMatrix->rptr[i][j] > 0.5) AdjMatrix->rptr[j][i] = AdjMatrix->rptr[i][j]; else AdjMatrix->rptr[i][j] = AdjMatrix->rptr[j][i]; } */ /* AdjMatrix->rptr[2+1-MINLABEL][3+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][10+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][11+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][12+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][13+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[2+1-MINLABEL][18+1-MINLABEL] = 1.0; AdjMatrix->rptr[3+1-MINLABEL][12+1-MINLABEL] = 1.0; AdjMatrix->rptr[3+1-MINLABEL][17+1-MINLABEL] = 1.0; AdjMatrix->rptr[3+1-MINLABEL][18+1-MINLABEL] = 1.0; AdjMatrix->rptr[4+1-MINLABEL][10+1-MINLABEL] = 1.0; AdjMatrix->rptr[4+1-MINLABEL][11+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][11+1-MINLABEL] = 1.0; AdjMatrix->rptr[10+1-MINLABEL][13+1-MINLABEL] = 1.0; AdjMatrix->rptr[12+1-MINLABEL][13+1-MINLABEL] = 1.0; AdjMatrix->rptr[12+1-MINLABEL][26+1-MINLABEL] = 1.0; AdjMatrix->rptr[17+1-MINLABEL][18+1-MINLABEL] = 1.0; */ /* right-hemisphere */ /* AdjMatrix->rptr[41+1-MINLABEL][42+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][49+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][50+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][51+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][52+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][53+1-MINLABEL] = 1.0; AdjMatrix->rptr[41+1-MINLABEL][54+1-MINLABEL] = 1.0; AdjMatrix->rptr[42+1-MINLABEL][51+1-MINLABEL] = 1.0; AdjMatrix->rptr[42+1-MINLABEL][53+1-MINLABEL] = 1.0; AdjMatrix->rptr[42+1-MINLABEL][54+1-MINLABEL] = 1.0; AdjMatrix->rptr[43+1-MINLABEL][49+1-MINLABEL] = 1.0; AdjMatrix->rptr[43+1-MINLABEL][50+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][50+1-MINLABEL] = 1.0; AdjMatrix->rptr[49+1-MINLABEL][52+1-MINLABEL] = 1.0; AdjMatrix->rptr[51+1-MINLABEL][52+1-MINLABEL] = 1.0; AdjMatrix->rptr[51+1-MINLABEL][58+1-MINLABEL] = 1.0; AdjMatrix->rptr[53+1-MINLABEL][54+1-MINLABEL] = 1.0; */ } else AdjMatrix = ComputeAdjMatrix(mri_label, mri_mask, MINLABEL, MAXLABEL); /* AdjMatrix may need manual adjusted to avoid meaningless comparisons * such as computing CNR between left WM and right WM */ for (i=1; i <= num_classes;i++) for (j=1; j <= num_classes; j++) { if (j==i) continue; /* the diagonal term will indicate whether the class is useful or not */ AdjMatrix->rptr[i][i] += AdjMatrix->rptr[i][j] + AdjMatrix->rptr[j][i]; } printf("Compute individual class statistics\n"); /* Compute class means and covariance matrix */ /* Note that here SWs will be covaraince matrix, not scatter matrix */ for (i=0; i < num_classes; i++) { if (AdjMatrix->rptr[i+1][i+1] < 0.5) continue; computeClassStats(LDAmeans[i], SWs[i], &classSize[i], mri_flash, mri_label, mri_mask, nvolumes_total, MINLABEL + i); } printf("class statistics computed \n"); if (fname != NULL) fp = fopen(fname, "w"); else fp = 0; printf("compute pair-wise CNR/Mahalanobis distances \n"); if (ldaflag) { for (i=0; i <num_classes-1;i++) for (j=i+1; j < num_classes; j++) { if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue; cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i], classSize[j], nvolumes_total, LDAweight, 1); if (fp) fprintf(fp, "%9.4f ", (float)cnr); printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr); } if (fp) { fprintf(fp, "\n"); fclose(fp); } } else { for (index = 0; index < CNR_pairs; index++) { i = ilist[index] - MINLABEL; j = jlist[index] - MINLABEL; if (AdjMatrix->rptr[i+1][j+1] < 0.5) continue; if (i== (2-MINLABEL) && j == (3-MINLABEL) && nvolumes_total > 1) cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i], classSize[j], nvolumes_total, LDAweight, 1); else cnr = computePairCNR(LDAmeans[i], LDAmeans[j], SWs[i], SWs[j], classSize[i], classSize[j], nvolumes_total, 0, 0); if (fp) fprintf(fp, "%9.4f ", (float)cnr); printf("CNR of class %d and class %d is %g\n", i+MINLABEL, j+MINLABEL, cnr); } if (fp) { fprintf(fp, "\n"); fclose(fp); } } /* output weights for optimize CNR for class 2 and class 3 */ if (weight_fname != NULL) { output_weights_to_file(LDAweight, weight_fname, nvolumes_total); } free(classSize); for (i=0; i< num_classes; i++) { free(LDAmeans[i]); MatrixFree(&SWs[i]); } free(LDAmeans); free(SWs); MatrixFree(&AdjMatrix); if (nvolumes_total > 1 && ((MINLABEL <=2 && MAXLABEL >= 3) || ldaflag)) { if (ldaflag) { printf("LDA weights for %d-%d are: \n", class1, class2); } else { printf("LDA weights for 2-3 are: \n"); } for (i=0; i < nvolumes_total; i++) { printf("%g ", LDAweight[i]); } printf("\n"); if (synth_fname != NULL) { /* linear projection of input volumes to a 1D volume */ min_val = 10000.0; max_val = -10000.0; for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue; value = 0.0; for (i=0; i < nvolumes_total; i++) { value += MRIFvox(mri_flash[i], x, y, z)*LDAweight[i]; } if (max_val < value) max_val = value; if (min_val > value) min_val = value; /* Borrow mri_flash[0] to store the float values first */ MRIFvox(mri_flash[0], x, y, z) = value; } printf("max_val = %g, min_val = %g \n", max_val, min_val); /* Scale output to [0, 255] */ for (z=0; z < depth; z++) for (y=0; y< height; y++) for (x=0; x < width; x++) { if (whole_volume == 0 && MRIvox(mri_mask, x, y, z) == 0) continue; value = (MRIFvox(mri_flash[0], x, y, z) - min_val)*255.0/(max_val - min_val) + 0.5; /* +0.5 for round-off */ if (value > 255.0) value = 255.0; if (value < 0) value = 0; /* Borrow mri_flash[0] to store the float values first */ MRIvox(mri_mask, x, y, z) = (BUFTYPE) value; } /* Output synthesized volume */ MRIwrite(mri_mask, synth_fname); } } free(LDAweight); msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("LDA took %d minutes and %d seconds.\n", minutes, seconds) ; MRIfree(&mri_mask); MRIfree(&mri_label); for (i=0; i < nvolumes_total; i++) { MRIfree(&mri_flash[i]); } exit(0); }
int main(int argc, char *argv[]) { char *gca_fname, *in_fname, **av, *xform_fname ; MRI *mri_in, *mri_tmp, *mri_orig = NULL ; GCA *gca ; int ac, nargs, input, ninputs ; TRANSFORM *transform = NULL ; char cmdline[CMD_LINE_LEN] ; double ll ; make_cmd_version_string (argc, argv, "$Id: mri_log_likelihood.c,v 1.4 2011/03/02 00:04:22 nicks Exp $", "$Name: stable5 $", cmdline); /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_log_likelihood.c,v 1.4 2011/03/02 00:04:22 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 < 3) ErrorExit (ERROR_BADPARM, "usage: %s [<options>] <inbrain1> <inbrain2> ... " "<atlas> <transform file> ...\n", Progname) ; ninputs = (argc - 1) / 2 ; if (DIAG_VERBOSE_ON) printf("reading %d input volume%ss\n", ninputs, ninputs > 1 ? "s" : "") ; in_fname = argv[1] ; gca_fname = argv[1+ninputs] ; xform_fname = argv[2+ninputs] ; transform = TransformRead(xform_fname) ; if (!transform) ErrorExit(ERROR_NOFILE, "%s: could not read input transform from %s", Progname, xform_fname) ; if (DIAG_VERBOSE_ON) printf("reading atlas from '%s'...\n", gca_fname) ; gca = GCAread(gca_fname) ; if (!gca) ErrorExit(ERROR_NOFILE, "%s: could not read input atlas from %s", Progname, gca_fname) ; fflush(stdout) ; for (input = 0 ; input < ninputs ; input++) { in_fname = argv[1+input] ; if (DIAG_VERBOSE_ON) printf("reading input volume from %s...\n", in_fname) ; mri_tmp = MRIread(in_fname) ; if (!mri_tmp) ErrorExit(ERROR_NOFILE, "%s: could not read input MR volume from %s", Progname, in_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) ; } MRIcopyFrame(mri_tmp, mri_in, 0, input) ; MRIfree(&mri_tmp) ; } MRIaddCommandLine(mri_in, cmdline) ; TransformInvert(transform, mri_in) ; if (orig_fname) { mri_orig = MRIread(orig_fname) ; if (mri_orig == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read orig volume from %s", Progname, orig_fname) ; } ll = GCAimageLogLikelihood(gca, mri_in, transform, 1, mri_orig) ; printf("%2.0f\n", 10000*ll) ; MRIfree(&mri_in) ; if (gca) GCAfree(&gca) ; if (mri_in) MRIfree(&mri_in) ; exit(0) ; return(0) ; }
int main(int argc, char *argv[]) { char **av, fname[STRLEN] ; int ac, nargs ; char *reg_fname, *in_fname, *out_stem, *cp ; int msec, minutes, seconds, nvox, float2int ; struct timeb start ; MRI_SURFACE *mris_lh_white, *mris_rh_white, *mris_lh_pial, *mris_rh_pial ; MRI *mri_aseg, *mri_seg, *mri_pial, *mri_tmp, *mri_ribbon, *mri_in, *mri_cortex, *mri_subcort_gm, *mri_wm, *mri_csf ; MATRIX *m_regdat ; float intensity, betplaneres, inplaneres ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_compute_volume_fractions.c,v 1.9 2012/11/07 18:58:02 greve Exp $", "$Name: $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; Progname = argv[0] ; 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(1) ; if (!strlen(sdir)) { cp = getenv("SUBJECTS_DIR") ; if (!cp) ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ; strcpy(sdir, cp) ; } reg_fname = argv[1] ; in_fname = argv[2] ; out_stem = argv[3] ; Progname = argv[0] ; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; TimerStart(&start) ; if (stricmp(reg_fname, "identity.nofile") == 0) { printf("using identity transform\n") ; m_regdat = NULL ; inplaneres = betplaneres = intensity = 1 ; float2int = 0 ; if (subject == NULL) subject = "unknown" ; } else { char *saved_subject = subject ; printf("reading registration file %s\n", reg_fname) ; regio_read_register(reg_fname, &subject, &inplaneres, &betplaneres, &intensity, &m_regdat, &float2int); if (saved_subject) // specified on cmdline subject = saved_subject ; m_regdat = regio_read_registermat(reg_fname) ; if (m_regdat == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load registration file from %s", Progname,reg_fname) ; } printf("Format is %s\n",fmt); sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ; printf("reading surface %s\n", fname) ; mris_lh_white = MRISread(fname) ; if (mris_lh_white == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load lh white surface from %s", Progname,fname) ; sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ; printf("reading surface %s\n", fname) ; mris_rh_white = MRISread(fname) ; if (mris_rh_white == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load rh white surface from %s", Progname,fname) ; sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ; printf("reading surface %s\n", fname) ; mris_lh_pial = MRISread(fname) ; if (mris_lh_pial == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load lh pial surface from %s", Progname,fname) ; sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ; printf("reading surface %s\n", fname) ; mris_rh_pial = MRISread(fname) ; if (mris_rh_pial == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load rh pial surface from %s", Progname,fname) ; sprintf(fname, "%s/%s/mri/aseg.mgz", sdir, subject) ; printf("reading volume %s\n", fname) ; mri_aseg = MRIread(fname) ; if (mri_aseg == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load aseg volume from %s", Progname,fname) ; printf("reading movable volume %s\n", in_fname) ; mri_in = MRIread(in_fname) ; if (mri_in == NULL) ErrorExit(ERROR_NOFILE, "%s: could not load input volume from %s", Progname,in_fname) ; nvox = (int)ceil(256/resolution); mri_pial = MRIalloc(nvox, nvox, nvox, MRI_UCHAR) ; MRIsetResolution(mri_pial, resolution, resolution, resolution) ; mri_pial->xstart = -resolution*mri_pial->width/2.0 ; mri_pial->xend = resolution*mri_pial->width/2.0 ; mri_pial->ystart = -resolution*mri_pial->height/2.0 ; mri_pial->yend = resolution*mri_pial->height/2.0 ; mri_pial->zstart = -resolution*mri_pial->depth/2.0 ; mri_pial->zend = resolution*mri_pial->depth/2 ; mri_pial->c_r = mri_aseg->c_r ; mri_pial->c_a = mri_aseg->c_a ; mri_pial->c_s = mri_aseg->c_s ; MRIreInitCache(mri_pial) ; printf("filling interior of lh pial surface...\n") ; MRISfillInterior(mris_lh_pial, resolution, mri_pial) ; mri_seg = MRIclone(mri_pial, NULL) ; mri_tmp = MRIclone(mri_pial, NULL) ; printf("filling interior of rh pial surface...\n") ; MRISfillInterior(mris_rh_pial, resolution, mri_tmp) ; MRIcopyLabel(mri_tmp, mri_pial, 1) ; MRIclear(mri_tmp) ; printf("filling interior of lh white matter surface...\n") ; MRISfillWhiteMatterInterior(mris_lh_white, mri_aseg, mri_seg, resolution, WM_VAL, SUBCORT_GM_VAL, CSF_VAL); printf("filling interior of rh white matter surface...\n") ; MRISfillWhiteMatterInterior(mris_rh_white, mri_aseg, mri_tmp, resolution, WM_VAL, SUBCORT_GM_VAL, CSF_VAL); MRIcopyLabel(mri_tmp, mri_seg, WM_VAL) ; MRIcopyLabel(mri_tmp, mri_seg, SUBCORT_GM_VAL) ; MRIcopyLabel(mri_tmp, mri_seg, CSF_VAL) ; MRIfree(&mri_tmp) ; mri_ribbon = MRInot(mri_seg, NULL) ; MRIcopyLabel(mri_seg, mri_pial, CSF_VAL) ; MRIreplaceValuesOnly(mri_pial, mri_pial, CSF_VAL, 0) ; MRIand(mri_ribbon, mri_pial, mri_ribbon, 1) ; MRIbinarize(mri_ribbon, mri_ribbon, 1, 0, GM_VAL) ; MRIcopyLabel(mri_ribbon, mri_seg, GM_VAL) ; MRIreplaceValuesOnly(mri_seg, mri_seg, CSF_VAL, 0) ; add_aseg_structures_outside_ribbon(mri_seg, mri_aseg, mri_seg, WM_VAL, SUBCORT_GM_VAL, CSF_VAL) ; { MATRIX *m_conformed_to_epi_vox2vox, *m_seg_to_conformed_vox2vox, *m_seg_to_epi_vox2vox ; if (m_regdat == NULL) // assume identity transform m_seg_to_epi_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_in) ; else { m_conformed_to_epi_vox2vox = MRIvoxToVoxFromTkRegMtx(mri_in, mri_aseg, m_regdat); m_seg_to_conformed_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_aseg) ; m_seg_to_epi_vox2vox = MatrixMultiply(m_conformed_to_epi_vox2vox, m_seg_to_conformed_vox2vox, NULL) ; MatrixFree(&m_regdat) ; MatrixFree(&m_conformed_to_epi_vox2vox) ; MatrixFree(&m_seg_to_conformed_vox2vox); } printf("seg to EPI vox2vox matrix:\n") ; MatrixPrint(Gstdout, m_seg_to_epi_vox2vox) ; mri_cortex = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ; MRIcopyHeader(mri_in, mri_cortex) ; mri_subcort_gm = MRIclone(mri_cortex, NULL) ; mri_wm = MRIclone(mri_cortex, NULL) ; mri_csf = MRIclone(mri_cortex, NULL) ; printf("computing partial volume fractions...\n") ; MRIcomputePartialVolumeFractions(mri_in, m_seg_to_epi_vox2vox, mri_seg, mri_wm, mri_subcort_gm, mri_cortex, mri_csf, WM_VAL, SUBCORT_GM_VAL, GM_VAL, 0) ; } sprintf(fname, "%s.wm.%s", out_stem,fmt) ; printf("writing wm %% to %s\n", fname) ; MRIwrite(mri_wm, fname) ; sprintf(fname, "%s.subcort_gm.%s", out_stem,fmt) ; printf("writing subcortical gm %% to %s\n", fname) ; MRIwrite(mri_subcort_gm, fname) ; sprintf(fname, "%s.cortex.%s", out_stem, fmt) ; printf("writing cortical gm %% to %s\n", fname) ; MRIwrite(mri_cortex, fname) ; sprintf(fname, "%s.csf.%s", out_stem,fmt) ; printf("writing csf %% to %s\n", fname) ; MRIwrite(mri_csf, fname) ; msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; printf("volume fraction calculation 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) ; }
int main(int argc, char *argv[]) { char **av, *out_name ; int ac, nargs ; int msec, minutes, seconds ; struct timeb start ; MRI_SURFACE *mris ; GCA_MORPH *gcam ; MRI *mri = NULL ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mris_interpolate_warp.c,v 1.5 2011/10/07 12:07:26 fischl Exp $", "$Name: $"); 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) ; } /* note that a "forward" morph means a retraction, so we reverse the order of the argvs here. This means that for every voxel in the inflated image we have a vector that points to where in the original image it came from, and *NOT* the reverse. */ mris = MRISread(argv[2]) ; if (mris == NULL) ErrorExit(ERROR_NOFILE, "%s: could not read source surface %s\n", Progname,argv[2]) ; MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ; if (MRISreadVertexPositions(mris, argv[1]) != NO_ERROR) ErrorExit(ERROR_NOFILE, "%s: could not read target surface %s\n", Progname,argv[1]) ; if (like_vol_name == NULL) { mri = MRIallocSequence(mris->vg.width, mris->vg.height, mris->vg.depth, MRI_FLOAT, 3) ; MRIcopyVolGeomToMRI(mri, &mris->vg) ; } else { MRI *mri_tmp ; mri_tmp = MRIread(like_vol_name) ; if (mri_tmp == NULL) { ErrorExit(ERROR_NOFILE, "%s: could not like volume %s\n", like_vol_name) ; } mri = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT, 3) ; MRIcopyHeader(mri_tmp, mri) ; MRIfree(&mri_tmp) ; } if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) { double xv, yv, zv ; VERTEX *v = &mris->vertices[0] ; MRISsurfaceRASToVoxel(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ; printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv); MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ; printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv); DiagBreak() ; } { MRI *mri_tmp ; mri_tmp = expand_mri_to_fit_surface(mris, mri) ; MRIfree(&mri) ; mri = mri_tmp ; } write_surface_warp_into_volume(mris, mri, niter) ; if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri, "warp.mgz") ; gcam = GCAMalloc(mri->width, mri->height, mri->depth) ; GCAMinitVolGeom(gcam, mri, mri) ; GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ; // GCAMreadWarpFromMRI(gcam, mri) ; // GCAsetVolGeom(gca, &gcam->atlas); #if 0 gcam->gca = gcaAllocMax(1, 1, 1, mri->width, mri->height, mri->depth, 0, 0) ; GCAMinit(gcam, mri, NULL, NULL, 0) ; #endif #if 0 GCAMinvert(gcam, mri) ; GCAMwriteInverseWarpToMRI(gcam, mri) ; GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ; // should be inverse now #endif if (mri_in) { MRI *mri_warped, *mri_tmp ; printf("applying warp to %s and writing to %s\n", mri_in->fname, out_fname) ; mri_tmp = MRIextractRegionAndPad(mri_in, NULL, NULL, pad) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; mri_warped = GCAMmorphToAtlas(mri_in, gcam, NULL, -1, SAMPLE_TRILINEAR) ; MRIwrite(mri_warped, out_fname) ; if (Gdiag_no >= 0) { double xi, yi, zi, xo, yo, zo, val; int xp, yp, zp ; GCA_MORPH_NODE *gcamn ; VERTEX *v = &mris->vertices[Gdiag_no] ; MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xi, &yi, &zi) ; MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xo, &yo, &zo) ; printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f)\n", Gdiag_no, xi, yi, zi, xo, yo, zo) ; MRIsampleVolume(mri_in, xo, yo, zo, &val) ; xp = nint(xi) ; yp = nint(yi) ; zp = nint(zi) ; gcamn = &gcam->nodes[xp][yp][zp] ; printf("warp = (%2.1f, %2.1f, %2.1f), orig (%2.1f %2.1f %2.1f) = %2.1f \n", gcamn->x, gcamn->y, gcamn->z, gcamn->origx, gcamn->origy, gcamn->origz,val) ; DiagBreak() ; } } if (no_write == 0) { out_name = argv[3] ; GCAMwrite(gcam, out_name) ; } msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; fprintf(stderr, "warp field calculation took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
int main(int argc, char* argv[]) { IoParams params; try { params.parse(argc,argv); } catch (const std::exception& excp) { std::cerr << " Exception while parsing cmd-line\n" << excp.what() << std::endl; exit(1); } catch (...) { std::cerr << " unhandled exception caught while parsing cmd line\n"; exit(1); } boost::shared_ptr<gmp::VolumeMorph> pmorph(new gmp::VolumeMorph); if ( !params.strTemplate.empty() ) { MRI* mri = MRIread( const_cast<char*>(params.strTemplate.c_str()) ); if (!mri) std::cerr << " Failed to open template mri " << params.strTemplate << std::endl; else pmorph->set_volGeom_fixed(mri); MRIfree(&mri); } if ( !params.strSubject.empty() ) { MRI* mri = MRIread( const_cast<char*>(params.strSubject.c_str()) ); if (!mri) std::cerr << " Failed to open subject mri " << params.strSubject << std::endl; else pmorph->set_volGeom_moving(mri); MRIfree(&mri); } IoParams::MorphContainerType::iterator it; for ( it = params.items.begin(); it != params.items.end(); ++it ) { if ( it->type == "affine" ) { boost::shared_ptr<gmp::AffineTransform3d> paffine( new gmp::AffineTransform3d); float* pf = read_transform( it->file.c_str() ); if ( !pf ) { std::cerr << " failed to read transform\n"; exit(1); } paffine->set_pars( pf); pmorph->m_transforms.push_back( paffine ); } else if ( it->type == "volume" ) { boost::shared_ptr<gmp::DeltaTransform3d> pvol( new gmp::DeltaTransform3d); MRI* field = MRIread ( const_cast<char*>( it->file.c_str() ) ); if ( !field ) { std::cerr << " failed to read field " << std::endl; exit(1); } pvol->set_field(field); pmorph->m_transforms.push_back( pvol ); } else if ( it->type == "gcam" ) { boost::shared_ptr<gmp::DeltaTransform3d> pvol( new gmp::DeltaTransform3d); GCA_MORPH* gcam = GCAMread( const_cast<char*>( it->file.c_str() ) ); if ( !gcam ) { std::cerr << " failed to read GCAM " << std::endl; exit(1); } // create bogus MRI to hold the geometry MRI* mri_template = MRIread( const_cast<char*> ( params.strTemplate.c_str() ) ); MRI* mriBuf = MRIalloc( gcam->image.width, gcam->image.height, gcam->image.depth, MRI_UCHAR); useVolGeomToMRI( &gcam->image, mriBuf ); GCAMrasToVox(gcam, mriBuf ); MRIfree( &mriBuf ); std::cout << " atlas geometry = " << gcam->atlas.width << " , " << gcam->atlas.height << " , " << gcam->atlas.depth << std::endl << " image geometry = " << gcam->image.width << " , " << gcam->image.height << " , " << gcam->image.depth << std::endl; MRI* mri = MRIallocSequence( mri_template->width, mri_template->height, mri_template->depth, MRI_FLOAT, 3); MRIcopyHeader(mri_template, mri); g_vDbgCoords = params.vDbgCoords; try { //MRI* mask = CopyGcamToDeltaField(gcam, mri); pvol->set_field(mri); //pvol->set_mask(mask); pmorph->m_transforms.push_back( pvol ); } catch (const std::string& e) { std::cerr << " Exception caught while processing GCAM node\n" << e << std::endl; exit(1); } MRIfree(&mri_template); } else if ( it->type == "morph" ) { boost::shared_ptr<gmp::VolumeMorph> tmpMorph(new gmp::VolumeMorph); try { tmpMorph->load( it->file.c_str() ); } catch (const char* msg) { std::cerr << " Exception caught while loading morph in file " << it->file << std::endl; exit(1); } for ( gmp::VolumeMorph::TransformContainerType::iterator transformIter = tmpMorph->m_transforms.begin(); transformIter != tmpMorph->m_transforms.end(); ++transformIter ) pmorph->m_transforms.push_back( *transformIter ); } else if ( it->type == "mesh" ) { boost::shared_ptr<gmp::FemTransform3d> pfem(new gmp::FemTransform3d); boost::shared_ptr<CMesh3d> pmesh(new CMesh3d); pmesh->load( it->file.c_str() ); pfem->m_sharedMesh = pmesh; pmorph->m_transforms.push_back(pfem); } else { std::cerr << " unhandled transform type " << it->type << std::endl; } } // next it // finally write morph file try { pmorph->save( params.strOut.c_str() ); } catch (const char* msg) { std::cerr << " Exception caught while saving morph\n" << msg << std::endl; exit(1); } return 0; }
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) ; }
static MRI * MRIcomputeSurfaceDistanceIntensities(MRI_SURFACE *mris, MRI *mri_ribbon, MRI *mri_aparc, MRI *mri, MRI *mri_aseg, int whalf) { MRI *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist ; int vno, ngm, outside_of_ribbon, label0, label, ohemi_label, xi, yi, zi, xk, yk, zk, x0, y0, z0, hemi_label, assignable ; double xv, yv, zv, step_size, dist, thickness, wdist, pdist, snx, sny, snz, nx, ny, nz, xl, yl, zl, x, y, z, dot, angle ; VERTEX *v ; mri_features = MRIallocSequence(mris->nvertices, 1, 1, MRI_FLOAT, 1) ; // one samples inwards, one in ribbon, and one outside MRIcopyHeader(mri, mri_features) ; mri_binary = MRIcopy(mri_ribbon, NULL) ; mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ; mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_pial_dist, "pd.mgz") ; MRIclear(mri_binary) ; MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ; MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ; MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ; mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL); if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) MRIwrite(mri_white_dist, "wd.mgz") ; if (mris->hemisphere == LEFT_HEMISPHERE) { ohemi_label = Right_Cerebral_Cortex ; hemi_label = Left_Cerebral_Cortex ; } else { hemi_label = Right_Cerebral_Cortex ; ohemi_label = Left_Cerebral_Cortex ; } step_size = mri->xsize/2 ; for (vno = 0 ; vno < mris->nvertices ; vno++) { v = &mris->vertices[vno] ; if (vno == Gdiag_no) DiagBreak() ; if (v->ripflag) continue ; // not cortex nx = v->pialx - v->whitex ; ny = v->pialy - v->whitey ; nz = v->pialz - v->whitez ; thickness = sqrt(nx*nx + ny*ny + nz*nz) ; if (FZERO(thickness)) continue ; // no cortex here x = (v->pialx + v->whitex)/2 ; y = (v->pialy + v->whitey)/2 ; z = (v->pialz + v->whitez)/2 ; // halfway between white and pial is x0 MRISsurfaceRASToVoxelCached(mris, mri_aseg, x, y, z, &xl, &yl, &zl) ; x0 = nint(xl); y0 = nint(yl) ; z0 = nint(zl) ; label0 = MRIgetVoxVal(mri_aparc, x0, y0, z0,0) ; // compute surface normal in voxel coords MRISsurfaceRASToVoxelCached(mris, mri_aseg, x+v->nx, y+v->ny, z+v->nz, &snx, &sny, &snz) ; snx -= xl ; sny -= yl ; snz -= zl ; for (ngm = 0, xk = -whalf ; xk <= whalf ; xk++) { xi = mri_aseg->xi[x0+xk] ; for (yk = -whalf ; yk <= whalf ; yk++) { yi = mri_aseg->yi[y0+yk] ; for (zk = -whalf ; zk <= whalf ; zk++) { zi = mri_aseg->zi[z0+zk] ; label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ; if (xi == Gx && yi == Gy && zi == Gz) DiagBreak() ; if (label != hemi_label) continue ; label = MRIgetVoxVal(mri_aparc, xi, yi, zi,0) ; if (label && label != label0) // if outside the ribbon it won't be assigned to a parcel continue ; // constrain it to be in the same cortical parcel // search along vector connecting x0 to this point to make sure it is we don't perforate wm or leave and re-enter cortex nx = xi-x0 ; ny = yi-y0 ; nz = zi-z0 ; thickness = sqrt(nx*nx + ny*ny + nz*nz) ; assignable = 1 ; // assume this point should be counted if (thickness > 0) { nx /= thickness ; ny /= thickness ; nz /= thickness ; dot = nx*snx + ny*sny + nz*snz ; angle = acos(dot) ; if (FABS(angle) > angle_threshold) assignable = 0 ; outside_of_ribbon = 0 ; for (dist = 0 ; assignable && dist <= thickness ; dist += step_size) { xv = x0+nx*dist ; yv = y0+ny*dist ; zv = z0+nz*dist ; if (nint(xv) == Gx && nint(yv) == Gy && nint(zv) == Gz) DiagBreak() ; MRIsampleVolume(mri_pial_dist, xv, yv, zv, &pdist) ; MRIsampleVolume(mri_white_dist, xv, yv, zv, &wdist) ; label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ; if (SKIP_LABEL(label) || label == ohemi_label) assignable = 0 ; if (wdist < 0) // entered wm - not assignable assignable = 0 ; else { if (pdist > 0) // outside pial surface outside_of_ribbon = 1 ; else { if (outside_of_ribbon) // left ribbon and reentered assignable = 0 ; } } } } // close of thickness > 0 if (assignable) ngm++ ; else DiagBreak() ; } } } MRIsetVoxVal(mri_features, vno, 0, 0, 0, ngm) ; } MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ; return(mri_features) ; }
/*---------------------------------------------------------------*/ int main(int argc, char *argv[]) { int nargs,r,c,s,n,segid,err; double val; nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; cmdline = argv2cmdline(argc,argv); uname(&uts); getcwd(cwd,2000); Progname = argv[0] ; argc --; argv++; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; if (argc == 0) usage_exit(); parse_commandline(argc, argv); check_options(); if (checkoptsonly) return(0); dump_options(stdout); SUBJECTS_DIR = getenv("SUBJECTS_DIR"); if (SUBJECTS_DIR == NULL) { printf("ERROR: SUBJECTS_DIR not defined in environment\n"); exit(1); } if (DoDavid) { printf("Loading David's stat file\n"); nitems = LoadDavidsTable(statfile, &lutindex, &log10p); } if (DoSue) { printf("Loading Sue's stat file\n"); nitems = LoadSuesTable(statfile, datcol1, log10flag, &lutindex, &log10p); } if (nitems == 0) { printf("ERROR: could not find any items in %s\n",statfile); exit(1); } if (annot == NULL) { seg = MRIread(segfile); if (seg == NULL) exit(1); } else { printf("Constructing seg from annotation\n"); sprintf(tmpstr,"%s/%s/surf/%s.white",SUBJECTS_DIR,subject,hemi); mris = MRISread(tmpstr); if (mris==NULL) exit(1); sprintf(tmpstr,"%s/%s/label/%s.%s.annot",SUBJECTS_DIR,subject,hemi,annot); err = MRISreadAnnotation(mris, tmpstr); if (err) exit(1); seg = MRISannotIndex2Seg(mris); } out = MRIallocSequence(seg->width,seg->height,seg->depth,MRI_FLOAT,1); MRIcopyHeader(seg,out); for (c=0; c < seg->width; c++) { //printf("%3d ",c); //if(c%20 == 19) printf("\n"); fflush(stdout); for (r=0; r < seg->height; r++) { for (s=0; s < seg->depth; s++) { segid = MRIgetVoxVal(seg,c,r,s,0); val = 0; if (segid != 0) { if (annot != NULL) { if (strcmp(hemi,"lh")==0) segid = segid + 1000; if (strcmp(hemi,"rh")==0) segid = segid + 2000; MRIsetVoxVal(seg,c,r,s,0,segid); } for (n=0; n < nitems; n++) { if (lutindex[n] == segid) { val = log10p[n]; break; } } } MRIsetVoxVal(out,c,r,s,0,val); } } } printf("\n"); MRIwrite(out,outfile); MRIwrite(seg,"segtmp.mgh"); printf("mri_stats2seg done\n"); return 0; }
/*--------------------------------------------------*/ int main(int argc, char **argv) { int nargs, nthin, nframestot=0, nr=0,nc=0,ns=0, fout; int r,c,s,f,outf,nframes,err,nthrep; double v, v1, v2, vavg, vsum; int inputDatatype=MRI_UCHAR; MATRIX *Upca=NULL,*Spca=NULL; MRI *Vpca=NULL; char *stem; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $"); if (nargs && argc - nargs == 1) { exit (0); } argc -= nargs; Progname = argv[0] ; argc --; argv++; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; if (argc == 0) { usage_exit(); } parse_commandline(argc, argv); check_options(); dump_options(stdout); if(maskfile) { printf("Loading mask %s\n",maskfile); mask = MRIread(maskfile); if(mask == NULL) { exit(1); } } printf("ninputs = %d\n",ninputs); if(DoCheck) { printf("Checking inputs\n"); for(nthin = 0; nthin < ninputs; nthin++) { if(Gdiag_no > 0 || debug) { printf("Checking %2d %s\n",nthin,inlist[nthin]); fflush(stdout); } mritmp = MRIreadHeader(inlist[nthin],MRI_VOLUME_TYPE_UNKNOWN); if (mritmp == NULL) { printf("ERROR: reading %s\n",inlist[nthin]); exit(1); } if (nthin == 0) { nc = mritmp->width; nr = mritmp->height; ns = mritmp->depth; } if (mritmp->width != nc || mritmp->height != nr || mritmp->depth != ns) { printf("ERROR: dimension mismatch between %s and %s\n", inlist[0],inlist[nthin]); exit(1); } nframestot += mritmp->nframes; inputDatatype = mritmp->type; // used by DoKeepDatatype option MRIfree(&mritmp); } } else { printf("NOT Checking inputs, assuming nframestot = ninputs\n"); nframestot = ninputs; mritmp = MRIreadHeader(inlist[0],MRI_VOLUME_TYPE_UNKNOWN); if (mritmp == NULL) { printf("ERROR: reading %s\n",inlist[0]); exit(1); } nc = mritmp->width; nr = mritmp->height; ns = mritmp->depth; MRIfree(&mritmp); } printf("nframestot = %d\n",nframestot); if (DoRMS) { if (ninputs != 1) { printf("ERROR: --rms supports only single input w/ multiple frames\n"); exit (1); } if (nframestot == 1) { printf("ERROR: --rms input must have multiple frames\n"); exit (1); } } if(ngroups != 0) { printf("Creating grouped mean matrix ngroups=%d, nper=%d\n", ngroups,nframestot/ngroups); M = GroupedMeanMatrix(ngroups,nframestot); if(M==NULL) { exit(1); } if(debug) { MatrixPrint(stdout,M); } } if(M != NULL) { if(nframestot != M->cols) { printf("ERROR: dimension mismatch between inputs (%d) and matrix (%d)\n", nframestot,M->rows); exit(1); } } if (DoPaired) { if (remainder(nframestot,2) != 0) { printf("ERROR: --paired-xxx specified but there are an " "odd number of frames\n"); exit(1); } } printf("Allocing output\n"); fflush(stdout); int datatype=MRI_FLOAT; if (DoKeepDatatype) { datatype = inputDatatype; } if (DoRMS) { // RMS always has single frame output mriout = MRIallocSequence(nc,nr,ns,datatype,1); } else { mriout = MRIallocSequence(nc,nr,ns,datatype,nframestot); } if (mriout == NULL) { exit(1); } printf("Done allocing\n"); fout = 0; for (nthin = 0; nthin < ninputs; nthin++) { if (DoRMS) break; // MRIrms reads the input frames if(Gdiag_no > 0 || debug) { printf("Loading %dth input %s\n", nthin+1,fio_basename(inlist[nthin],NULL)); fflush(stdout); } mritmp = MRIread(inlist[nthin]); if(mritmp == NULL) { printf("ERROR: loading %s\n",inlist[nthin]); exit(1); } if(nthin == 0) { MRIcopyHeader(mritmp, mriout); //mriout->nframes = nframestot; } if(DoAbs) { if(Gdiag_no > 0 || debug) { printf("Removing sign from input\n"); } MRIabs(mritmp,mritmp); } if(DoPos) { if(Gdiag_no > 0 || debug) { printf("Setting input negatives to 0.\n"); } MRIpos(mritmp,mritmp); } if(DoNeg) { if(Gdiag_no > 0 || debug) { printf("Setting input positives to 0.\n"); } MRIneg(mritmp,mritmp); } for(f=0; f < mritmp->nframes; f++) { for(c=0; c < nc; c++) { for(r=0; r < nr; r++) { for(s=0; s < ns; s++) { v = MRIgetVoxVal(mritmp,c,r,s,f); MRIsetVoxVal(mriout,c,r,s,fout,v); } } } fout++; } MRIfree(&mritmp); } if(DoCombine) { // Average frames from non-zero voxels int nhits; mritmp = MRIallocSequence(nc,nr,ns,MRI_FLOAT,1); MRIcopyHeader(mritmp,mriout); for(c=0; c < nc; c++) { for(r=0; r < nr; r++) { for(s=0; s < ns; s++) { nhits = 0; vsum = 0; for(f=0; f < mriout->nframes; f++) { v = MRIgetVoxVal(mriout,c,r,s,f); if (v > 0) { vsum += v; nhits ++; } } if(nhits > 0 ) { MRIsetVoxVal(mritmp,c,r,s,0,vsum/nhits); } } // for s }// for r } // for c MRIfree(&mriout); mriout = mritmp; } // do combine if(DoPrune) { // This computes the prune mask, applied below printf("Computing prune mask \n"); PruneMask = MRIframeBinarize(mriout,FLT_MIN,NULL); printf("Found %d voxels in prune mask\n",MRInMask(PruneMask)); } if(DoNormMean) { printf("Normalizing by mean across frames\n"); MRInormalizeFramesMean(mriout); } if(DoNorm1) { printf("Normalizing by first across frames\n"); MRInormalizeFramesFirst(mriout); } if(DoASL) { printf("Computing ASL matrix matrix\n"); M = ASLinterpMatrix(mriout->nframes); } if(M != NULL) { printf("Multiplying by matrix\n"); mritmp = fMRImatrixMultiply(mriout, M, NULL); if(mritmp == NULL) { exit(1); } MRIfree(&mriout); mriout = mritmp; } if(DoPaired) { printf("Combining pairs\n"); mritmp = MRIcloneBySpace(mriout,-1,mriout->nframes/2); for (c=0; c < nc; c++) { for (r=0; r < nr; r++) { for (s=0; s < ns; s++) { fout = 0; for (f=0; f < mriout->nframes; f+=2) { v1 = MRIgetVoxVal(mriout,c,r,s,f); v2 = MRIgetVoxVal(mriout,c,r,s,f+1); v = 0; if(DoPairedAvg) { v = (v1+v2)/2.0; } if(DoPairedSum) { v = (v1+v2); } if(DoPairedDiff) { v = v1-v2; // difference } if(DoPairedDiffNorm) { v = v1-v2; // difference vavg = (v1+v2)/2.0; if (vavg != 0.0) { v = v/vavg; } } if(DoPairedDiffNorm1) { v = v1-v2; // difference if (v1 != 0.0) { v = v/v1; } else { v = 0; } } if(DoPairedDiffNorm2) { v = v1-v2; // difference if (v2 != 0.0) { v = v/v2; } else { v = 0; } } MRIsetVoxVal(mritmp,c,r,s,fout,v); fout++; } } } } MRIfree(&mriout); mriout = mritmp; } nframes = mriout->nframes; printf("nframes = %d\n",nframes); if(DoBonfCor) { DoAdd = 1; AddVal = -log10(mriout->nframes); } if(DoMean) { printf("Computing mean across frames\n"); mritmp = MRIframeMean(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoMedian) { printf("Computing median across frames\n"); mritmp = MRIframeMedian(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoMeanDivN) { printf("Computing mean2 = sum/(nframes^2)\n"); mritmp = MRIframeSum(mriout,NULL); MRIfree(&mriout); mriout = mritmp; MRImultiplyConst(mriout, 1.0/(nframes*nframes), mriout); } if(DoSum) { printf("Computing sum across frames\n"); mritmp = MRIframeSum(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoTAR1) { printf("Computing temoral AR1 %d\n",mriout->nframes-TAR1DOFAdjust); mritmp = fMRItemporalAR1(mriout,TAR1DOFAdjust,NULL,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoStd || DoVar) { printf("Computing std/var across frames\n"); if(mriout->nframes < 2) { printf("ERROR: cannot compute std from one frame\n"); exit(1); } //mritmp = fMRIvariance(mriout, -1, 1, NULL); mritmp = fMRIcovariance(mriout, 0, -1, NULL, NULL); if(DoStd) { MRIsqrt(mritmp, mritmp); } MRIfree(&mriout); mriout = mritmp; } if(DoMax) { printf("Computing max across all frames \n"); mritmp = MRIvolMax(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoMaxIndex) { printf("Computing max index across all frames \n"); mritmp = MRIvolMaxIndex(mriout,1,NULL,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoConjunction) { printf("Computing conjunction across all frames \n"); mritmp = MRIconjunct(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoMin) { printf("Computing min across all frames \n"); mritmp = MRIvolMin(mriout,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoSort) { printf("Sorting \n"); mritmp = MRIsort(mriout,mask,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoVote) { printf("Voting \n"); mritmp = MRIvote(mriout,mask,NULL); MRIfree(&mriout); mriout = mritmp; } if(DoMultiply) { printf("Multiplying by %lf\n",MultiplyVal); MRImultiplyConst(mriout, MultiplyVal, mriout); } if(DoAdd) { printf("Adding %lf\n",AddVal); MRIaddConst(mriout, AddVal, mriout); } if(DoSCM) { printf("Computing spatial correlation matrix (%d)\n",mriout->nframes); mritmp = fMRIspatialCorMatrix(mriout); if(mritmp == NULL) { exit(1); } MRIfree(&mriout); mriout = mritmp; } if(DoPCA) { // Saves only non-zero components printf("Computing PCA\n"); if(PCAMaskFile) { printf(" PCA Mask %s\n",PCAMaskFile); PCAMask = MRIread(PCAMaskFile); if(PCAMask == NULL) { exit(1); } } err=MRIpca(mriout, &Upca, &Spca, &Vpca, PCAMask); if(err) { exit(1); } stem = IDstemFromName(out); sprintf(tmpstr,"%s.u.mtx",stem); MatrixWriteTxt(tmpstr, Upca); sprintf(tmpstr,"%s.stats.dat",stem); WritePCAStats(tmpstr,Spca); MRIfree(&mriout); mriout = Vpca; } if(NReplications > 0) { printf("NReplications %d\n",NReplications); mritmp = MRIallocSequence(mriout->width, mriout->height, mriout->depth, mriout->type, mriout->nframes*NReplications); if(mritmp == NULL) { exit(1); } printf("Done allocing\n"); MRIcopyHeader(mriout,mritmp); for(c=0; c < mriout->width; c++) { for(r=0; r < mriout->height; r++) { for(s=0; s < mriout->depth; s++) { outf = 0; for(nthrep = 0; nthrep < NReplications; nthrep++) { for(f=0; f < mriout->nframes; f++) { v = MRIgetVoxVal(mriout,c,r,s,f); MRIsetVoxVal(mritmp,c,r,s,outf,v); outf ++; } } } } } MRIfree(&mriout); mriout = mritmp; } if(DoPrune) { // Apply prune mask that was computed above printf("Applying prune mask \n"); MRImask(mriout, PruneMask, mriout, 0, 0); } if(DoRMS) { printf("Computing RMS across input frames\n"); mritmp = MRIread(inlist[0]); MRIcopyHeader(mritmp, mriout); MRIrms(mritmp,mriout); } printf("Writing to %s\n",out); err = MRIwrite(mriout,out); if(err) { exit(err); } return(0); }
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) ; }
/*------------------------------------------------------*/ MRI *afniRead(const char *fname, int read_volume) { FILE *fp; char header_fname[STRLEN]; char *c; MRI *mri, *header; int big_endian_flag; long brik_file_length; long nvoxels; int bytes_per_voxel; int i, j, k; int swap_flag; AF af; float scaling = 1.; void *pmem = 0; float *pf; short *ps; unsigned char *pc; float det; float xfov, yfov, zfov; float fMin = 0.; float fMax = 0.; float flMin = 0.; float flMax = 0.; int initialized = 0; int frame; int bytes; strcpy(header_fname, fname); c = strrchr(header_fname, '.'); if (c == NULL) { errno = 0; ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname)); } if (strcmp(c, ".BRIK") != 0) { errno = 0; ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): bad file name %s", fname)); } sprintf(c, ".HEAD"); if ((fp = fopen(header_fname, "r")) == NULL) { errno = 0; ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname)); } // initialize AFNI structure AFinit(&af); // read header file if (!readAFNIHeader(fp, &af)) return (NULL); printAFNIHeader(&af); // well, we don't have time if (af.numtypes != 1) // should be the same as af.dataset_rank[1] = subbricks { errno = 0; // ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): nframes = %d (only 1 frame supported)", af.numtypes)); printf("INFO: number of frames dataset_rank[1] = %d : numtypes = %d \n", af.dataset_rank[1], af.numtypes); } // byteorder_string : required field if (strcmp(af.byteorder_string, "MSB_FIRST") == 0) big_endian_flag = 1; else if (strcmp(af.byteorder_string, "LSB_FIRST") == 0) big_endian_flag = 0; else { errno = 0; ErrorReturn(NULL, (ERROR_BADPARM, "read_afni_header(): unrecognized byte order string %s", af.byteorder_string)); } // brick_types : required field if (af.brick_types[0] == 2 // int || af.brick_types[0] > 3 )// 4 = double, 5 = complex, 6 = rgb { errno = 0; ErrorReturn(NULL, (ERROR_BADPARM, "afniRead(): unsupported data type %d, Must be 0 (byte), 1(short), or 3(float)", af.brick_types[0])); } ////////////////////////////////////////////////////////////////////////////////// // now we allocate space for MRI // dataset_dimensions : required field header = MRIallocHeader(af.dataset_dimensions[0], af.dataset_dimensions[1], af.dataset_dimensions[2], MRI_UCHAR, af.dataset_rank[1] ); // set number of frames header->nframes = af.dataset_rank[1]; // direction cosines (use orient_specific) // orient_specific : required field header->x_r = afni_orientations[af.orient_specific[0]][0]; header->x_a = afni_orientations[af.orient_specific[0]][1]; header->x_s = afni_orientations[af.orient_specific[0]][2]; header->y_r = afni_orientations[af.orient_specific[1]][0]; header->y_a = afni_orientations[af.orient_specific[1]][1]; header->y_s = afni_orientations[af.orient_specific[1]][2]; header->z_r = afni_orientations[af.orient_specific[2]][0]; header->z_a = afni_orientations[af.orient_specific[2]][1]; header->z_s = afni_orientations[af.orient_specific[2]][2]; /* --- quick determinant check --- */ det = + header->x_r * (header->y_a * header->z_s - header->z_a * header->y_s) - header->x_a * (header->y_r * header->z_s - header->z_r * header->y_s) + header->x_s * (header->y_r * header->z_a - header->z_r * header->y_a); if (det == 0) { MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_BADPARM, "read_afni_header(): error in orientations %d, %d, %d (direction cosine matrix has determinant zero)", af.orient_specific[0], af.orient_specific[1], af.orient_specific[2])); } // sizes use delta // delta : required field header->xsize = af.delta[0]; header->ysize = af.delta[1]; header->zsize = af.delta[2]; // uses origin // origin : required field header->c_r = header->x_r * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) + header->y_r * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) + header->z_r * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]); header->c_a = header->x_a * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) + header->y_a * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) + header->z_a * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]); header->c_s = header->x_s * (header->xsize * (header->width-1.0)/2.0 + af.origin[0]) + header->y_s * (header->ysize * (header->height-1.0)/2.0 + af.origin[1]) + header->z_s * (header->zsize * (header->depth-1.0)/2.0 + af.origin[2]); header->ras_good_flag = 1; if (header->xsize < 0) header->xsize = -header->xsize; if (header->ysize < 0) header->ysize = -header->ysize; if (header->zsize < 0) header->zsize = -header->zsize; header->imnr0 = 1; header->imnr1 = header->depth; header->ps = header->xsize; header->thick = header->zsize; header->xend = (header->width / 2.0) * header->xsize; header->xstart = -header->xend; header->yend = (header->height / 2.0) * header->ysize; header->ystart = -header->yend; header->zend = (header->depth / 2.0) * header->zsize; header->zstart = -header->zend; xfov = header->xend - header->xstart; yfov = header->yend - header->ystart; zfov = header->zend - header->zstart; header->fov = ( xfov > yfov ? (xfov > zfov ? xfov : zfov ) : (yfov > zfov ? yfov : zfov ) ); #if (BYTE_ORDER==LITTLE_ENDIAN) //#ifdef Linux swap_flag = big_endian_flag; #else swap_flag = !big_endian_flag; #endif if ((fp = fopen(fname, "r")) == NULL) { MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error opening file %s", header_fname)); } fseek(fp, 0, SEEK_END); brik_file_length = ftell(fp); fseek(fp, 0, SEEK_SET); // number of voxels consecutive nvoxels = header->width * header->height * header->depth * header->nframes; if (brik_file_length % nvoxels) { fclose(fp); MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): BRIK file length (%d) is not divisible by the number of voxels (%d)", brik_file_length, nvoxels)); } // bytes_per_voxel = brik_file_length / nvoxels; // this assumes one frame bytes_per_voxel = af.brick_types[0] + 1; // 0(byte)-> 1, 1(short) -> 2, 3(float)->4 bytes = header->width*header->height*header->depth*bytes_per_voxel; // this check is for nframes = 1 case which is the one we are supporting if (bytes_per_voxel != brik_file_length/nvoxels) { fclose(fp); MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): type info stored in header does not agree with the file size: %d != %d/%d", bytes_per_voxel, brik_file_length/nvoxels)); } // if brick_float_facs != 0 then we scale values to be float if (af.numfacs != 0 && af.brick_float_facs[0] != 0.) { header->type = MRI_FLOAT; scaling = af.brick_float_facs[0]; } else { if (bytes_per_voxel == 1) header->type = MRI_UCHAR; else if (bytes_per_voxel == 2) header->type = MRI_SHORT; else if (bytes_per_voxel == 4) header->type = MRI_FLOAT; else { fclose(fp); MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_UNSUPPORTED, "afniRead(): don't know what to do with %d bytes per voxel", bytes_per_voxel)); } } /////////////////////////////////////////////////////////////////////// if (read_volume) { // mri = MRIalloc(header->width, header->height, header->depth, header->type); mri = MRIallocSequence(header->width, header->height, header->depth, header->type, header->nframes) ; MRIcopyHeader(header, mri); for (frame = 0; frame < header->nframes; ++frame) { initialized = 0; for (k = 0;k < mri->depth;k++) { for (j = 0;j < mri->height;j++) { if (af.brick_float_facs[frame]) scaling = af.brick_float_facs[frame]; else scaling = 1.; { pmem = (void *) malloc(bytes_per_voxel*mri->width); if (pmem) { if (fread(pmem, bytes_per_voxel, mri->width, fp) != mri->width) { fclose(fp); MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): error reading from file %s", fname)); } // swap bytes if (swap_flag) { if (bytes_per_voxel == 2) // short { swab(pmem, pmem, mri->width * 2); } else if (bytes_per_voxel == 4) // float { pf = (float *) pmem; for (i = 0;i < mri->width;i++, pf++) *pf = swapFloat(*pf); } } // now scaling if (bytes_per_voxel == 1) // byte { pc = (unsigned char *) pmem; for (i=0; i < mri->width; i++) { if (scaling == 1.) MRIseq_vox(mri, i, j, k, frame) = *pc; else MRIFseq_vox(mri, i, j, k, frame) = ((float) (*pc))*scaling; ++pc; } findMinMaxByte((unsigned char *) pmem, mri->width, &flMin, &flMax); } if (bytes_per_voxel == 2) // short { ps = (short *) pmem; for (i=0; i < mri->width; i++) { // if (*ps != 0) // printf("%d ", *ps); if (scaling == 1.) MRISseq_vox(mri, i, j, k, frame) = *ps; else MRIFseq_vox(mri, i, j, k, frame) = ((float) (*ps))*scaling; ++ps; } findMinMaxShort((short *) pmem, mri->width, &flMin, &flMax); } else if (bytes_per_voxel == 4) // float { pf = (float *) pmem; for (i=0; i < mri->width; i++) { MRIFseq_vox(mri, i, j, k, frame) = (*pf)*scaling; ++pf; } findMinMaxFloat((float *) pmem, mri->width, &flMin, &flMax); } free(pmem); // if (initialized == 0) { fMin = flMin; fMax = flMax; initialized = 1; } else { if (flMin < fMin) fMin = flMin; if (flMax > fMax) fMax = flMax; // printf("\n fmin =%f, fmax = %f, local min = %f, max = %f\n", fMin, fMax, flMin, flMax); } } else { fclose(fp); MRIfree(&header); errno = 0; ErrorReturn(NULL, (ERROR_BADFILE, "afniRead(): could not allocate memory for reading %s", fname)); } } } // height } // depth // valid only for nframs == 1 { printf("BRICK_STATS min = %f <--> actual min = %f\n", af.brick_stats[0+2*frame], fMin*scaling); printf("BRICK_STATS max = %f <--> actual max = %f\n", af.brick_stats[1+2*frame], fMax*scaling); } } // nframes } else // not reading volume mri = MRIcopy(header, NULL); strcpy(mri->fname, fname); fclose(fp); MRIfree(&header); AFclean(&af); return(mri); } /* end afniRead() */
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) { int c,r,s,f; double val,rval; FILE *fp; MRI *mritmp; Progname = argv[0] ; argc --; argv++; ErrorInit(NULL, NULL, NULL) ; DiagInit(NULL, NULL, NULL) ; /* assign default geometry */ cdircos[0] = 1.0; cdircos[1] = 0.0; cdircos[2] = 0.0; rdircos[0] = 0.0; rdircos[1] = 1.0; rdircos[2] = 0.0; sdircos[0] = 0.0; sdircos[1] = 0.0; sdircos[2] = 1.0; res[0] = 1.0; res[1] = 1.0; res[2] = 1.0; cras[0] = 0.0; cras[1] = 0.0; cras[2] = 0.0; res[3] = 2.0; /* TR */ if (argc == 0) usage_exit(); parse_commandline(argc, argv); check_options(); dump_options(stdout); if(tempid != NULL) { printf("INFO: reading template header\n"); if(! DoCurv) mritemp = MRIreadHeader(tempid,tempfmtid); else mritemp = MRIread(tempid); if (mritemp == NULL) { printf("ERROR: reading %s header\n",tempid); exit(1); } if(NewVoxSizeSpeced){ dim[0] = round(mritemp->width*mritemp->xsize/res[0]); dim[1] = round(mritemp->height*mritemp->ysize/res[1]); dim[2] = round(mritemp->depth*mritemp->zsize/res[2]); dim[3] = mritemp->nframes; res[3] = mritemp->tr; dimSpeced = 1; } if(dimSpeced){ mritmp = MRIallocSequence(dim[0],dim[1],dim[2],MRI_FLOAT,dim[3]); MRIcopyHeader(mritemp,mritmp); MRIfree(&mritemp); mritemp = mritmp; } if(resSpeced){ mritemp->xsize = res[0]; mritemp->ysize = res[1]; mritemp->zsize = res[2]; mritemp->tr = res[3]; } dim[0] = mritemp->width; dim[1] = mritemp->height; dim[2] = mritemp->depth; if (nframes > 0) dim[3] = nframes; else dim[3] = mritemp->nframes; mritemp->nframes = dim[3]; } if(mritemp) { if(SpikeTP >= mritemp->nframes){ printf("ERROR: SpikeTP = %d >= mritemp->nframes = %d\n", SpikeTP,mritemp->nframes); exit(1); } } printf("Synthesizing\n"); srand48(seed); if (strcmp(pdfname,"gaussian")==0) mri = MRIrandn(dim[0], dim[1], dim[2], dim[3], gausmean, gausstd, NULL); else if (strcmp(pdfname,"uniform")==0) mri = MRIdrand48(dim[0], dim[1], dim[2], dim[3], 0, 1, NULL); else if (strcmp(pdfname,"const")==0) mri = MRIconst(dim[0], dim[1], dim[2], dim[3], ValueA, NULL); else if (strcmp(pdfname,"sphere")==0) { if(voxradius < 0) voxradius = sqrt( pow(dim[0]/2.0,2)+pow(dim[1]/2.0,2)+pow(dim[2]/2.0,2) )/2.0; printf("voxradius = %lf\n",voxradius); mri = MRIsphereMask(dim[0], dim[1], dim[2], dim[3], dim[0]/2.0, dim[1]/2.0, dim[2]/2.0, voxradius, ValueA, NULL); } else if (strcmp(pdfname,"delta")==0) { mri = MRIconst(dim[0], dim[1], dim[2], dim[3], delta_off_value, NULL); if (delta_crsf_speced == 0) { delta_crsf[0] = dim[0]/2; delta_crsf[1] = dim[1]/2; delta_crsf[2] = dim[2]/2; delta_crsf[3] = dim[3]/2; } printf("delta set to %g at %d %d %d %d\n",delta_value,delta_crsf[0], delta_crsf[1],delta_crsf[2],delta_crsf[3]); MRIFseq_vox(mri, delta_crsf[0], delta_crsf[1], delta_crsf[2], delta_crsf[3]) = delta_value; } else if (strcmp(pdfname,"chi2")==0) { rfs = RFspecInit(seed,NULL); rfs->name = strcpyalloc("chi2"); rfs->params[0] = dendof; mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); printf("Synthesizing chi2 with dof=%d\n",dendof); RFsynth(mri,rfs,NULL); } else if (strcmp(pdfname,"z")==0) { printf("Synthesizing z \n"); rfs = RFspecInit(seed,NULL); rfs->name = strcpyalloc("gaussian"); rfs->params[0] = 0; // mean rfs->params[1] = 1; // std mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri,rfs,NULL); } else if (strcmp(pdfname,"t")==0) { printf("Synthesizing t with dof=%d\n",dendof); rfs = RFspecInit(seed,NULL); rfs->name = strcpyalloc("t"); rfs->params[0] = dendof; mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri,rfs,NULL); } else if (strcmp(pdfname,"tr")==0) { printf("Synthesizing t with dof=%d as ratio of z/sqrt(chi2)\n",dendof); rfs = RFspecInit(seed,NULL); // numerator rfs->name = strcpyalloc("gaussian"); rfs->params[0] = 0; // mean rfs->params[1] = 1; // std mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri,rfs,NULL); // denominator rfs->name = strcpyalloc("chi2"); rfs->params[0] = dendof; mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri2,rfs,NULL); fMRIsqrt(mri2,mri2); // sqrt of chi2 mri = MRIdivide(mri,mri2,mri); MRIscalarMul(mri, mri, sqrt(dendof)) ; MRIfree(&mri2); } else if (strcmp(pdfname,"F")==0) { printf("Synthesizing F with num=%d den=%d\n",numdof,dendof); rfs = RFspecInit(seed,NULL); rfs->name = strcpyalloc("F"); rfs->params[0] = numdof; rfs->params[1] = dendof; mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri,rfs,NULL); } else if (strcmp(pdfname,"Fr")==0) { printf("Synthesizing F with num=%d den=%d as ratio of two chi2\n", numdof,dendof); rfs = RFspecInit(seed,NULL); rfs->name = strcpyalloc("chi2"); // numerator rfs->params[0] = numdof; mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri,rfs,NULL); // denominator rfs->params[0] = dendof; mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); RFsynth(mri2,rfs,NULL); mri = MRIdivide(mri,mri2,mri); MRIscalarMul(mri, mri, (double)dendof/numdof) ; MRIfree(&mri2); } else if (strcmp(pdfname,"voxcrs")==0) { // three frames. 1st=col, 2nd=row, 3rd=slice printf("Filling with vox CRS\n"); mri = MRIconst(dim[0], dim[1], dim[2], 3, 0, NULL); for(c=0; c < mri->width; c ++){ for(r=0; r < mri->height; r ++){ for(s=0; s < mri->depth; s ++){ MRIsetVoxVal(mri,c,r,s,0,c); MRIsetVoxVal(mri,c,r,s,1,r); MRIsetVoxVal(mri,c,r,s,2,s); } } } } else if (strcmp(pdfname,"boundingbox")==0) { printf("Setting bounding box \n"); if(mritemp == NULL) mritemp = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL); mri = MRIsetBoundingBox(mritemp,&boundingbox,ValueA,ValueB); if(!mri) exit(1); } else if (strcmp(pdfname,"checker")==0) { printf("Checker \n"); mri=MRIchecker(mritemp,NULL); if(!mri) exit(1); } else if (strcmp(pdfname,"sliceno")==0) { printf("SliceNo \n"); if(mritemp == NULL){ printf("ERROR: need --temp with sliceno\n"); exit(1); } mri=MRIsliceNo(mritemp,NULL); if(!mri) exit(1); } else if (strcmp(pdfname,"indexno")==0) { printf("IndexNo \n"); if(mritemp == NULL){ printf("ERROR: need --temp with indexno\n"); exit(1); } mri=MRIindexNo(mritemp,NULL); if(!mri) exit(1); } else if (strcmp(pdfname,"crs")==0) { printf("CRS \n"); if(mritemp == NULL){ printf("ERROR: need --temp with crs\n"); exit(1); } mri=MRIcrs(mritemp,NULL); if(!mri) exit(1); } else { printf("ERROR: pdf %s unrecognized, must be gaussian, uniform,\n" "const, delta, checker\n", pdfname); exit(1); } if (tempid != NULL) { MRIcopyHeader(mritemp,mri); mri->type = MRI_FLOAT; // Override if(nframes > 0) mri->nframes = nframes; if(TR > 0) mri->tr = TR; } else { if(mri == NULL) { usage_exit(); } mri->xsize = res[0]; mri->ysize = res[1]; mri->zsize = res[2]; mri->tr = res[3]; mri->x_r = cdircos[0]; mri->x_a = cdircos[1]; mri->x_s = cdircos[2]; mri->y_r = rdircos[0]; mri->y_a = rdircos[1]; mri->y_s = rdircos[2]; mri->z_r = sdircos[0]; mri->z_a = sdircos[1]; mri->z_s = sdircos[2]; if(!usep0){ mri->c_r = cras[0]; mri->c_a = cras[1]; mri->c_s = cras[2]; } else MRIp0ToCRAS(mri, p0[0], p0[1], p0[2]); } if (gstd > 0) { if(!UseFFT){ printf("Smoothing\n"); MRIgaussianSmooth(mri, gstd, gmnnorm, mri); /* gmnnorm = 1 = normalize */ } else { printf("Smoothing with FFT \n"); mri2 = MRIcopy(mri,NULL); mri = MRI_fft_gaussian(mri2, mri, gstd, gmnnorm); /* gmnnorm = 1 = normalize */ } if (rescale) { printf("Rescaling\n"); if (strcmp(pdfname,"z")==0) RFrescale(mri,rfs,NULL,mri); if (strcmp(pdfname,"chi2")==0) RFrescale(mri,rfs,NULL,mri); if (strcmp(pdfname,"t")==0) RFrescale(mri,rfs,NULL,mri); if (strcmp(pdfname,"tr")==0) RFrescale(mri,rfs,NULL,mri); if (strcmp(pdfname,"F")==0) RFrescale(mri,rfs,NULL,mri); if (strcmp(pdfname,"Fr")==0) RFrescale(mri,rfs,NULL,mri); } } if(DoHSC){ // This multiplies each frame by a random number // between HSCMin HSCMax to simulate heteroscedastisity printf("Applying HSC %lf %lf\n",HSCMin,HSCMax); for(f=0; f < mri->nframes; f++){ rval = (HSCMax-HSCMin)*drand48() + HSCMin; if(debug) printf("%3d %lf\n",f,rval); for(c=0; c < mri->width; c ++){ for(r=0; r < mri->height; r ++){ for(s=0; s < mri->depth; s ++){ val = MRIgetVoxVal(mri,c,r,s,f); MRIsetVoxVal(mri,c,r,s,f,rval*val); } } } } } if(AddOffset) { printf("Adding offset\n"); offset = MRIread(tempid); if(offset == NULL) exit(1); if(OffsetFrame == -1) OffsetFrame = nint(offset->nframes/2); printf("Offset frame %d\n",OffsetFrame); mritmp = fMRIframe(offset, OffsetFrame, NULL); if(mritmp == NULL) exit(1); MRIfree(&offset); offset = mritmp; fMRIaddOffset(mri, offset, NULL, mri); } if(SpikeTP > 0){ printf("Spiking time point %d\n",SpikeTP); for(c=0; c < mri->width; c ++){ for(r=0; r < mri->height; r ++){ for(s=0; s < mri->depth; s ++){ MRIsetVoxVal(mri,c,r,s,SpikeTP,1e9); } } } } if(DoAbs){ printf("Computing absolute value\n"); MRIabs(mri,mri); } if(!NoOutput){ printf("Saving\n"); if(!DoCurv) MRIwriteAnyFormat(mri,volid,volfmt,-1,NULL); else { printf("Saving in curv format\n"); MRIScopyMRI(surf, mri, 0, "curv"); MRISwriteCurvature(surf,volid); } } if(sum2file){ val = MRIsum2All(mri); fp = fopen(sum2file,"w"); if(fp == NULL){ printf("ERROR: opening %s\n",sum2file); exit(1); } printf("sum2all: %20.10lf\n",val); printf("vrf: %20.10lf\n",1/val); fprintf(fp,"%20.10lf\n",val); } return(0); }
int main(int argc, char *argv[]) { char **av; MRI *mri_src, *mri_mask, *mri_dst ; int nargs, ac, nmask; int x, y, z; float value; MRI_REGION *region; LTA *lta = 0; int transform_type; MRI *mri_tmp; nargs = handle_version_option ( argc, argv, "$Id: mri_mask.c,v 1.18 2012/12/07 22:45:50 greve 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) { printf("Incorrect number of arguments, argc = %d\n", argc); usage(1); } mri_src = MRIread(argv[1]) ; if (!mri_src) ErrorExit(ERROR_BADPARM, "%s: could not read source volume %s", Progname, argv[1]) ; mri_mask = MRIread(argv[2]) ; if (!mri_mask) ErrorExit(ERROR_BADPARM, "%s: could not read mask volume %s", Progname, argv[2]) ; if(mri_src->width != mri_mask->width) { printf("ERROR: dimension mismatch between source and mask\n"); exit(1); } printf("DoAbs = %d\n",DoAbs); /* Read LTA transform and apply it to mri_mask */ if (xform_fname != NULL) { printf("Apply the given LTA xfrom to the mask volume\n"); // read transform transform_type = TransformFileNameType(xform_fname); if (transform_type == MNI_TRANSFORM_TYPE || transform_type == TRANSFORM_ARRAY_TYPE || transform_type == REGISTER_DAT || transform_type == FSLREG_TYPE ) { printf("Reading transform ...\n"); lta = LTAreadEx(xform_fname) ; if (!lta) ErrorExit(ERROR_NOFILE, "%s: could not read transform file %s", Progname, xform_fname) ; if (transform_type == FSLREG_TYPE) { if (lta_src == 0 || lta_dst == 0) { fprintf(stderr, "ERROR: fslmat does not have information on " "the src and dst volumes\n"); fprintf(stderr, "ERROR: you must give options '-lta_src' " "and '-lta_dst' to specify the src and dst volume infos\n"); } LTAmodifySrcDstGeom(lta, lta_src, lta_dst); // add src and dst information LTAchangeType(lta, LINEAR_VOX_TO_VOX); } if (lta->xforms[0].src.valid == 0) { if (lta_src == 0) { fprintf(stderr, "The transform does not have the valid src volume info.\n"); fprintf(stderr, "Either you give src volume info by option -lta_src or\n"); fprintf(stderr, "make the transform to have the valid src info.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, lta_src, NULL); // add src information // getVolGeom(lta_src, <->src); } } if (lta->xforms[0].dst.valid == 0) { if (lta_dst == 0) { fprintf(stderr, "The transform does not have the valid dst volume info.\n"); fprintf(stderr, "Either you give src volume info by option -lta_dst or\n"); fprintf(stderr, "make the transform to have the valid dst info.\n"); fprintf(stderr, "If the dst was average_305, then you can set\n"); fprintf(stderr, "environmental variable USE_AVERAGE305 true\n"); fprintf(stderr, "without giving the dst volume for RAS-to-RAS transform.\n"); ErrorExit(ERROR_BAD_PARM, "Bailing out...\n"); } else { LTAmodifySrcDstGeom(lta, NULL, lta_dst); // add dst information } } } else { ErrorExit(ERROR_BADPARM, "transform is not of MNI, nor Register.dat, nor FSLMAT type"); } if (invert) { VOL_GEOM vgtmp; LT *lt; MATRIX *m_tmp = lta->xforms[0].m_L ; lta->xforms[0].m_L = MatrixInverse(lta->xforms[0].m_L, NULL) ; MatrixFree(&m_tmp) ; lt = <a->xforms[0]; if (lt->dst.valid == 0 || lt->src.valid == 0) { fprintf(stderr, "WARNING:**************************************" "*************************\n"); fprintf(stderr, "WARNING:dst volume information is invalid. " "Most likely produced wrong inverse.\n"); fprintf(stderr, "WARNING:**************************************" "*************************\n"); } copyVolGeom(<->dst, &vgtmp); copyVolGeom(<->src, <->dst); copyVolGeom(&vgtmp, <->src); } // LTAchangeType(lta, LINEAR_VOX_TO_VOX); mri_tmp = MRIalloc(mri_src->width, mri_src->height, mri_src->depth, mri_mask->type) ; MRIcopyHeader(mri_src, mri_tmp) ; mri_tmp = LTAtransformInterp(mri_mask, mri_tmp, lta, InterpMethod); // mri_tmp = //MRIlinearTransformInterp // ( // mri_mask, mri_tmp, lta->xforms[0].m_L, InterpMethod // ); MRIfree(&mri_mask); mri_mask = mri_tmp; if (lta_src) { MRIfree(<a_src); } if (lta_dst) { MRIfree(<a_dst); } if (lta) { LTAfree(<a); } } /* if (xform_fname != NULL) */ // Threshold mask nmask = 0; for (z = 0 ; z <mri_mask->depth ; z++) { for (y = 0 ; y < mri_mask->height ; y++) { for (x = 0 ; x < mri_mask->width ; x++) { value = MRIgetVoxVal(mri_mask, x, y, z, 0); if(DoAbs) { value = fabs(value); } if(value <= threshold) { MRIsetVoxVal(mri_mask,x,y,z,0,0); } else { nmask ++; } } } } printf("Found %d voxels in mask (pct=%6.2f)\n",nmask, 100.0*nmask/(mri_mask->width*mri_mask->height*mri_mask->depth)); if(DoBB){ printf("Computing bounding box, npad = %d\n",nPadBB); region = REGIONgetBoundingBox(mri_mask,nPadBB); REGIONprint(stdout, region); mri_tmp = MRIextractRegion(mri_mask, NULL, region); if(mri_tmp == NULL) exit(1); MRIfree(&mri_mask); mri_mask = mri_tmp; mri_tmp = MRIextractRegion(mri_src, NULL, region); if(mri_tmp == NULL) exit(1); MRIfree(&mri_src); mri_src = mri_tmp; } int mask=0; float out_val=0; if (do_transfer) { mask = (int)transfer_val; out_val = transfer_val; } mri_dst = MRImask(mri_src, mri_mask, NULL, mask, out_val) ; if (!mri_dst) { ErrorExit(Gerror, "%s: stripping failed", Progname) ; } if (keep_mask_deletion_edits) { mri_dst = MRImask(mri_dst, mri_mask, NULL, 1, 1) ; // keep voxels = 1 if (!mri_dst) ErrorExit(Gerror, "%s: stripping failed on keep_mask_deletion_edits", Progname) ; } printf("Writing masked volume to %s...", argv[3]) ; MRIwrite(mri_dst, argv[3]); printf("done.\n") ; MRIfree(&mri_src); MRIfree(&mri_mask); MRIfree(&mri_dst); exit(0); } /* end main() */