// "readHeader()": read nifti header information from file nifti_1_header niftiManager::readHeader( const std::string& imageFilenameRef ) const { std::string imageFilenameZipped( imageFilenameRef ); std::string imageFilename( imageFilenameRef ); std::string extension( boost::filesystem::path(imageFilename).extension().string() ); if ( extension == ".gz" ) { imageFilename.resize(imageFilename.size()-3); // Variables for calling system commands std::string sysCommand( "gzip -dcf " + imageFilenameZipped + " > " + imageFilename ); int success(system(sysCommand.c_str())); } else if ( extension == getFileExtension( ETFull ) ) { } else { std::cerr << "File \"" << imageFilenameZipped << "\" has no recognized extension (\"" << extension << "\") stopping." << std::endl; exit(1); } nifti_image* niftiImage = NULL; boost::mutex& ioMutex(boost::detail::thread::singleton<boost::mutex>::instance()) ; ioMutex.lock(); { niftiImage = nifti_image_read(imageFilename.c_str(), 0); // load_data = 0, only header and not image data is read } ioMutex.unlock(); if( !niftiImage ) { std::stringstream errormessage; errormessage << "ERROR @ niftiManager::readHeader(): there was an error calling nifti_image_read() on image file "<< imageFilename <<std::endl; throw std::runtime_error( errormessage.str() ); } if( niftiImage->ndim > 3 ) { std::stringstream errormessage; errormessage << "ERROR @ niftiManager::readHeader(): nifti file has more than 3 dimensions (" << niftiImage->ndim <<"): "<< niftiImage->nx <<" "<< niftiImage->ny <<" "<< niftiImage->nz <<" "<< niftiImage->nt <<" "<< niftiImage->nu <<" "<< niftiImage->nv <<std::endl; throw std::runtime_error( errormessage.str() ); } nifti_1_header header = nifti_convert_nim2nhdr( niftiImage ); // clean up nifti_image_free( niftiImage ); if ( extension == ".gz" ) { // Variables for calling system commands std::string sysCommand( "rm -f " + imageFilename ); int success(system(sysCommand.c_str())); } return header; }// end niftiManager::readHeader() -----------------------------------------------------------------
void JNiftiImage::clear() { if (d->m_image) { nifti_image_unload(d->m_image); nifti_image_free(d->m_image); d->m_image=0; d->m_data_loaded=false; } }
int main(int argc, char *argv[]){ if(!argv[1]) { printf("\n./cutTree <Tree Name> <Nr. Cuts> <Mask Name> <Output Name>\n"); return 0; } printf("\nLoading the dendrogram ... \n"); FILE *treeFile = fopen(argv[1], "r"); int goodValues; fscanf(treeFile, "%i", &goodValues); Node *tree = malloc((goodValues-1)*sizeof(Node)); for(int i=0; i<goodValues-1; i++){ fscanf(treeFile, "%i %i %lf", &(tree[i].left), &(tree[i].right), &(tree[i].distance)); } fclose(treeFile); printf("\nCutting the dendrogram ...\n"); int * clusterid; int nr_clusters = atoi(argv[2]); clusterid = (int*)malloc(goodValues*sizeof(int)); cuttree (goodValues, tree, nr_clusters, clusterid); free(tree); printf("\nLoading mask template ... \n"); FSLIO *fslio; fslio = FslInit(); void *buffer = FslReadAllVolumes(fslio, argv[3]); double ***mask = FslGetVolumeAsScaledDouble(fslio, 0); FslClose(fslio); printf("\nSaving the image ...\n"); nifti_image *nim = nifti_image_read(argv[3], 1); int nx = nim->nx; int ny = nim->ny; int nz = nim->nz; short *pData = (short *)nim->data; int c = 0; int c2 = 0; for(int k=0;k<nz;k++) { for(int j=0;j<ny;j++) { for(int i=0;i<nx;i++) { if ( mask[k][j][i] != 0 ) { pData[c2] = clusterid[c]+1; c++; c2++; } else { pData[c2] = 0; c2++; } }}} nim->data = (short *)pData; int ret = nifti_set_filenames(nim, argv[4], 0, 1); nifti_image_write( nim ); nifti_image_free( nim ); free(clusterid); return 0; }
void FreeAllNiftiImages(nifti_image **niftiImages, int N) { for (int i = 0; i < N; i++) { if (niftiImages[i] != NULL) { nifti_image_free(niftiImages[i]); } } }
LoaderNifti::~LoaderNifti() { m_data.clear(); std::vector<float>().swap( m_data ); m_dataset.clear(); std::vector<Dataset*>().swap( m_dataset ); if ( m_header ) { nifti_image_free( m_header ); } }
void reg_f3d_gpu<T>::ClearWarped() { if(this->warped!=NULL){ NR_CUDA_SAFE_CALL(cudaFreeHost(this->warped->data)) this->warped->data = NULL; nifti_image_free(this->warped); this->warped=NULL; } if(this->warped_gpu!=NULL){ cudaCommon_free<float>(&this->warped_gpu); this->warped_gpu=NULL; } if(this->warped2_gpu!=NULL){ cudaCommon_free<float>(&this->warped2_gpu); this->warped2_gpu=NULL; } return; }
/************************** align multi-subjects, using a file containing a binary vector that indicates whether or not to use a voxel input: the raw matrix data structure array, the number of matrices (subjects), the binary vector file output: the remaining number of voxels, remove voxels from raw matrix and location ***************************/ int AlignMatricesByFile(RawMatrix** r_matrices, int nSubs, const char* file, Point* pts) { // align multi-subjects, remove all-zero voxels, assume that all subjects have the same number of voxels int row = r_matrices[0]->row; // originally is the total number of voxels x*y*z int i, j; int count=0; nifti_image* nim; nim = nifti_image_read(file, 1); // for inputting mask file short* data = NULL; switch (nim->datatype) // now only get one type { case DT_SIGNED_SHORT: data = (short*)nim->data; break; default: FATAL("wrong data type of mask file!"); } for (i=0; i<nSubs; i++) // remove the all-zero voxels { int col = r_matrices[i]->col; float* mat = r_matrices[i]->matrix; count = 0; for (j=0; j<row; j++) { if (data[j]) { memcpy(&(mat[count*col]), &(mat[j*col]), col*sizeof(float)); count++; } } r_matrices[i]->row = count; // update the row information } count = 0; for (j=0; j<row; j++) { if (data[j]) { memcpy(&(pts[count]), &(pts[j]), 3*sizeof(int)); count++; } } nifti_image_free(nim); return count; }
bool WriteNifti(nifti_image* inputNifti, float* data, const char* filename, bool addFilename, bool checkFilename) { char* filenameWithExtension; // Add the provided filename to the original filename, before the dot if (addFilename) { // Find the dot in the original filename const char* p = inputNifti->fname; int dotPosition = 0; while ( (p != NULL) && ((*p) != '.') ) { p++; dotPosition++; } // Allocate temporary array filenameWithExtension = (char*)malloc(strlen(inputNifti->fname) + strlen(filename) + 1); if (filenameWithExtension == NULL) { printf("Could not allocate temporary host memory! \n"); return false; } // Copy filename to the dot strncpy(filenameWithExtension,inputNifti->fname,dotPosition); filenameWithExtension[dotPosition] = '\0'; // Add the extension strcat(filenameWithExtension,filename); // Add the rest of the original filename strcat(filenameWithExtension,inputNifti->fname+dotPosition); } // Create new nifti image nifti_image *outputNifti = new nifti_image; // Copy information from input data outputNifti = nifti_copy_nim_info(inputNifti); // Set data pointer outputNifti->data = (void*)data; // Set data type to float outputNifti->datatype = DT_FLOAT; outputNifti->nbyper = 4; // Change filename and write bool written = false; if (addFilename) { if ( nifti_set_filenames(outputNifti, filenameWithExtension, checkFilename, 1) == 0) { nifti_image_write(outputNifti); written = true; } } else if (!addFilename) { if ( nifti_set_filenames(outputNifti, filename, checkFilename, 1) == 0) { nifti_image_write(outputNifti); written = true; } } outputNifti->data = NULL; nifti_image_free(outputNifti); if (addFilename) { free(filenameWithExtension); } if (written) { return true; } else { return false; } }
int main(int argc, char **argv) { //----------------------- // Input pointers float *h_Input_Volume; float *h_Displacement_Field_X, *h_Displacement_Field_Y, *h_Displacement_Field_Z; //----------------------- // Output pointers float *h_Interpolated_Volume; void *allMemoryPointers[500]; int numberOfMemoryPointers = 0; // Default parameters int OPENCL_PLATFORM = 0; int OPENCL_DEVICE = 0; bool DEBUG = false; bool PRINT = true; bool CHANGE_OUTPUT_NAME = false; const char* outputFilename; // Size parameters int INPUT_DATA_H, INPUT_DATA_W, INPUT_DATA_D; int REFERENCE_DATA_H, REFERENCE_DATA_W, REFERENCE_DATA_D; float INPUT_VOXEL_SIZE_X, INPUT_VOXEL_SIZE_Y, INPUT_VOXEL_SIZE_Z; float REFERENCE_VOXEL_SIZE_X, REFERENCE_VOXEL_SIZE_Y, REFERENCE_VOXEL_SIZE_Z; //--------------------- /* Input arguments */ FILE *fp = NULL; // No inputs, so print help text if (argc == 1) { printf("Transforms a volume using provided displacement fields, which have to be of the same size as the reference volume. The input volume is automagically resized and rescaled to match the input volume. \n\n"); printf("Usage:\n\n"); printf("TransformVolume volume_to_transform.nii reference_volume.nii displacement_field_x.nii displacement_field_y.nii displacement_field_z.nii [options]\n\n"); printf("Options:\n\n"); printf(" -platform The OpenCL platform to use (default 0) \n"); printf(" -device The OpenCL device to use for the specificed platform (default 0) \n"); printf(" -output Set output filename (default volume_to_transform_warped.nii) \n"); printf(" -quiet Don't print anything to the terminal (default false) \n"); printf("\n\n"); return 1; } else if (argc < 6) { printf("Need one volume to warp, one reference volume and three displacement field volumes!\n\n"); return -1; } // Try to open files else if (argc > 1) { fp = fopen(argv[1],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[1]); return -1; } fclose(fp); fp = fopen(argv[2],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[2]); return -1; } fclose(fp); fp = fopen(argv[3],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[3]); return -1; } fclose(fp); fp = fopen(argv[4],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[4]); return -1; } fclose(fp); fp = fopen(argv[5],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[5]); return -1; } fclose(fp); } // Loop over additional inputs int i = 6; while (i < argc) { char *input = argv[i]; char *p; if (strcmp(input,"-platform") == 0) { OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10); if (OPENCL_PLATFORM < 0) { printf("OpenCL platform must be >= 0!\n"); return -1; } i += 2; } else if (strcmp(input,"-device") == 0) { OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10); if (OPENCL_DEVICE < 0) { printf("OpenCL device must be >= 0!\n"); return -1; } i += 2; } else if (strcmp(input,"-quiet") == 0) { PRINT = false; i += 1; } else if (strcmp(input,"-output") == 0) { CHANGE_OUTPUT_NAME = true; outputFilename = argv[i+1]; i += 2; } else { printf("Unrecognized option! %s \n",argv[i]); return -1; } } // Read data nifti_image *inputVolume = nifti_image_read(argv[1],1); if (inputVolume == NULL) { printf("Could not open volume to transform!\n"); return -1; } nifti_image *referenceVolume = nifti_image_read(argv[2],1); if (referenceVolume == NULL) { printf("Could not open reference volume!\n"); return -1; } nifti_image *inputDisplacementX = nifti_image_read(argv[3],1); if (inputDisplacementX == NULL) { printf("Could not open displacement X volume!\n"); return -1; } nifti_image *inputDisplacementY = nifti_image_read(argv[4],1); if (inputDisplacementY == NULL) { printf("Could not open displacement Y volume!\n"); return -1; } nifti_image *inputDisplacementZ = nifti_image_read(argv[5],1); if (inputDisplacementZ == NULL) { printf("Could not open displacement Z volume!\n"); return -1; } // Get data dimensions from input data INPUT_DATA_W = inputVolume->nx; INPUT_DATA_H = inputVolume->ny; INPUT_DATA_D = inputVolume->nz; INPUT_VOXEL_SIZE_X = inputVolume->dx; INPUT_VOXEL_SIZE_Y = inputVolume->dy; INPUT_VOXEL_SIZE_Z = inputVolume->dz; REFERENCE_DATA_W = referenceVolume->nx; REFERENCE_DATA_H = referenceVolume->ny; REFERENCE_DATA_D = referenceVolume->nz; REFERENCE_VOXEL_SIZE_X = referenceVolume->dx; REFERENCE_VOXEL_SIZE_Y = referenceVolume->dy; REFERENCE_VOXEL_SIZE_Z = referenceVolume->dz; // Check if the displacement volumes have the same size int DISPLACEMENT_DATA_W, DISPLACEMENT_DATA_H, DISPLACEMENT_DATA_D; DISPLACEMENT_DATA_W = inputDisplacementX->nx; DISPLACEMENT_DATA_H = inputDisplacementX->ny; DISPLACEMENT_DATA_D = inputDisplacementX->nz; if ( (DISPLACEMENT_DATA_W != REFERENCE_DATA_W) || (DISPLACEMENT_DATA_H != REFERENCE_DATA_H) || (DISPLACEMENT_DATA_D != REFERENCE_DATA_D) ) { printf("Dimensions of displacement field x does not match the reference volume!\n"); return -1; } DISPLACEMENT_DATA_W = inputDisplacementY->nx; DISPLACEMENT_DATA_H = inputDisplacementY->ny; DISPLACEMENT_DATA_D = inputDisplacementY->nz; if ( (DISPLACEMENT_DATA_W != REFERENCE_DATA_W) || (DISPLACEMENT_DATA_H != REFERENCE_DATA_H) || (DISPLACEMENT_DATA_D != REFERENCE_DATA_D) ) { printf("Dimensions of displacement field y does not match the reference volume!\n"); return -1; } DISPLACEMENT_DATA_W = inputDisplacementZ->nx; DISPLACEMENT_DATA_H = inputDisplacementZ->ny; DISPLACEMENT_DATA_D = inputDisplacementZ->nz; if ( (DISPLACEMENT_DATA_W != REFERENCE_DATA_W) || (DISPLACEMENT_DATA_H != REFERENCE_DATA_H) || (DISPLACEMENT_DATA_D != REFERENCE_DATA_D) ) { printf("Dimensions of displacement field z does not match the reference volume!\n"); return -1; } // Calculate size, in bytes int INPUT_VOLUME_SIZE = INPUT_DATA_W * INPUT_DATA_H * INPUT_DATA_D * sizeof(float); int REFERENCE_VOLUME_SIZE = REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D * sizeof(float); // Print some info if (PRINT) { printf("Authored by K.A. Eklund \n"); printf("Input volume size: %i x %i x %i \n", INPUT_DATA_W, INPUT_DATA_H, INPUT_DATA_D); printf("Input volume voxel size: %f x %f x %f \n", INPUT_VOXEL_SIZE_X, INPUT_VOXEL_SIZE_Y, INPUT_VOXEL_SIZE_Z); printf("Reference volume size: %i x %i x %i \n", REFERENCE_DATA_W, REFERENCE_DATA_H, REFERENCE_DATA_D); printf("Reference volume voxel size: %f x %f x %f \n", REFERENCE_VOXEL_SIZE_X, REFERENCE_VOXEL_SIZE_Y, REFERENCE_VOXEL_SIZE_Z); } if (PRINT) { printf("Input volume size in bytes: %i \n", INPUT_VOLUME_SIZE); } // ------------------------------------------------ // Allocate memory on the host if (!AllocateMemory(h_Input_Volume, INPUT_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if (!AllocateMemory(h_Interpolated_Volume, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if (!AllocateMemory(h_Displacement_Field_X, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if (!AllocateMemory(h_Displacement_Field_Y, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if (!AllocateMemory(h_Displacement_Field_Z, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } // Convert data to floats if ( inputVolume->datatype == DT_SIGNED_SHORT ) { short int *p = (short int*)inputVolume->data; for (int i = 0; i < INPUT_DATA_W * INPUT_DATA_H * INPUT_DATA_D; i++) { h_Input_Volume[i] = (float)p[i]; } } else if ( inputVolume->datatype == DT_FLOAT ) { float *p = (float*)inputVolume->data; for (int i = 0; i < INPUT_DATA_W * INPUT_DATA_H * INPUT_DATA_D; i++) { h_Input_Volume[i] = p[i]; } } else { printf("Unknown data type in volume to transform, aborting!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if ( inputDisplacementX->datatype == DT_SIGNED_SHORT ) { short int *p = (short int*)inputDisplacementX->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_X[i] = (float)p[i]; } } else if ( inputDisplacementX->datatype == DT_FLOAT ) { float *p = (float*)inputDisplacementX->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_X[i] = p[i]; } } else { printf("Unknown data type in displacement x volume, aborting!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if ( inputDisplacementY->datatype == DT_SIGNED_SHORT ) { short int *p = (short int*)inputDisplacementY->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_Y[i] = (float)p[i]; } } else if ( inputDisplacementY->datatype == DT_FLOAT ) { float *p = (float*)inputDisplacementY->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_Y[i] = p[i]; } } else { printf("Unknown data type in displacement y volume, aborting!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } if ( inputDisplacementZ->datatype == DT_SIGNED_SHORT ) { short int *p = (short int*)inputDisplacementZ->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_Z[i] = (float)p[i]; } } else if ( inputDisplacementZ->datatype == DT_FLOAT ) { float *p = (float*)inputDisplacementZ->data; for (int i = 0; i < REFERENCE_DATA_W * REFERENCE_DATA_H * REFERENCE_DATA_D; i++) { h_Displacement_Field_Z[i] = p[i]; } } else { printf("Unknown data type in displacement z volume, aborting!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } //------------------------ BROCCOLI_LIB BROCCOLI(OPENCL_PLATFORM,OPENCL_DEVICE); // Something went wrong... if (BROCCOLI.GetOpenCLInitiated() == 0) { printf("Get platform IDs error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLPlatformIDsError())); printf("Get device IDs error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLDeviceIDsError())); printf("Create context error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLCreateContextError())); printf("Get create context info error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLContextInfoError())); printf("Create command queue error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLCreateCommandQueueError())); printf("Create program error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLCreateProgramError())); printf("Build program error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLBuildProgramError())); printf("Get program build info error is %s \n",BROCCOLI.GetOpenCLErrorMessage(BROCCOLI.GetOpenCLProgramBuildInfoError())); // Print create kernel errors int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (createKernelErrors[i] != 0) { printf("Create kernel error %i is %s \n",i,BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[i])); } } // Print build info to file fp = fopen("buildinfo.txt","w"); if (fp == NULL) { printf("Could not open buildinfo.txt! \n"); } if (BROCCOLI.GetOpenCLBuildInfoChar() != NULL) { int error = fputs(BROCCOLI.GetOpenCLBuildInfoChar(),fp); if (error == EOF) { printf("Could not write to buildinfo.txt! \n"); } } fclose(fp); printf("OpenCL initialization failed, aborting! \nSee buildinfo.txt for output of OpenCL compilation!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); return -1; } // Initialization OK else if (BROCCOLI.GetOpenCLInitiated() == 1) { // Set all necessary pointers and values BROCCOLI.SetInputT1Volume(h_Input_Volume); BROCCOLI.SetT1Width(INPUT_DATA_W); BROCCOLI.SetT1Height(INPUT_DATA_H); BROCCOLI.SetT1Depth(INPUT_DATA_D); BROCCOLI.SetT1VoxelSizeX(INPUT_VOXEL_SIZE_X); BROCCOLI.SetT1VoxelSizeY(INPUT_VOXEL_SIZE_Y); BROCCOLI.SetT1VoxelSizeZ(INPUT_VOXEL_SIZE_Z); BROCCOLI.SetMNIWidth(REFERENCE_DATA_W); BROCCOLI.SetMNIHeight(REFERENCE_DATA_H); BROCCOLI.SetMNIDepth(REFERENCE_DATA_D); BROCCOLI.SetMNIVoxelSizeX(REFERENCE_VOXEL_SIZE_X); BROCCOLI.SetMNIVoxelSizeY(REFERENCE_VOXEL_SIZE_Y); BROCCOLI.SetMNIVoxelSizeZ(REFERENCE_VOXEL_SIZE_Z); BROCCOLI.SetMMT1ZCUT(0); BROCCOLI.SetInterpolationMode(LINEAR); BROCCOLI.SetOutputDisplacementField(h_Displacement_Field_X,h_Displacement_Field_Y,h_Displacement_Field_Z); BROCCOLI.SetOutputInterpolatedT1Volume(h_Interpolated_Volume); if (DEBUG) { BROCCOLI.SetDebug(true); } for (int i = 0; i < numberOfMemoryPointers; i++) { printf("Pointer i is %i \n",allMemoryPointers[i]); } // Run the actual transformation BROCCOLI.TransformVolumesNonParametricWrapper(); for (int i = 0; i < numberOfMemoryPointers; i++) { printf("Pointer i is %i \n",allMemoryPointers[i]); } // Print create buffer errors int* createBufferErrors = BROCCOLI.GetOpenCLCreateBufferErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (createBufferErrors[i] != 0) { printf("Create buffer error %i is %s \n",i,BROCCOLI.GetOpenCLErrorMessage(createBufferErrors[i])); } } // Print run kernel errors int* runKernelErrors = BROCCOLI.GetOpenCLRunKernelErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (runKernelErrors[i] != 0) { printf("Run kernel error %i is %s \n",i,BROCCOLI.GetOpenCLErrorMessage(runKernelErrors[i])); } } } // Create new nifti image nifti_image *outputNifti = new nifti_image; // Copy information from input data outputNifti = nifti_copy_nim_info(referenceVolume); // Change filename if (!CHANGE_OUTPUT_NAME) { nifti_set_filenames(outputNifti, inputVolume->fname, 0, 1); // Write transformed data to file WriteNifti(outputNifti,h_Interpolated_Volume,"_warped",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); //nifti_set_filenames(outputNifti, "warped.nii", 0, 1); //WriteNifti(outputNifti,h_Interpolated_Volume,"",DONT_ADD_FILENAME,DONT_CHECK_EXISTING_FILE); } else { //nifti_set_filenames(outputNifti, outputFilename, 0, 1); // Write transformed data to file //WriteNifti(outputNifti,h_Interpolated_Volume,"",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); } // Free all memory FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputVolume); nifti_image_free(referenceVolume); nifti_image_free(inputDisplacementX); nifti_image_free(inputDisplacementY); nifti_image_free(inputDisplacementZ); nifti_image_free(outputNifti); return 1; }
// "readImage()": reads a 3D image ValueType niftiManager::readImage( const std::string& imageFilenameRef, std::vector<std::vector<std::vector<float> > >* imagePointer ) const { std::vector<std::vector<std::vector<float> > >& image( *imagePointer ); std::string imageFilename( imageFilenameRef ); std::string imageFilenameZipped( imageFilenameRef ); std::string extension( boost::filesystem::path(imageFilename).extension().string() ); if ( extension == ".gz" ) { imageFilename.resize(imageFilename.size()-3); // Variables for calling system commands std::string sysCommand( "gzip -dcf " + imageFilenameZipped + " > " + imageFilename ); int success(system(sysCommand.c_str())); } else if ( extension == getFileExtension( ETFull ) ) { } else { std::cerr << "File \"" << imageFilenameZipped << "\" has no recognized extension (\"" << extension << "\") stopping." << std::endl; return VTError; } nifti_image* niftiImage = NULL; boost::mutex& ioMutex(boost::detail::thread::singleton<boost::mutex>::instance()) ; ioMutex.lock(); { niftiImage = nifti_image_read(imageFilename.c_str(), 1); } ioMutex.unlock(); if( !niftiImage ) { std::cerr<< "ERROR @ niftiManager::readImage(): there was an error calling nifti_image_read() on image file "<< imageFilename <<std::endl; return VTError; } if( niftiImage->ndim > 3 ) { std::cerr << "ERROR @ niftiManager::readImage(): nifti file has more than 3 dimensions (" << niftiImage->ndim <<"): "<< niftiImage->nx <<" "<< niftiImage->ny <<" "<< niftiImage->nz <<" "<< niftiImage->nt <<" "<< niftiImage->nu <<" "<< niftiImage->nv <<std::endl; return VTError; } const size_t repType( niftiImage->datatype ); const size_t repByteSize( niftiImage->nbyper ); const size_t dataSize( niftiImage->nvox ); ValueType imageValueType; if(repType == DT_UINT8 ) { imageValueType = VTUINT8; } else if(repType == DT_FLOAT32 ) { imageValueType = VTFloat32; } else { std::cerr<< "ERROR @ niftiManager::readImage(): image representation type not recognized (neither UINT8 nor FLOAT32)" << std::endl; return VTError; } const size_t dimx( niftiImage->nx ); const size_t dimy( niftiImage->ny ); const size_t dimz( niftiImage->nz); image.clear(); { std::vector<float> zvector(dimz,0); std::vector<std::vector<float> >yzmatrix(dimy,zvector); image.resize(dimx,yzmatrix); } void* niftiData(niftiImage->data); for (int i=0 ; i<dimz ; ++i) { for (int j=0 ; j<dimy ; ++j) { for (int k=0 ; k<dimx ; ++k) { size_t voxOffset( (i*dimy*dimx) + (j*dimx) + k ); if( voxOffset >= dataSize ) { std::cerr<< "ERROR @ niftiManager::readImage():: pointer offset was too high when loading nifti data" << std::endl; return VTError; } size_t byteOffset( voxOffset * repByteSize ); void* dataPos = static_cast<unsigned char*>(niftiData) + byteOffset; if (repType == DT_UINT8) { unsigned char datapoint = *(static_cast<unsigned char*>(dataPos)); image[k][j][i] = (float)datapoint; } else if (repType == DT_FLOAT32) { float datapoint = *(static_cast<float*>(dataPos)); image[k][j][i] = datapoint; } else { std::cerr<< "ERROR @ niftiManager::readImage(): image representation type not recognized (neither UINT8 nor FLOAT32)" << std::endl; return VTError; } } } } // clean up nifti_image_free( niftiImage ); if ( extension == ".gz" ) { // Variables for calling system commands std::string sysCommand( "rm -f " + imageFilename ); int success(system(sysCommand.c_str())); } return imageValueType; }// end niftiManager::readImage() -----------------------------------------------------------------
int main(int argc, char **argv) { PARAM *param = (PARAM *)calloc(1,sizeof(PARAM)); FLAG *flag = (FLAG *)calloc(1,sizeof(FLAG)); /* read the input parameter */ for(int i=1;i<argc;i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0 || strcmp(argv[i], "--help")==0){ Usage(argv[0]); return 0; } else if(strcmp(argv[i], "--xml")==0){ printf("%s",xml_transform); return 0; } #ifdef _SVN_REV if(strcmp(argv[i], "-version")==0 || strcmp(argv[i], "-Version")==0 || strcmp(argv[i], "-V")==0 || strcmp(argv[i], "-v")==0 || strcmp(argv[i], "--v")==0 || strcmp(argv[i], "--version")==0){ printf("NiftyReg revision number: %i\n",_SVN_REV); return 0; } #endif else if((strcmp(argv[i],"-ref")==0) || (strcmp(argv[i],"-target")==0)){ param->referenceImageName=argv[++i]; flag->referenceImageFlag=1; } else if(strcmp(argv[i], "-comp1") == 0){ param->inputSecondCPPName=argv[++i]; param->inputFirstCPPName=argv[++i]; param->outputDeformationName=argv[++i]; flag->composeTransformation1Flag=1; } else if(strcmp(argv[i], "-comp2") == 0){ param->inputSecondCPPName=argv[++i]; param->inputDeformationName=argv[++i]; param->outputDeformationName=argv[++i]; flag->composeTransformation2Flag=1; } else if(strcmp(argv[i], "-comp3") == 0){ param->inputSeconDefName=argv[++i]; param->inputDeformationName=argv[++i]; param->outputDeformationName=argv[++i]; flag->composeTransformation3Flag=1; } else if(strcmp(argv[i], "-def2disp") == 0){ param->inputDeformationName=argv[++i]; param->outputDisplacementName=argv[++i]; flag->def2dispFlag=1; } else if(strcmp(argv[i], "-disp2def") == 0){ param->inputDisplacementName=argv[++i]; param->outputDeformationName=argv[++i]; flag->disp2defFlag=1; } else if(strcmp(argv[i], "-updSform") == 0){ param->inputSourceImageName=argv[++i]; param->inputAffineName=argv[++i]; param->outputSourceImageName=argv[++i]; flag->updateSformFlag=1; } else if(strcmp(argv[i], "-aff2def") == 0){ param->inputAffineName=argv[++i]; param->sourceImageName=argv[++i]; param->inputFirstCPPName=argv[++i]; param->outputDeformationName=argv[++i]; flag->aff2defFlag=1; } else if(strcmp(argv[i], "-invAffine") == 0){ param->inputAffineName=argv[++i]; param->outputAffineName=argv[++i]; flag->invertAffineFlag=1; } else if(strcmp(argv[i], "-invDef") == 0){ param->inputDeformationName=argv[++i]; param->sourceImageName=argv[++i]; param->outputDeformationName=argv[++i]; flag->invertDefFlag=1; } else if(strcmp(argv[i], "-cpp2def") == 0){ param->cpp2defInputName=argv[++i]; param->cpp2defOutputName=argv[++i]; flag->cpp2defFlag=1; } else if(strcmp(argv[i], "-compAff") == 0){ param->inputAffineName=argv[++i]; param->inputAffineName2=argv[++i]; param->outputAffineName=argv[++i]; flag->composeAffineFlag=1; } else if(strcmp(argv[i], "-tps2cpp") == 0){ param->tpsTextFilename=argv[++i]; param->CPPSpacing=(float)atof(argv[++i]); param->ApproxTPSWeight=(float)atof(argv[++i]); param->outputCPPName=argv[++i]; flag->tps2cppFlag=1; } else if(strcmp(argv[i], "-tps2def") == 0){ param->tpsTextFilename=argv[++i]; param->ApproxTPSWeight=(float)atof(argv[++i]); param->outputDeformationName=argv[++i]; flag->tps2defFlag=1; } else{ fprintf(stderr,"Err:\tParameter %s unknown.\n",argv[i]); PetitUsage(argv[0]); return 1; } } if(!flag->referenceImageFlag){ fprintf(stderr,"Err:\tThe reference image has to be defined.\n"); PetitUsage(argv[0]); return 1; } /* Read the reference image */ nifti_image *referenceImage = reg_io_ReadImageHeader(param->referenceImageName); if(referenceImage == NULL){ fprintf(stderr,"[NiftyReg ERROR] Error when reading the reference image: %s\n",param->referenceImageName); PetitUsage(argv[0]); return 1; } reg_checkAndCorrectDimension(referenceImage); /* ************************************************ */ /* INITIALISE A CPP DEF DEF FROM LANDMARKS WITH TPS */ /* ************************************************ */ if(flag->tps2cppFlag || flag->tps2defFlag){ // Read the text file that contains the landmark coordinates std::vector<PrecisionTYPE> values; std::ifstream infile(param->tpsTextFilename); if(!infile){ fprintf(stderr,"[ERROR] Can not open the file %s\n", param->tpsTextFilename); exit(1); } PrecisionTYPE val; while(!infile.eof()){ infile >> val; values.push_back(val); } infile.close(); size_t landmarkNumber=0; if(referenceImage->ndim==2) landmarkNumber=values.size()/4; else if(referenceImage->ndim==3) landmarkNumber=values.size()/6; else{ fprintf(stderr,"[ERROR] The reference image is expected to be of dimension 2 or 3\n"); exit(1); } printf("[NiftyReg] Landmark number %i\n", (int)landmarkNumber); PrecisionTYPE *px=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); PrecisionTYPE *py=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); PrecisionTYPE *cx=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); PrecisionTYPE *cy=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); PrecisionTYPE *pz=NULL; PrecisionTYPE *cz=NULL; if(referenceImage->ndim==3){ pz=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); cz=(PrecisionTYPE *)malloc(landmarkNumber*sizeof(PrecisionTYPE)); } size_t i=0, l=0; while(l<landmarkNumber){ px[l]=values[i];++i; py[l]=values[i];++i; if(referenceImage->ndim==3){pz[l]=values[i];++i;} cx[l]=values[i]-px[l];++i; cy[l]=values[i]-py[l];++i; if(referenceImage->ndim==3){cz[l]=values[i]-pz[l];++i;} ++l; } // Create the TPS object reg_tps<PrecisionTYPE> *tps = new reg_tps<PrecisionTYPE>(referenceImage->dim[0],landmarkNumber); tps->SetAproxInter(param->ApproxTPSWeight); // Set the landmark initial and final positions if(referenceImage->ndim==3) tps->SetPosition(px,py,pz,cx,cy,cz); else if(referenceImage->ndim==2) tps->SetPosition(px,py,cx,cy); free(cx);free(cy);free(px);free(py); if(referenceImage->ndim==3){ free(cz);free(pz); } // Compute the coefficients tps->InitialiseTPS(); nifti_image *outputImage=NULL; if(flag->tps2cppFlag){ // Compute the cpp dimension float gridSpacing[3]={param->CPPSpacing,param->CPPSpacing,param->CPPSpacing}; if(gridSpacing[0]<0) gridSpacing[0] *= -1.0f * referenceImage->dx; if(gridSpacing[1]<0) gridSpacing[1] *= -1.0f * referenceImage->dy; if(referenceImage->nz>1) if(gridSpacing[2]<0) gridSpacing[2] *= -1.0f * referenceImage->dz; // Create and allocate the cpp image reg_createControlPointGrid<PrecisionTYPE>(&outputImage, referenceImage, gridSpacing); nifti_set_filenames(outputImage,param->outputCPPName,0,0); } else{ // Creation of the deformation field image outputImage=nifti_copy_nim_info(referenceImage); outputImage->nbyper=sizeof(PrecisionTYPE); if(sizeof(PrecisionTYPE)==sizeof(float)) outputImage->datatype=NIFTI_TYPE_FLOAT32; else outputImage->datatype=NIFTI_TYPE_FLOAT64; outputImage->ndim=outputImage->dim[0]=5; outputImage->nt=outputImage->dim[4]=1; if(referenceImage->nz>1) outputImage->nu=outputImage->dim[5]=3; else outputImage->nu=outputImage->dim[5]=2; outputImage->nvox=outputImage->nx* outputImage->ny * outputImage->nz * outputImage->nt * outputImage->nu; // allocate the deformation field data array outputImage->data=(void *)malloc(outputImage->nvox*outputImage->nbyper); } tps->FillDeformationField(outputImage); reg_io_WriteImageFile(outputImage,param->outputDeformationName); nifti_image_free(outputImage); delete tps; }
int main(int argc, char **argv) { if(strcmp(argv[1], "--xml")==0){ printf("%s",xml_average); return 0; } if(argc<3){ usage(argv[0]); return EXIT_SUCCESS; } //Check the name of the first file to verify if they are analyse or nifti image std::string n(argv[2]); if( n.find( ".nii.gz") != std::string::npos || n.find( ".nii") != std::string::npos || n.find( ".hdr") != std::string::npos || n.find( ".img") != std::string::npos || n.find( ".img.gz") != std::string::npos) { // Input arguments are image filename // Read the first image to average nifti_image *tempImage=reg_io_ReadImageHeader(argv[2]); if(tempImage==NULL){ fprintf(stderr, "The following image can not be read: %s\n", argv[2]); return EXIT_FAILURE; } reg_checkAndCorrectDimension(tempImage); // Create the average image nifti_image *average_image=nifti_copy_nim_info(tempImage); nifti_image_free(tempImage);tempImage=NULL; average_image->datatype=NIFTI_TYPE_FLOAT32; if(sizeof(PrecisionTYPE)==sizeof(double)) average_image->datatype=NIFTI_TYPE_FLOAT64; average_image->nbyper=sizeof(PrecisionTYPE); average_image->data=(void *)malloc(average_image->nvox*average_image->nbyper); reg_tools_addSubMulDivValue(average_image,average_image,0.f,2); int imageTotalNumber=0; for(int i=2;i<argc;++i){ nifti_image *tempImage=reg_io_ReadImageFile(argv[i]); if(tempImage==NULL){ fprintf(stderr, "[!] The following image can not be read: %s\n", argv[i]); return EXIT_FAILURE; } reg_checkAndCorrectDimension(tempImage); if(average_image->nvox!=tempImage->nvox){ fprintf(stderr, "[!] All images must have the same size. Error when processing: %s\n", argv[i]); return EXIT_FAILURE; } reg_tools_addSubMulDivImages(average_image,tempImage,average_image,0); imageTotalNumber++; nifti_image_free(tempImage);tempImage=NULL; } reg_tools_addSubMulDivValue(average_image,average_image,(float)imageTotalNumber,3); reg_io_WriteImageFile(average_image,argv[1]); nifti_image_free(average_image); } else{ // input arguments are assumed to be text file name // Create an mat44 array to store all input matrices const size_t matrixNumber=argc-2; mat44 *inputMatrices=(mat44 *)malloc(matrixNumber * sizeof(mat44)); // Read all the input matrices for(size_t m=0;m<matrixNumber;++m){ if(FILE *aff=fopen(argv[m+2], "r")){ fclose(aff); } else{ fprintf(stderr,"The specified input affine file (%s) can not be read\n",argv[m+2]); exit(1); } // Read the current matrix file std::ifstream affineFile; affineFile.open(argv[m+2]); if(affineFile.is_open()){ // Transfer the values into the mat44 array int i=0; float value1,value2,value3,value4; while(!affineFile.eof()){ affineFile >> value1 >> value2 >> value3 >> value4; inputMatrices[m].m[i][0] = value1; inputMatrices[m].m[i][1] = value2; inputMatrices[m].m[i][2] = value3; inputMatrices[m].m[i][3] = value4; i++; if(i>3) break; } } affineFile.close(); } // All the input matrices are log-ed for(size_t m=0;m<matrixNumber;++m){ inputMatrices[m] = reg_mat44_logm(&inputMatrices[m]); } // All the exponentiated matrices are summed up into one matrix //temporary double are used to avoid error accumulation double tempValue[16]={0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; for(size_t m=0;m<matrixNumber;++m){ tempValue[0]+= (double)inputMatrices[m].m[0][0]; tempValue[1]+= (double)inputMatrices[m].m[0][1]; tempValue[2]+= (double)inputMatrices[m].m[0][2]; tempValue[3]+= (double)inputMatrices[m].m[0][3]; tempValue[4]+= (double)inputMatrices[m].m[1][0]; tempValue[5]+= (double)inputMatrices[m].m[1][1]; tempValue[6]+= (double)inputMatrices[m].m[1][2]; tempValue[7]+= (double)inputMatrices[m].m[1][3]; tempValue[8]+= (double)inputMatrices[m].m[2][0]; tempValue[9]+= (double)inputMatrices[m].m[2][1]; tempValue[10]+=(double)inputMatrices[m].m[2][2]; tempValue[11]+=(double)inputMatrices[m].m[2][3]; tempValue[12]+=(double)inputMatrices[m].m[3][0]; tempValue[13]+=(double)inputMatrices[m].m[3][1]; tempValue[14]+=(double)inputMatrices[m].m[3][2]; tempValue[15]+=(double)inputMatrices[m].m[3][3]; } // Average matrix is computed tempValue[0] /= (double)matrixNumber; tempValue[1] /= (double)matrixNumber; tempValue[2] /= (double)matrixNumber; tempValue[3] /= (double)matrixNumber; tempValue[4] /= (double)matrixNumber; tempValue[5] /= (double)matrixNumber; tempValue[6] /= (double)matrixNumber; tempValue[7] /= (double)matrixNumber; tempValue[8] /= (double)matrixNumber; tempValue[9] /= (double)matrixNumber; tempValue[10]/= (double)matrixNumber; tempValue[11]/= (double)matrixNumber; tempValue[12]/= (double)matrixNumber; tempValue[13]/= (double)matrixNumber; tempValue[14]/= (double)matrixNumber; tempValue[15]/= (double)matrixNumber; // The final matrix is exponentiated mat44 outputMatrix; outputMatrix.m[0][0]=(float)tempValue[0]; outputMatrix.m[0][1]=(float)tempValue[1]; outputMatrix.m[0][2]=(float)tempValue[2]; outputMatrix.m[0][3]=(float)tempValue[3]; outputMatrix.m[1][0]=(float)tempValue[4]; outputMatrix.m[1][1]=(float)tempValue[5]; outputMatrix.m[1][2]=(float)tempValue[6]; outputMatrix.m[1][3]=(float)tempValue[7]; outputMatrix.m[2][0]=(float)tempValue[8]; outputMatrix.m[2][1]=(float)tempValue[9]; outputMatrix.m[2][2]=(float)tempValue[10]; outputMatrix.m[2][3]=(float)tempValue[11]; outputMatrix.m[3][0]=(float)tempValue[12]; outputMatrix.m[3][1]=(float)tempValue[13]; outputMatrix.m[3][2]=(float)tempValue[14]; outputMatrix.m[3][3]=(float)tempValue[15]; outputMatrix = reg_mat44_expm(&outputMatrix); // Free the array containing the input matrices free(inputMatrices); // The final matrix is saved reg_tool_WriteAffineFile(&outputMatrix,argv[1]); }
// "writeImage()": writes a 3D image void niftiManager::writeImage( const std::string& imageFilename, const ValueType dataValueType, const std::vector<std::vector<std::vector<float> > >& image, bool doZip ) const { if (image.empty()) { std::cerr<< "ERROR @ niftiManager::writeImage(): image matrix is empty, image has not been written" <<std::endl; return; } const size_t dimx = image.size(); const size_t dimy = image[0].size(); const size_t dimz = image[0][0].size(); nifti_1_header imageHeader; imageHeader.sizeof_hdr = 0; if(m_header.sizeof_hdr != 0) { imageHeader = m_header; } generateHeader( dimx, dimy, dimz, dataValueType, &imageHeader); nifti_image* niftiImage = nifti_convert_nhdr2nim( imageHeader, NULL); const size_t repByteSize( niftiImage->nbyper ); const size_t dataSize( niftiImage->nvox ); const size_t repType( niftiImage->datatype ); if ( dataSize != (dimx*dimy*dimz) ) { throw std::runtime_error( "niftiManager::writeImage(): image header nvox and matrix size do not match" ); } if ( repType != imageHeader.datatype ) { throw std::runtime_error( "niftiManager::writeImage(): created header datatype and input argument dont match" ); } if(niftiImage->data != NULL) { throw std::runtime_error( "niftiManager::writeVector(): nifti_convert_nhdr2nim had already allocated memory" ); } niftiImage->data = malloc (dataSize * repByteSize); for (int i=0 ; i<dimz ; ++i) { for (int j=0 ; j<dimy ; ++j) { for (int k=0 ; k<dimx ; ++k) { size_t voxOffset( (i*dimy*dimx) + (j*dimx) + k ); if( voxOffset >= dataSize ) { throw std::runtime_error( "ERROR @ niftiManager::writeImage():: pointer offset was too high when loading nifti data"); } size_t byteOffset( voxOffset * repByteSize ); void* dataPos = static_cast<unsigned char*>(niftiImage->data) + byteOffset; if (repType == DT_UINT8) { unsigned char datapoint = (unsigned char)image[k][j][i]; *(static_cast<unsigned char*>(dataPos)) = datapoint; } else if (repType == DT_FLOAT32) { float datapoint = image[k][j][i]; *(static_cast<float*>(dataPos)) = datapoint; } else { throw std::runtime_error("ERROR @ niftiManager::writeImage(): image representation type not recognized (neither UINT8 nor FLOAT32)"); } } } } if( nifti_set_filenames(niftiImage, imageFilename.c_str(), 0, 1) ) { std::stringstream errormessage; errormessage << "ERROR @ niftiManager::writeImage(): there was an error calling nifti_set_filenames() on output image file "<< imageFilename <<std::endl; throw std::runtime_error( errormessage.str() ); } boost::mutex& ioMutex(boost::detail::thread::singleton<boost::mutex>::instance()) ; ioMutex.lock(); { nifti_image_write( niftiImage ); } ioMutex.unlock(); // clean up nifti_image_free( niftiImage ); if (doZip) { // zip file // Variables for calling system commands std::string gzipString("gzip -f "); std::string sysCommand(gzipString + imageFilename); int success(system(sysCommand.c_str())); } return; }// end niftiManager::writeImage() -----------------------------------------------------------------
int main(int argc, char * argv[]) { nifti_image * nim = NULL; char * fin = NULL; char * fout = NULL; long seed = -1; int ac = 0; if( argc < 2 ){ return show_help(); } /* Process command line arguments */ for( ac = 1; ac < argc; ac++ ){ if( !strncmp(argv[ac], "-h", 2) ){ return show_help(); } else if( !strncmp(argv[ac], "-in", 3) ){ if( ++ac >= argc ){ fprintf(stderr, "** missing argument for -input\n"); return 1; } fin = argv[ac]; /* no string copy, just pointer assignment */ } else if( !strncmp(argv[ac], "-out", 4) ){ if( ++ac >= argc ){ fprintf(stderr, "** missing argument for -output\n"); return 1; } fout = argv[ac]; } else if( !strncmp(argv[ac], "-v", 2) ){ if( ++ac >= argc ){ fprintf(stderr, "** missing argument for -verb\n"); return 1; } nifti_set_debug_level(atoi(argv[ac])); } else if( !strncmp(argv[ac], "-s", 2) ){ if( ++ac >= argc ){ fprintf(stderr, "** missing argument for -seed\n"); return 1; } seed = atol(argv[ac]); } else{ fprintf(stderr,"** invalid option, '%s'\n", argv[ac]); return 1; } } printf("Results from the parsing:\n"); printf("%10s","FILE_IN:"); printf(" %-30s\n",fin); printf("%10s","FILE_OUT:"); printf(" %-30s\n",fout); printf("%10s","INDEX:"); printf(" %-30ld\n",seed); if( !fin ) {fprintf(stderr, "** missing option '-input'\n"); return 1;} if( !fout ) {fprintf(stderr, "** missing option '-output'\n"); return 1;} if( seed < 0 ){fprintf(stderr, "** missing option '-seed'\n"); return 1;} /* read input dataset */ nim = nifti_image_read(fin, 1); if ( !nim ){ fprintf(stderr, "** failed to read NIFTI image from '%s'", fin); return 1; } calculate_edgerr(nim, seed); /* memory clean up */ nifti_image_free( nim ); return 0; }
int main(int argc, char **argv) { PARAM *param = (PARAM *)calloc(1,sizeof(PARAM)); FLAG *flag = (FLAG *)calloc(1,sizeof(FLAG)); flag->operationTypeFlag=-1; /* read the input parameter */ for(int i=1;i<argc;i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0 || strcmp(argv[i], "--help")==0){ Usage(argv[0]); return 0; } else if(strcmp(argv[i], "--xml")==0){ printf("%s",xml_tools); return 0; } #ifdef _SVN_REV if(strcmp(argv[i], "-version")==0 || strcmp(argv[i], "-Version")==0 || strcmp(argv[i], "-V")==0 || strcmp(argv[i], "-v")==0 || strcmp(argv[i], "--v")==0 || strcmp(argv[i], "--version")==0){ printf("NiftyReg revision number: %i\n",_SVN_REV); return 0; } #endif else if(strcmp(argv[i], "-in") == 0){ param->inputImageName=argv[++i]; flag->inputImageFlag=1; } else if(strcmp(argv[i], "-out") == 0){ param->outputImageName=argv[++i]; flag->outputImageFlag=1; } else if(strcmp(argv[i], "-add") == 0){ param->operationImageName=argv[++i]; if(isNumeric(param->operationImageName)==true){ param->operationValue=(float)atof(param->operationImageName); param->operationImageName=NULL; } flag->operationTypeFlag=0; } else if(strcmp(argv[i], "-sub") == 0){ param->operationImageName=argv[++i]; if(isNumeric(param->operationImageName)){ param->operationValue=(float)atof(param->operationImageName); param->operationImageName=NULL; } flag->operationTypeFlag=1; } else if(strcmp(argv[i], "-mul") == 0){ param->operationImageName=argv[++i]; if(isNumeric(param->operationImageName)){ param->operationValue=(float)atof(param->operationImageName); param->operationImageName=NULL; } flag->operationTypeFlag=2; } else if(strcmp(argv[i], "-div") == 0){ param->operationImageName=argv[++i]; if(isNumeric(param->operationImageName)){ param->operationValue=(float)atof(param->operationImageName); param->operationImageName=NULL; } flag->operationTypeFlag=3; } else if(strcmp(argv[i], "-rms") == 0){ param->rmsImageName=argv[++i]; flag->rmsImageFlag=1; } else if(strcmp(argv[i], "-smo") == 0){ param->smoothValue=atof(argv[++i]); flag->smoothValueFlag=1; } else if(strcmp(argv[i], "-smoG") == 0){ param->smoothValueX=atof(argv[++i]); param->smoothValueY=atof(argv[++i]); param->smoothValueZ=atof(argv[++i]); flag->smoothGaussianFlag=1; } else if(strcmp(argv[i], "-bin") == 0){ flag->binarisedImageFlag=1; } else if(strcmp(argv[i], "-thr") == 0){ param->thresholdImageValue=atof(argv[++i]); flag->thresholdImageFlag=1; } else if(strcmp(argv[i], "-nan") == 0){ param->operationImageName=argv[++i]; flag->nanMaskFlag=1; } else{ fprintf(stderr,"Err:\tParameter %s unknown.\n",argv[i]); PetitUsage(argv[0]); return 1; } } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// /* Read the image */ nifti_image *image = reg_io_ReadImageFile(param->inputImageName); if(image == NULL){ fprintf(stderr,"** ERROR Error when reading the target image: %s\n",param->inputImageName); return 1; } reg_checkAndCorrectDimension(image); //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->smoothValueFlag){ nifti_image *smoothImg = nifti_copy_nim_info(image); smoothImg->data = (void *)malloc(smoothImg->nvox * smoothImg->nbyper); memcpy(smoothImg->data, image->data, smoothImg->nvox*smoothImg->nbyper); int radius[3];radius[0]=radius[1]=radius[2]=param->smoothValue; reg_smoothNormImageForCubicSpline<PrecisionTYPE>(smoothImg, radius); if(flag->outputImageFlag) reg_io_WriteImageFile(smoothImg, param->outputImageName); else reg_io_WriteImageFile(smoothImg, "output.nii"); nifti_image_free(smoothImg); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->smoothGaussianFlag){ nifti_image *smoothImg = nifti_copy_nim_info(image); smoothImg->data = (void *)malloc(smoothImg->nvox * smoothImg->nbyper); memcpy(smoothImg->data, image->data, smoothImg->nvox*smoothImg->nbyper); bool boolX[8]={3,1,0,0,0,0,0,0}; reg_gaussianSmoothing(smoothImg,param->smoothValueX,boolX); bool boolY[8]={3,0,1,0,0,0,0,0}; reg_gaussianSmoothing(smoothImg,param->smoothValueY,boolY); bool boolZ[8]={3,0,0,1,0,0,0,0}; reg_gaussianSmoothing(smoothImg,param->smoothValueZ,boolZ); if(flag->outputImageFlag) reg_io_WriteImageFile(smoothImg, param->outputImageName); else reg_io_WriteImageFile(smoothImg, "output.nii"); nifti_image_free(smoothImg); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->operationTypeFlag>-1){ nifti_image *image2=NULL; if(param->operationImageName!=NULL){ image2 = reg_io_ReadImageFile(param->operationImageName); if(image2 == NULL){ fprintf(stderr,"** ERROR Error when reading the image: %s\n",param->operationImageName); return 1; } reg_checkAndCorrectDimension(image2); } nifti_image *resultImage = nifti_copy_nim_info(image); resultImage->data = (void *)malloc(resultImage->nvox * resultImage->nbyper); if(image2!=NULL) reg_tools_addSubMulDivImages(image, image2, resultImage, flag->operationTypeFlag); else reg_tools_addSubMulDivValue(image, resultImage, param->operationValue, flag->operationTypeFlag); if(flag->outputImageFlag) reg_io_WriteImageFile(resultImage,param->outputImageName); else reg_io_WriteImageFile(resultImage,"output.nii"); nifti_image_free(resultImage); if(image2!=NULL) nifti_image_free(image2); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->rmsImageFlag){ nifti_image *image2 = reg_io_ReadImageFile(param->rmsImageName); if(image2 == NULL){ fprintf(stderr,"** ERROR Error when reading the image: %s\n",param->rmsImageName); return 1; } reg_checkAndCorrectDimension(image2); // Check image dimension if(image->dim[0]!=image2->dim[0] || image->dim[1]!=image2->dim[1] || image->dim[2]!=image2->dim[2] || image->dim[3]!=image2->dim[3] || image->dim[4]!=image2->dim[4] || image->dim[5]!=image2->dim[5] || image->dim[6]!=image2->dim[6] || image->dim[7]!=image2->dim[7]){ fprintf(stderr,"Both images do not have the same dimension\n"); return 1; } double meanRMSerror = reg_tools_getMeanRMS(image, image2); printf("%g\n", meanRMSerror); nifti_image_free(image2); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->binarisedImageFlag){ reg_tools_binarise_image(image); reg_tools_changeDatatype<unsigned char>(image); if(flag->outputImageFlag) reg_io_WriteImageFile(image,param->outputImageName); else reg_io_WriteImageFile(image,"output.nii"); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->thresholdImageFlag){ reg_tools_binarise_image(image, param->thresholdImageValue); reg_tools_changeDatatype<unsigned char>(image); if(flag->outputImageFlag) reg_io_WriteImageFile(image,param->outputImageName); else reg_io_WriteImageFile(image,"output.nii"); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// if(flag->nanMaskFlag){ nifti_image *maskImage = reg_io_ReadImageFile(param->operationImageName); if(maskImage == NULL){ fprintf(stderr,"** ERROR Error when reading the image: %s\n",param->operationImageName); return 1; } reg_checkAndCorrectDimension(maskImage); nifti_image *resultImage = nifti_copy_nim_info(image); resultImage->data = (void *)malloc(resultImage->nvox * resultImage->nbyper); reg_tools_nanMask_image(image,maskImage,resultImage); if(flag->outputImageFlag) reg_io_WriteImageFile(resultImage,param->outputImageName); else reg_io_WriteImageFile(resultImage,"output.nii"); nifti_image_free(resultImage); nifti_image_free(maskImage); } //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\// nifti_image_free(image); return 0; }
int main (int argc, char *argv[]) { char TEMP_STR[256]; nifti_set_debug_level(3); int Errors=0; { PrintTest("NOT REALLY AN ERROR, JUST TESTING THE ERROR TEST REPORTING MECHANISM",1,NIFTITEST_FALSE,&Errors); PrintTest("NOT REALLY AN ERROR, JUST TESTING THE ERROR COUNTING MECHANISM",Errors==1,NIFTITEST_FALSE,&Errors); Errors=0; } { const char write_image_filename[6][64]={ "ATestReferenceImageForReadingAndWriting.nii", "ATestReferenceImageForReadingAndWriting.hdr", "ATestReferenceImageForReadingAndWriting.img", "ATestReferenceImageForReadingAndWriting.nii.gz", "ATestReferenceImageForReadingAndWriting.hdr.gz", "ATestReferenceImageForReadingAndWriting.img.gz" }; printf("======= Testing All Nifti Valid Names ======\n"); fflush(stdout); unsigned int filenameindex; for(filenameindex=0;filenameindex<6; filenameindex++) { char buf[512]; int CompressedTwoFile = strstr(write_image_filename[filenameindex],".img.gz") != 0 || strstr(write_image_filename[filenameindex],".hdr.gz") != 0; printf("======= Testing with filename: %s ======\n",write_image_filename[filenameindex]); fflush(stdout); nifti_image * reference_image = generate_reference_image(write_image_filename[filenameindex],&Errors); /* * Add an extension to test extension reading */ { static char ext[] = "THIS IS A TEST"; sprintf(buf,"nifti_add_extension %s",write_image_filename[filenameindex]); PrintTest(buf, nifti_add_extension(reference_image, ext,sizeof(ext), NIFTI_ECODE_COMMENT) == -1, NIFTITEST_FALSE,&Errors); sprintf(buf,"valid_nifti_extension %s",write_image_filename[filenameindex]); PrintTest("valid_nifti_extensions", valid_nifti_extensions(reference_image) == 0, NIFTITEST_FALSE,&Errors); } PrintTest("Create reference image",reference_image==0,NIFTITEST_TRUE,&Errors); nifti_image_write ( reference_image ) ; /* * test nifti_copy_extension */ { nifti_image *nim = nifti_simple_init_nim(); PrintTest("nifti_copy_extension", nifti_copy_extensions(nim,reference_image), NIFTITEST_FALSE,&Errors); nifti_image_free(nim); nim = nifti_copy_nim_info(reference_image); PrintTest("nifti_copy_nim_info", nim == 0, NIFTITEST_FALSE,&Errors); PrintTest("nifti_nim_is_valid", nifti_nim_is_valid(nim,0) == 0, NIFTITEST_FALSE,&Errors); nifti_image_free(nim); } { nifti_image * reloaded_image = nifti_image_read(reference_image->fname,1); PrintTest("Reload of image ",reloaded_image==0,NIFTITEST_TRUE,&Errors); { /* * if the file is named '.img', '.hdr', '.img.gz', or '.hdr.gz', then * the header extensions won't be saved with the file. * The test will fail if it finds an extension in a 2-file NIfTI, or * fails to find one in a '.nii' or '.nii.gz' file. */ int result = valid_nifti_extensions(reloaded_image); sprintf(buf,"reload valid_nifti_extensions %s",write_image_filename[filenameindex]); PrintTest(buf, CompressedTwoFile ? result != 0 : result == 0, NIFTITEST_FALSE,&Errors); } nifti_image_infodump(reloaded_image); compare_reference_image_values(reference_image,reloaded_image,&Errors); nifti_image_free(reloaded_image); } { nifti_brick_list NB_orig, NB_select; nifti_image * nim_orig, * nim_select; int blist[5] = { 7, 0, 5, 5, 9 }; /* * test some error paths in the nifti_image_read_bricks */ nim_orig = nifti_image_read_bricks(reference_image->fname,0,blist, &NB_orig); PrintTest("invalid arg bricked image read 1",nim_orig != 0,NIFTITEST_FALSE,&Errors); nim_orig = nifti_image_read_bricks(reference_image->fname, 0, NULL, &NB_orig); PrintTest("Reload of bricked image",nim_orig == 0,NIFTITEST_FALSE,&Errors); nifti_free_NBL(&NB_orig); nifti_image_free(nim_orig); nim_select = nifti_image_read_bricks(reference_image->fname, 5, blist, &NB_select); PrintTest("Reload of bricked image with blist",nim_orig == 0,NIFTITEST_FALSE,&Errors); nifti_free_NBL(&NB_select); nifti_image_free(nim_select); } /* * test nifti_update_dims_from_array */ PrintTest("nifti_update_dims_from_array -- valid dims", nifti_update_dims_from_array(reference_image) != 0, NIFTITEST_FALSE,&Errors); reference_image->dim[0] = 8; PrintTest("nifti_update_dims_from_array -- invalid dims", nifti_update_dims_from_array(reference_image) == 0, NIFTITEST_FALSE,&Errors); { nifti_1_header x = nifti_convert_nim2nhdr(reference_image); char buf[512]; sprintf(buf,"nifti_hdr_looks_good %s",reference_image->fname); PrintTest(buf, !nifti_hdr_looks_good(&x), NIFTITEST_FALSE,&Errors); } nifti_image_free(reference_image); } /* * check nifti_findimgname */ { char *imgname = nifti_findimgname("ATestReferenceImageForReadingAndWriting.hdr",2); PrintTest("nifti_findimgname", imgname == 0 || strcmp(imgname,"ATestReferenceImageForReadingAndWriting.img") != 0, NIFTITEST_FALSE,&Errors); free(imgname); } { int IsNiftiFile; IsNiftiFile = is_nifti_file(write_image_filename[0]); PrintTest("is_nifti_file0", IsNiftiFile != 1,NIFTITEST_FALSE,&Errors); IsNiftiFile = is_nifti_file(write_image_filename[1]); PrintTest("is_nifti_file1", IsNiftiFile != 2,NIFTITEST_FALSE,&Errors); IsNiftiFile = is_nifti_file(write_image_filename[3]); PrintTest("is_nifti_file2", IsNiftiFile != 1,NIFTITEST_FALSE,&Errors); IsNiftiFile = is_nifti_file(write_image_filename[4]); PrintTest("is_nifti_file2", IsNiftiFile != 2,NIFTITEST_FALSE,&Errors); } } { /* * test writing and reading an ascii file */ nifti_image * reference_image = generate_reference_image("TestAsciiImage.nia",&Errors); reference_image->nifti_type = 3; nifti_image_write(reference_image); nifti_image * reloaded_image = nifti_image_read("TestAsciiImage.nia",1); PrintTest("Read/Write Ascii image", reloaded_image == 0,NIFTITEST_FALSE,&Errors); nifti_image_free(reference_image); nifti_image_free(reloaded_image); } { enum { NUM_FILE_NAMES=8 }; const char * FILE_NAMES[NUM_FILE_NAMES]={ "myimage", "myimage.tif", "myimage.tif.gz", "myimage.nii", "myimage.img.gz", ".nii", ".myhiddenimage", ".myhiddenimage.nii" }; const char * KNOWN_FILE_BASENAMES[NUM_FILE_NAMES]={ "myimage", "myimage.tif", "myimage.tif.gz", "myimage", "myimage", "", ".myhiddenimage", ".myhiddenimage" }; const int KNOWN_nifti_validfilename[NUM_FILE_NAMES]={ 1, 1, 1, 1, 1, 0, 1, 1 }; const int KNOWN_nifti_is_complete_filename[NUM_FILE_NAMES]={ 0, 0, 0, 1, 1, 0, 0, 1 }; unsigned int fni; for(fni=0;fni<NUM_FILE_NAMES;fni++) { printf("\nTesting \"%s\" filename\n",FILE_NAMES[fni]); { int KnownValid=nifti_validfilename(FILE_NAMES[fni]); snprintf(TEMP_STR,256,"nifti_validfilename(\"%s\")=%d",FILE_NAMES[fni],KnownValid); PrintTest(TEMP_STR,KnownValid != KNOWN_nifti_validfilename[fni],NIFTITEST_FALSE,&Errors); } { int KnownValid=nifti_is_complete_filename(FILE_NAMES[fni]); snprintf(TEMP_STR,256,"nifti_is_complete_filename(\"%s\")=%d",FILE_NAMES[fni],KnownValid); PrintTest(TEMP_STR,KnownValid != KNOWN_nifti_is_complete_filename[fni],NIFTITEST_FALSE,&Errors); } { char * basename=nifti_makebasename(FILE_NAMES[fni]); snprintf(TEMP_STR,256,"nifti_makebasename(\"%s\")=\"%s\"",FILE_NAMES[fni],basename); PrintTest(TEMP_STR,strcmp(basename,KNOWN_FILE_BASENAMES[fni]) != 0,NIFTITEST_FALSE,&Errors); free(basename); } } /* * the following 2 calls aren't tested, because all they do is display * compile-time information -- no way to fail unless writing to stdout fails. */ nifti_disp_lib_hist(); nifti_disp_lib_version(); /* * the following exercises error path code in nifti_image_read_bricks */ PrintTest( "nifti_image_read_bricks 1", nifti_image_read_bricks((char *)0,-1,(const int *)0,(nifti_brick_list *)0) != 0, NIFTITEST_FALSE, &Errors); PrintTest( "nifti_image_read_bricks 1", nifti_image_read_bricks("NOFILE.NOFILE",-1,(const int *)0,(nifti_brick_list *)0) != 0, NIFTITEST_FALSE, &Errors); } /* * call nifti_datatype_string with all possible values */ #define nifti_datatype_test(constant,string) \ { \ char buf[64]; \ sprintf(buf,"nifti_datatype_string %s",string); \ PrintTest( \ buf, \ strcmp(nifti_datatype_string(constant),string) != 0, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_datatype_test(DT_UNKNOWN,"UNKNOWN"); nifti_datatype_test(DT_BINARY, "BINARY"); nifti_datatype_test(DT_INT8, "INT8"); nifti_datatype_test(DT_UINT8, "UINT8"); nifti_datatype_test(DT_INT16, "INT16"); nifti_datatype_test(DT_UINT16, "UINT16"); nifti_datatype_test(DT_INT32, "INT32"); nifti_datatype_test(DT_UINT32, "UINT32"); nifti_datatype_test(DT_INT64, "INT64"); nifti_datatype_test(DT_UINT64, "UINT64"); nifti_datatype_test(DT_FLOAT32, "FLOAT32"); nifti_datatype_test(DT_FLOAT64, "FLOAT64"); nifti_datatype_test(DT_FLOAT128, "FLOAT128"); nifti_datatype_test(DT_COMPLEX64, "COMPLEX64"); nifti_datatype_test(DT_COMPLEX128, "COMPLEX128"); nifti_datatype_test(DT_COMPLEX256, "COMPLEX256"); nifti_datatype_test(DT_RGB24, "RGB24"); #define nifti_is_inttype_test(constant,rval) \ { \ char buf[64]; \ sprintf(buf,"nifti_datatype_string %d",constant); \ PrintTest( \ buf, \ nifti_is_inttype(constant) != rval, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_is_inttype_test(DT_UNKNOWN,0); nifti_is_inttype_test(DT_BINARY,0); nifti_is_inttype_test(DT_INT8,1); nifti_is_inttype_test(DT_UINT8,1); nifti_is_inttype_test(DT_INT16,1); nifti_is_inttype_test(DT_UINT16,1); nifti_is_inttype_test(DT_INT32,1); nifti_is_inttype_test(DT_UINT32,1); nifti_is_inttype_test(DT_INT64,1); nifti_is_inttype_test(DT_UINT64,1); nifti_is_inttype_test(DT_FLOAT32,0); nifti_is_inttype_test(DT_FLOAT64,0); nifti_is_inttype_test(DT_FLOAT128,0); nifti_is_inttype_test(DT_COMPLEX64,0); nifti_is_inttype_test(DT_COMPLEX128,0); nifti_is_inttype_test(DT_COMPLEX256,0); nifti_is_inttype_test(DT_RGB24,1); #define nifti_units_string_test(constant,string) \ { \ char buf[64]; \ sprintf(buf,"nifti_units_string_test %s",string); \ PrintTest( \ buf, \ strcmp(nifti_units_string(constant),string) != 0, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_units_string_test(NIFTI_UNITS_METER,"m"); nifti_units_string_test(NIFTI_UNITS_MM,"mm"); nifti_units_string_test(NIFTI_UNITS_MICRON,"um"); nifti_units_string_test(NIFTI_UNITS_SEC,"s"); nifti_units_string_test(NIFTI_UNITS_MSEC,"ms"); nifti_units_string_test(NIFTI_UNITS_USEC,"us"); nifti_units_string_test(NIFTI_UNITS_HZ,"Hz"); nifti_units_string_test(NIFTI_UNITS_PPM,"ppm"); nifti_units_string_test(NIFTI_UNITS_RADS,"rad/s"); #define nifti_intent_string_test(constant,string) \ { \ char buf[64]; \ sprintf(buf,"nifti_intent_string %s",string); \ PrintTest( \ buf, \ strcmp(nifti_intent_string(constant),string) != 0, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_intent_string_test(NIFTI_INTENT_CORREL,"Correlation statistic"); nifti_intent_string_test(NIFTI_INTENT_TTEST,"T-statistic"); nifti_intent_string_test(NIFTI_INTENT_FTEST,"F-statistic"); nifti_intent_string_test(NIFTI_INTENT_ZSCORE,"Z-score"); nifti_intent_string_test(NIFTI_INTENT_CHISQ,"Chi-squared distribution"); nifti_intent_string_test(NIFTI_INTENT_BETA,"Beta distribution"); nifti_intent_string_test(NIFTI_INTENT_BINOM,"Binomial distribution"); nifti_intent_string_test(NIFTI_INTENT_GAMMA,"Gamma distribution"); nifti_intent_string_test(NIFTI_INTENT_POISSON,"Poisson distribution"); nifti_intent_string_test(NIFTI_INTENT_NORMAL,"Normal distribution"); nifti_intent_string_test(NIFTI_INTENT_FTEST_NONC,"F-statistic noncentral"); nifti_intent_string_test(NIFTI_INTENT_CHISQ_NONC,"Chi-squared noncentral"); nifti_intent_string_test(NIFTI_INTENT_LOGISTIC,"Logistic distribution"); nifti_intent_string_test(NIFTI_INTENT_LAPLACE,"Laplace distribution"); nifti_intent_string_test(NIFTI_INTENT_UNIFORM,"Uniform distribition"); nifti_intent_string_test(NIFTI_INTENT_TTEST_NONC,"T-statistic noncentral"); nifti_intent_string_test(NIFTI_INTENT_WEIBULL,"Weibull distribution"); nifti_intent_string_test(NIFTI_INTENT_CHI,"Chi distribution"); nifti_intent_string_test(NIFTI_INTENT_INVGAUSS,"Inverse Gaussian distribution"); nifti_intent_string_test(NIFTI_INTENT_EXTVAL,"Extreme Value distribution"); nifti_intent_string_test(NIFTI_INTENT_PVAL,"P-value"); nifti_intent_string_test(NIFTI_INTENT_LOGPVAL,"Log P-value"); nifti_intent_string_test(NIFTI_INTENT_LOG10PVAL,"Log10 P-value"); nifti_intent_string_test(NIFTI_INTENT_ESTIMATE,"Estimate"); nifti_intent_string_test(NIFTI_INTENT_LABEL,"Label index"); nifti_intent_string_test(NIFTI_INTENT_NEURONAME,"NeuroNames index"); nifti_intent_string_test(NIFTI_INTENT_GENMATRIX,"General matrix"); nifti_intent_string_test(NIFTI_INTENT_SYMMATRIX,"Symmetric matrix"); nifti_intent_string_test(NIFTI_INTENT_DISPVECT,"Displacement vector"); nifti_intent_string_test(NIFTI_INTENT_VECTOR,"Vector"); nifti_intent_string_test(NIFTI_INTENT_POINTSET,"Pointset"); nifti_intent_string_test(NIFTI_INTENT_TRIANGLE,"Triangle"); nifti_intent_string_test(NIFTI_INTENT_QUATERNION,"Quaternion"); nifti_intent_string_test(NIFTI_INTENT_DIMLESS,"Dimensionless number"); nifti_intent_string_test(-200,"Unknown"); #define nifti_slice_string_test(constant,string) \ { \ char buf[64]; \ sprintf(buf,"nifti_slice_string_test %s",string); \ PrintTest( \ buf, \ strcmp(nifti_slice_string(constant),string) != 0, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_slice_string_test(NIFTI_SLICE_SEQ_INC,"sequential_increasing"); nifti_slice_string_test(NIFTI_SLICE_SEQ_DEC,"sequential_decreasing"); nifti_slice_string_test(NIFTI_SLICE_ALT_INC,"alternating_increasing"); nifti_slice_string_test(NIFTI_SLICE_ALT_DEC,"alternating_decreasing"); nifti_slice_string_test(NIFTI_SLICE_ALT_INC2,"alternating_increasing_2"); nifti_slice_string_test(NIFTI_SLICE_ALT_DEC2,"alternating_decreasing_2"); #define nifti_orientation_string_test(constant,string) \ { \ char buf[64]; \ sprintf(buf,"nifti_orientation_string_test %s",string); \ PrintTest( \ buf, \ strcmp(nifti_orientation_string(constant),string) != 0, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_orientation_string_test(NIFTI_L2R,"Left-to-Right"); nifti_orientation_string_test(NIFTI_R2L,"Right-to-Left"); nifti_orientation_string_test(NIFTI_P2A,"Posterior-to-Anterior"); nifti_orientation_string_test(NIFTI_A2P,"Anterior-to-Posterior"); nifti_orientation_string_test(NIFTI_I2S,"Inferior-to-Superior"); nifti_orientation_string_test(NIFTI_S2I,"Superior-to-Inferior"); #define nifti_datatype_sizes_test(constant,Nbyper,Swapsize) \ { \ int nbyper; \ int swapsize; \ char buf[64]; \ sprintf(buf,"nifti_datatype_sizes_test %d",constant); \ nifti_datatype_sizes(constant,&nbyper,&swapsize); \ PrintTest( \ buf, \ nbyper != Nbyper || swapsize != Swapsize, \ NIFTITEST_FALSE, \ &Errors); \ } nifti_datatype_sizes_test(DT_UINT8,1,0); nifti_datatype_sizes_test(DT_UINT16,2,2); nifti_datatype_sizes_test(DT_RGB24,3,0); nifti_datatype_sizes_test(DT_FLOAT32,4,4); nifti_datatype_sizes_test(DT_COMPLEX64,8,4); nifti_datatype_sizes_test(DT_UINT64,8,8); nifti_datatype_sizes_test(DT_FLOAT128,16,16); nifti_datatype_sizes_test(DT_COMPLEX128,16,8); nifti_datatype_sizes_test(DT_COMPLEX256,32,16); { mat44 R; unsigned i,j; for(i = 0; i < 4; i++) for(j = 0; j < 4; j++) R.m[i][j] = (i == j ? 1 : 0); float qb; float qc; float qd; float qx; float qy; float qz; float dx; float dy; float dz; float qfac; nifti_mat44_to_quatern(R,&qb,&qc,&qd,&qx,&qy,&qz,&dx,&dy,&dz,&qfac); PrintTest("nifti_mat44_to_quatern", qb != 0.000000 || qc != 0.000000 || qd != 0.000000 || qx != 0.000000 || qy != 0.000000 || qd != 0.000000 || dx != 1.000000 || dy != 1.000000 || dz != 1.000000 || qfac != 1.000000, NIFTITEST_FALSE,&Errors); } { mat44 x = nifti_make_orthog_mat44(0.14,0.0,0.0, 0.0,0.9,0.0, 0.0,0.0,1.1); PrintTest("nifti_make_orthog_mat44", x.m[0][0] != 1.0 || x.m[1][1] != 1.0 || x.m[2][2] != 1.0 || x.m[3][3] != 1.0, NIFTITEST_FALSE,&Errors); } { static char x[16] = { 'a','b','c','d','e','f','g','h', 'H','G','F','E','D','C','B','A' }; nifti_swap_Nbytes(1,16,(void *)x); PrintTest("nifti_swap_16bytes", x[0] != 'A' || x[1] != 'B' || x[2] != 'C' || x[3] != 'D' || x[4] != 'E' || x[5] != 'F' || x[6] != 'G' || x[7] != 'H' || x[8] != 'h' || x[9] != 'g' || x[10] != 'f' || x[11] != 'e' || x[12] != 'd' || x[13] != 'c' || x[14] != 'b' || x[15] != 'a', NIFTITEST_FALSE,&Errors); } { static char x[8] = { 'a','b','c','d','D','C','B','A' }; nifti_swap_Nbytes(1,8,(void *)x); PrintTest("nifti_swap_8bytes", x[0] != 'A' || x[1] != 'B' || x[2] != 'C' || x[3] != 'D' || x[4] != 'd' || x[5] != 'c' || x[6] != 'b' || x[7] != 'a', NIFTITEST_FALSE,&Errors); } { /* * test nifti_simple_init_nim */ nifti_image *nim = nifti_simple_init_nim(); PrintTest("nifti_simple_init_nim", nim == 0,NIFTITEST_FALSE,&Errors); nifti_image_free(nim); nim = 0; /* * test nifti_image_open */ znzFile f = nifti_image_open("ATestReferenceImageForReadingAndWriting.hdr","r",&nim); PrintTest("nifti_image_open", nim == 0 || f == 0, NIFTITEST_FALSE,&Errors); PrintTest("nifti_image_load", nifti_image_load(nim) == -1, NIFTITEST_FALSE,&Errors); nifti_image_unload(nim); PrintTest("nifti_image_unload", nim->data != 0, NIFTITEST_FALSE,&Errors); znzclose(f); nifti_image_free(nim); } /* * call various functions from nifti_stats */ printf("\n\nTOTAL ERRORS=%d\n",Errors); return Errors; }
// niftiManager::readVector():reads 1D nifti vector ValueType niftiManager::readVector(const std::string& vectorFilenameRef, std::vector<float>* vectorPointer) const { std::vector<float>& vector = *vectorPointer; std::string vectorFilename( vectorFilenameRef ); std::string vectorFilenameZipped( vectorFilenameRef ); std::string extension; std::string zipExtension( boost::filesystem::path(vectorFilename).extension().string() ); if ( zipExtension == ".gz" ) { vectorFilename.resize(vectorFilename.size()-3); // Variables for calling system commands std::string sysCommand( "gzip -dcf " + vectorFilenameZipped + " > " + vectorFilename ); int success(system(sysCommand.c_str())); extension = ( boost::filesystem::path(vectorFilename).extension().string() ); } else if ( zipExtension == getFileExtension( ETFull ) || zipExtension == getFileExtension( ETCompact ) ) { extension = zipExtension; } else { std::cerr << "File \"" << vectorFilenameZipped << "\" has no recognized extension (\"" << zipExtension << "\") stopping." << std::endl; return VTError; } ValueType vectorValueType; if( extension == getFileExtension( ETFull ) ) { nifti_image* niftiImage = NULL; boost::mutex& ioMutex(boost::detail::thread::singleton<boost::mutex>::instance()) ; ioMutex.lock(); { niftiImage = nifti_image_read(vectorFilename.c_str(), 1); } ioMutex.unlock(); if( !niftiImage ) { std::cerr<< "ERROR @ niftiManager::readVector(): there was an error calling nifti_image_read() on vector "<< vectorFilename <<std::endl; return VTError; } if( niftiImage->ndim != 1 ) { std::cerr << "ERROR @ niftiManager::readVector(): nifti file has more than 1 dimension (" << niftiImage->ndim <<"): "<< niftiImage->nx <<" "<< niftiImage->ny <<" "<< niftiImage->nz <<" "<< niftiImage->nt <<" "<< niftiImage->nu <<" "<< niftiImage->nv <<std::endl; return VTError; } const size_t repType( niftiImage->datatype ); const size_t repByteSize( niftiImage->nbyper ); const size_t dataSize( niftiImage->nvox ); if( repType == DT_FLOAT32 ) { vectorValueType = VTFloat32; } else if ( repType == DT_UINT8 ) { vectorValueType = VTUINT8; } else { std::cerr<< "ERROR @ niftiManager::readVector(): vector representation type not recognized (not FLOAT32 nor UNIT8)" << std::endl; return VTError; } const size_t dimx( niftiImage->nx ); if( dimx != dataSize ) { std::cerr<< "ERROR @ niftiManager::readVector(): vector dimension does not match data size" << std::endl; return VTError; } vector.clear(); vector.resize(dataSize,0); void* niftiData(niftiImage->data); for (int i=0 ; i<dataSize ; ++i) { size_t byteOffset( i * repByteSize ); if( byteOffset >= dataSize ) { std::cerr<< "ERROR @ niftiManager::readVector():: pointer offset was too high when loading nifti data" << std::endl; return VTError; } void* dataPos = static_cast<unsigned char*>(niftiData) + byteOffset; if (repType == DT_UINT8) { unsigned char datapoint = *(static_cast<unsigned char*>(dataPos)); vector[i] = (float)datapoint; } else if (repType == DT_FLOAT32) { float datapoint = *(static_cast<float*>(dataPos)); vector[i] = datapoint; } else { std::cerr<< "ERROR @ niftiManager::readVector(): vector representation type not recognized (not FLOAT32 nor UNIT8)" << std::endl; return VTError; } } // clean up nifti_image_free( niftiImage ); } else if ( extension == getFileExtension( ETCompact ) ) { std::ifstream inFile; inFile.open( vectorFilename.c_str(), std::ios::in | std::ios::binary | std::ios::ate ); if( !inFile.is_open() ) { std::stringstream errormessage; errormessage << "ERROR @ niftiManager::readVector(): there was an error opening the input image file "<< vectorFilename <<std::endl; throw std::runtime_error( errormessage.str() ); } size_t dataSize = inFile.tellg(); void* data = malloc( dataSize ); inFile.seekg( 0, std::ios::beg ); boost::mutex& ioMutex(boost::detail::thread::singleton<boost::mutex>::instance()) ; ioMutex.lock(); { inFile.read( static_cast<char*>(data), dataSize ); } ioMutex.unlock(); inFile.close(); const size_t headerSize = UINT32_SIZE + UINT32_SIZE; void* dataPos = static_cast<unsigned char*>(data); const size_t repType = *(static_cast<uint32_t*>(dataPos)); dataPos = static_cast<unsigned char*>(data) + UINT32_SIZE; const size_t dimx = *(static_cast<uint32_t*>(dataPos)); size_t repByteSize( 0 ); if( repType == (FLOAT_SIZE * CHAR_BIT) ) { vectorValueType = VTFloat32; repByteSize = FLOAT_SIZE; } else if ( repType == (UINT8_SIZE * CHAR_BIT) ) { vectorValueType = VTUINT8; repByteSize = UINT8_SIZE; } else { std::cerr<< "ERROR @ niftiManager::readVector(): vector representation type not recognized: " << repType << " (not FLOAT32 nor UNIT8)" << std::endl; return VTError; } const size_t dataSizeTest = headerSize + ( dimx * repByteSize ); if( dataSize != dataSizeTest ) { std::stringstream errormessage; errormessage << "ERROR @ niftiManager::readVector(): file data as read: "<< dataSize << " is different as file data according to header: " << dataSizeTest <<std::endl; errormessage<<" headerSize: "<< headerSize <<" dimx: "<< dimx <<" repSize: "<<repByteSize << std::endl; throw std::runtime_error( errormessage.str() ); } vector.clear(); vector.resize(dimx,0); for( size_t i = 0; i < dimx; ++i ) { size_t byteOffset( headerSize + ( i * repByteSize ) ); if( byteOffset >= dataSize ) { std::cerr<< "ERROR @ niftiManager::readVector():: pointer offset was too high when loading nifti data" << std::endl; return VTError; } dataPos = static_cast<unsigned char*>(data) + byteOffset; if ( vectorValueType == VTUINT8 ) { uint8_t datapoint = *(static_cast<uint8_t*>(dataPos)); vector[i] = (float)datapoint; } else if ( vectorValueType == VTFloat32 ) { float datapoint = *(static_cast<float*>(dataPos)); vector[i] = datapoint; } else { std::cerr<< "ERROR @ niftiManager::readVector(): vector representation type not recognized (not FLOAT32 nor UNIT8)" << std::endl; return VTError; } } // clean up free( data ); } else { std::cerr << "File \"" << vectorFilename << "\" has no recognized extension (\"" << extension << "\") stopping." << std::endl; return VTError; } if ( zipExtension == ".gz" ) { // Variables for calling system commands std::string sysCommand( "rm -f " + vectorFilename ); int success(system(sysCommand.c_str())); } return vectorValueType; }// end niftiManager::readVector() ----------------------------------------------------------------
THD_3dim_dataset * THD_open_nifti( char *pathname ) { THD_3dim_dataset *dset=NULL ; nifti_image *nim ; int ntt , nbuc , nvals ; int use_qform = 0 , use_sform = 0, form_code = 0 ; int statcode = 0 , datum , iview , ibr ; int scale_data = 0 ; /* flag based on scl_slope and inter 20 Jun 2008 */ int xform_data = 0; THD_ivec3 orixyz , nxyz ; THD_fvec3 dxyz , orgxyz ; THD_mat33 R ; mat44 ijk_to_dicom44 ; char *ppp , prefix[THD_MAX_PREFIX] ; char form_priority = 'S' ; /* 23 Mar 2006 */ static int n_xform_warn=0; ENTRY("THD_open_nifti") ; /*-- open input file --*/ { /* set the nifti_io debug level 8 Apr 2005 [rickr] */ char * ept = my_getenv("AFNI_NIFTI_DEBUG"); if( ept != NULL ) nifti_set_debug_level(atoi(ept)); } nifti_set_alter_cifti(1) ; /* if CIFTI, shift dims 23 Jul 2015 [rickr] */ nim = nifti_image_read( pathname, 0 ) ; if( nim == NULL || nim->nifti_type == 0 ) RETURN(NULL) ; /*-- extract some useful AFNI-ish information from the nim struct --*/ /* we must have at least 2 spatial dimensions */ /* this should be okay 11 Jun 2007 */ /* if( nim->nx < 2 || nim->ny < 2 ) RETURN(NULL) ; */ /* 4th dimension = time; 5th dimension = bucket: these are mutually exclusive in AFNI at present */ ntt = nim->nt ; nbuc = nim->nu ; /* nt and nu might be 0 now (see irritating niftilib 1.17 update) */ /* so ensure that ntt and nbuc are positive 02 Mar 2006 [rickr] */ if( ntt <= 0 ) ntt = 1; if( nbuc <= 0 ) nbuc = 1; if( nim->nz <= 0 ) nim->nz = 1 ; /* 03 Mar 2006: RWCox */ if( ntt > 1 && nbuc > 1 ){ fprintf(stderr, "** AFNI can't deal with 5 dimensional NIfTI(%s)\n", pathname ) ; RETURN(NULL) ; } nvals = MAX(ntt,nbuc) ; /* collapse higher-dimensional datasets 23 Jul 2015 [rickr] */ /* (this includes CIFTI) */ if( nim->nv > 1 ) nvals *= nim->nv; if( nim->nw > 1 ) nvals *= nim->nw; if( ntt > 1 ) ntt = nvals; else nbuc = nvals; /* determine type of dataset values: if we are scaling, or if the data type in the NIfTI file is something AFNI can't handle, then the result will be floats */ /* do not scale if slope is 0 or if slope is 1 and inter is 0 */ if( !isfinite(nim->scl_slope) || !isfinite(nim->scl_inter) ){ fprintf(stderr,"** bad scl_slope and inter = %f, %f, ignoring...\n", nim->scl_slope, nim->scl_inter); } else { scale_data = nim->scl_slope != 0.0 && (nim->scl_slope != 1.0 || nim->scl_inter != 0.0) ; } { char *eee = getenv("AFNI_NIFTI_SCALE") ; if( eee != NULL && toupper(*eee) == 'N' ) scale_data = 0 ; } switch( nim->datatype ){ default: fprintf(stderr, "** AFNI can't handle NIFTI datatype=%d (%s) in file %s\n", nim->datatype, nifti_datatype_string(nim->datatype), pathname ); RETURN(NULL) ; break ; case DT_UINT8: datum = scale_data ? MRI_float : MRI_byte ; xform_data = scale_data; break ; case DT_INT16: datum = scale_data ? MRI_float : MRI_short ; xform_data = scale_data; break ; case DT_FLOAT32: datum = MRI_float ; break ; case DT_COMPLEX64: datum = MRI_complex ; break ; case DT_RGB24: datum = MRI_rgb ; break ; case DT_INT8: /* NIfTI-1 data types that AFNI can't handle directly */ case DT_UINT16: case DT_INT32: case DT_UINT32: case DT_FLOAT64: datum = MRI_float ; xform_data = 1 ; break ; #if 0 case DT_COMPLEX128: /* this case would be too much like real work */ fprintf(stderr, "** AFNI convert NIFTI_datatype=%d (%s) in file %s to COMPLEX64\n", nim->datatype, nifti_datatype_string(nim->datatype), pathname ); datum = MRI_complex ; break ; #endif } if( xform_data && !AFNI_noenv("AFNI_NIFTI_TYPE_WARN")) { if (!n_xform_warn || AFNI_yesenv("AFNI_NIFTI_TYPE_WARN")) {/* ZSS 04/11 */ fprintf(stderr, "** AFNI converts NIFTI_datatype=%d (%s) in file %s to FLOAT32\n", nim->datatype, nifti_datatype_string(nim->datatype), pathname ); if (!AFNI_yesenv("AFNI_NIFTI_TYPE_WARN")) { fprintf(stderr, " Warnings of this type will be muted for this session.\n" " Set AFNI_NIFTI_TYPE_WARN to YES to see them all, NO to see none.\n"); } } ++n_xform_warn; } /* check for statistics code */ if( nim->intent_code >= NIFTI_FIRST_STATCODE && nim->intent_code <= NIFTI_LAST_STATCODE ){ if( nim->intent_code > FUNC_PT_TYPE ){ fprintf(stderr, "** AFNI doesn't understand NIFTI statistic type %d (%s) in file %s\n", nim->intent_code , nifti_intent_string(nim->intent_code) , pathname ) ; } else { statcode = nim->intent_code ; if( nbuc > 1 ){ fprintf(stderr, "** AFNI doesn't support NIFTI voxel-dependent statistic parameters" " in file %s\n" , pathname ) ; statcode = 0 ; } } } /* 23 Mar 2006: set qform or sform as having priority -- RWCox */ ppp = my_getenv("NIFTI_FORM_PRIORITY") ; if( ppp == NULL ) ppp = getenv("AFNI_FORM_PRIORITY") ; if( ppp == NULL ) ppp = getenv("AFNI_NIFTI_PRIORITY") ; if( ppp == NULL ) ppp = getenv("AFNI_NIFTI_FORM") ; if( ppp == NULL ) ppp = getenv("AFNI_NIFTI_FORM_PRIORITY") ; if( ppp != NULL ){ char fp = toupper(*ppp) ; if( fp == 'S' || fp == 'Q' ) form_priority = fp ; else WARNING_message("Illegal NIFTI_FORM_PRIORITY='%s'",ppp) ; } /** 24 Mar 2006: check determs of qform and sform, if have both **/ if( nim->qform_code > 0 && nim->sform_code > 0 ){ float qdet , sdet ; LOAD_MAT(R, nim->qto_xyz.m[0][0] , nim->qto_xyz.m[0][1] , nim->qto_xyz.m[0][2] , nim->qto_xyz.m[1][0] , nim->qto_xyz.m[1][1] , nim->qto_xyz.m[1][2] , nim->qto_xyz.m[2][0] , nim->qto_xyz.m[2][1] , nim->qto_xyz.m[2][2] ) ; qdet = MAT_DET(R) ; LOAD_MAT(R, nim->sto_xyz.m[0][0] , nim->sto_xyz.m[0][1] , nim->sto_xyz.m[0][2] , nim->sto_xyz.m[1][0] , nim->sto_xyz.m[1][1] , nim->sto_xyz.m[1][2] , nim->sto_xyz.m[2][0] , nim->sto_xyz.m[2][1] , nim->sto_xyz.m[2][2] ) ; sdet = MAT_DET(R) ; if( qdet*sdet < 0.0f ) WARNING_message("NIfTI('%s'): Qform/Sform handedness differ; %c wins!", pathname , form_priority ) ; } /* KRH 07/11/05 -- adding ability to choose spatial transform from the options of qform, sform, bothform, or noform. If qform is present, it will be used. If qform is absent, but sform present, then the sform will be modified to be an orthogonal rotation and used. If both qform and sform are absent, then we will have an error. Previously assumed qform present. */ /* 23 Mar 2006: use form_priority to choose between them */ if ((nim->qform_code > 0) && (nim->sform_code > 0) ) { if( form_priority == 'Q' ) { use_qform = 1 ; use_sform = 0 ; } else { use_qform = 0 ; use_sform = 1 ; } } else if (nim->qform_code > 0){ use_qform = 1 ; use_sform = 0 ; } else if (nim->sform_code > 0){ use_qform = 0 ; use_sform = 1 ; } else { use_qform = 0 ; use_sform = 0 ; WARNING_message( "NO spatial transform (neither qform nor sform), in NIfTI file '%s'" , pathname ) ; } /** now take NIfTI-1.1 coords and transform to AFNI codes **/ if (use_qform) { float orgx, orgy, orgz ; form_code = nim->qform_code; /* determine orientation from the qto_xyz matrix, which transforms (i,j,k) voxel indexes to (x,y,z) LPI coordinates */ LOAD_MAT(R, -nim->qto_xyz.m[0][0] , /* negate x and y */ -nim->qto_xyz.m[0][1] , /* coefficients, */ -nim->qto_xyz.m[0][2] , /* since AFNI works */ -nim->qto_xyz.m[1][0] , /* with RAI coords, */ -nim->qto_xyz.m[1][1] , /* but NIFTI uses */ -nim->qto_xyz.m[1][2] , /* LPI coordinates. */ nim->qto_xyz.m[2][0] , /* [Which is my own] */ nim->qto_xyz.m[2][1] , /* [damn fault!!!!!] */ nim->qto_xyz.m[2][2] ) ; LOAD_MAT44(ijk_to_dicom44, -nim->qto_xyz.m[0][0] , /* negate x and y */ -nim->qto_xyz.m[0][1] , /* coefficients, */ -nim->qto_xyz.m[0][2] , /* since AFNI works */ -nim->qto_xyz.m[0][3] , -nim->qto_xyz.m[1][0] , /* with RAI coords, */ -nim->qto_xyz.m[1][1] , /* but NIFTI uses */ -nim->qto_xyz.m[1][2] , /* LPI coordinates. */ -nim->qto_xyz.m[1][3] , nim->qto_xyz.m[2][0] , /* [Which is my own] */ nim->qto_xyz.m[2][1] , /* [damn fault!!!!!] */ nim->qto_xyz.m[2][2] , nim->qto_xyz.m[2][3] ) ; orixyz = THD_matrix_to_orientation( R ) ; /* compute orientation codes */ iview = NIFTI_code_to_view(nim->qform_code); /* load the offsets and the grid spacings */ if (ORIENT_xyz[orixyz.ijk[0]] == 'z' ) { orgx = nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[0]] - 1][3] ; } else { orgx = - nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[0]] - 1][3] ; } if (ORIENT_xyz[orixyz.ijk[1]] == 'z' ) { orgy = nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[1]] - 1][3] ; } else { orgy = - nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[1]] - 1][3] ; } if (ORIENT_xyz[orixyz.ijk[2]] == 'z' ) { orgz = nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[2]] - 1][3] ; } else { orgz = - nim->qto_xyz.m[ORIENT_xyzint[orixyz.ijk[2]] - 1][3] ; } LOAD_FVEC3( orgxyz , orgx , orgy , orgz ) ; #if 0 LOAD_FVEC3( orgxyz , -nim->qto_xyz.m[0][3] , /* again, negate */ -nim->qto_xyz.m[1][3] , /* x and y coords */ nim->qto_xyz.m[2][3] ) ; #endif /* AFNI space units are always mm */ if( nim->xyz_units == NIFTI_UNITS_METER ){ nim->dx *= 1000.0 ; nim->dy *= 1000.0 ; nim->dz *= 1000.0 ; } else if( nim->xyz_units == NIFTI_UNITS_MICRON ){ nim->dx *= 0.001 ; nim->dy *= 0.001 ; nim->dz *= 0.001 ; } LOAD_FVEC3( dxyz , (ORIENT_sign[orixyz.ijk[0]]=='+') ? nim->dx : -nim->dx , (ORIENT_sign[orixyz.ijk[1]]=='+') ? nim->dy : -nim->dy , (ORIENT_sign[orixyz.ijk[2]]=='+') ? nim->dz : -nim->dz ) ; } else if (use_sform) { int orimap[7] = { 6 , 1 , 0 , 2 , 3 , 4 , 5 } ; int oritmp[3] ; float dxtmp, dytmp, dztmp ; float xmax, ymax, zmax ; float orgx, orgy, orgz ; float fig_merit, ang_merit ; form_code = nim->sform_code; /* convert sform to nifti orientation codes */ /* n2 10 Jul, 2015 [rickr] */ nifti_dmat44_to_orientation(nim->sto_xyz, &oritmp[0], &oritmp[1], &oritmp[2] ) ; /* convert nifti orientation codes to AFNI codes and store in vector */ LOAD_IVEC3( orixyz , orimap[oritmp[0]] , orimap[oritmp[1]] , orimap[oritmp[2]] ) ; /* assume original view if there's no talairach id present */ iview = NIFTI_code_to_view(nim->sform_code); /* load the offsets and the grid spacings */ if (ORIENT_xyz[orixyz.ijk[0]] == 'z' ) { orgx = nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[0]] - 1][3] ; } else { orgx = - nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[0]] - 1][3] ; } if (ORIENT_xyz[orixyz.ijk[1]] == 'z' ) { orgy = nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[1]] - 1][3] ; } else { orgy = - nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[1]] - 1][3] ; } if (ORIENT_xyz[orixyz.ijk[2]] == 'z' ) { orgz = nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[2]] - 1][3] ; } else { orgz = - nim->sto_xyz.m[ORIENT_xyzint[orixyz.ijk[2]] - 1][3] ; } LOAD_FVEC3( orgxyz , orgx , orgy , orgz ) ; #if 0 LOAD_FVEC3( orgxyz , -nim->sto_xyz.m[0][3] , /* again, negate */ -nim->sto_xyz.m[1][3] , /* x and y coords */ nim->sto_xyz.m[2][3] ) ; #endif #define MAXNUM(a,b) ( (a) > (b) ? (a):(b)) #define MAX3(a,b,c) ( (MAXNUM(a,b)) > (MAXNUM(a,c)) ? (MAXNUM(a,b)):(MAXNUM(a,c))) #define MINNUM(a,b) ( (a) < (b) ? (a):(b)) #define MIN3(a,b,c) ( (MINNUM(a,b)) < (MINNUM(a,c)) ? (MINNUM(a,b)):(MINNUM(a,c))) dxtmp = sqrt ( nim->sto_xyz.m[0][0] * nim->sto_xyz.m[0][0] + nim->sto_xyz.m[1][0] * nim->sto_xyz.m[1][0] + nim->sto_xyz.m[2][0] * nim->sto_xyz.m[2][0] ) ; xmax = MAX3(fabs(nim->sto_xyz.m[0][0]),fabs(nim->sto_xyz.m[1][0]),fabs(nim->sto_xyz.m[2][0])) / dxtmp ; dytmp = sqrt ( nim->sto_xyz.m[0][1] * nim->sto_xyz.m[0][1] + nim->sto_xyz.m[1][1] * nim->sto_xyz.m[1][1] + nim->sto_xyz.m[2][1] * nim->sto_xyz.m[2][1] ) ; ymax = MAX3(fabs(nim->sto_xyz.m[0][1]),fabs(nim->sto_xyz.m[1][1]),fabs(nim->sto_xyz.m[2][1])) / dytmp ; dztmp = sqrt ( nim->sto_xyz.m[0][2] * nim->sto_xyz.m[0][2] + nim->sto_xyz.m[1][2] * nim->sto_xyz.m[1][2] + nim->sto_xyz.m[2][2] * nim->sto_xyz.m[2][2] ) ; zmax = MAX3(fabs(nim->sto_xyz.m[0][2]),fabs(nim->sto_xyz.m[1][2]),fabs(nim->sto_xyz.m[2][2])) / dztmp ; fig_merit = MIN3(xmax,ymax,zmax) ; ang_merit = acos (fig_merit) * 180.0 / 3.141592653 ; #if 0 if (fabs(ang_merit) > .01) { WARNING_message ( "qform not present in:\n" " '%s'\n" " oblique sform used, and the worst axis is\n" " %f degrees from plumb.\n" " If you are performing spatial transformations on this dset, \n" " or viewing/combining it with volumes of differing obliquity,\n" " you should consider running: \n" " 3dWarp -deoblique \n" " on this and other oblique datasets in the same session.\n" ,pathname, ang_merit ) ; } #endif if( nim->xyz_units == NIFTI_UNITS_METER ){ dxtmp *= 1000.0 ; dytmp *= 1000.0 ; dztmp *= 1000.0 ; } else if( nim->xyz_units == NIFTI_UNITS_MICRON ){ dxtmp *= 0.001 ; dytmp *= 0.001 ; dztmp *= 0.001 ; } LOAD_FVEC3( dxyz , (ORIENT_sign[orixyz.ijk[0]]=='+') ? dxtmp : -dxtmp , (ORIENT_sign[orixyz.ijk[1]]=='+') ? dytmp : -dytmp , (ORIENT_sign[orixyz.ijk[2]]=='+') ? dztmp : -dztmp ) ; LOAD_MAT44(ijk_to_dicom44, -nim->sto_xyz.m[0][0] , /* negate x and y */ -nim->sto_xyz.m[0][1] , /* coefficients, */ -nim->sto_xyz.m[0][2] , /* since AFNI works */ -nim->sto_xyz.m[0][3] , -nim->sto_xyz.m[1][0] , /* with RAI coords, */ -nim->sto_xyz.m[1][1] , /* but NIFTI uses */ -nim->sto_xyz.m[1][2] , /* LPI coordinates. */ -nim->sto_xyz.m[1][3] , nim->sto_xyz.m[2][0] , /* [Which is my own] */ nim->sto_xyz.m[2][1] , /* [damn fault!!!!!] */ nim->sto_xyz.m[2][2] , nim->sto_xyz.m[2][3] ) ; } else { /* NO SPATIAL XFORM. BAD BAD BAD BAD BAD BAD. */ float dxtmp, dytmp, dztmp ; /* if pixdim data are present, use them in order to set pixel dimensions. otherwise, set the dimensions to 1 unit. */ dxtmp = ((nim->pixdim[1] > 0) ? nim->pixdim[1] : 1) ; dytmp = ((nim->pixdim[2] > 0) ? nim->pixdim[2] : 1) ; dztmp = ((nim->pixdim[3] > 0) ? nim->pixdim[3] : 1) ; if( nim->xyz_units == NIFTI_UNITS_METER ){ dxtmp *= 1000.0 ; dytmp *= 1000.0 ; dztmp *= 1000.0 ; } else if( nim->xyz_units == NIFTI_UNITS_MICRON ){ dxtmp *= 0.001 ; dytmp *= 0.001 ; dztmp *= 0.001 ; } /* set orientation to LPI by default */ LOAD_IVEC3( orixyz , 1 , 2 , 4 ) ; LOAD_FVEC3( dxyz , (ORIENT_sign[orixyz.ijk[0]]=='+') ? dxtmp : -dxtmp , (ORIENT_sign[orixyz.ijk[1]]=='+') ? dytmp : -dytmp , (ORIENT_sign[orixyz.ijk[2]]=='+') ? dztmp : -dztmp ) ; iview = NIFTI_default_view(); /* set origin to 0,0,0 */ LOAD_FVEC3( orgxyz , 0 , 0 , 0 ) ; /* put scaled identity matrix by default */ LOAD_MAT44(ijk_to_dicom44, dxtmp, 0.0, 0.0, 0.0, 0.0, dytmp, 0.0, 0.0, 0.0, 0.0, dztmp, 0.0 ); } /*-- make an AFNI dataset! --*/ dset = EDIT_empty_copy(NULL) ; ppp = THD_trailname(pathname,0) ; /* strip directory */ MCW_strncpy( prefix , ppp , THD_MAX_PREFIX ) ; /* to make prefix */ /* You need to set the path too before, if you loaded ~/tmp/joe.nii the path appeared to be ./joe.nii, troubling in multiple instances. ZSS Dec 2011 */ THD_init_diskptr_names( dset->dblk->diskptr , THD_filepath(pathname) , NULL , prefix , dset->view_type , True ); nxyz.ijk[0] = nim->nx ; /* grid dimensions */ nxyz.ijk[1] = nim->ny ; nxyz.ijk[2] = nim->nz ; dset->idcode.str[0] = 'N' ; /* overwrite 1st 3 bytes with something special */ dset->idcode.str[1] = 'I' ; dset->idcode.str[2] = 'I' ; MCW_hash_idcode( pathname , dset ) ; /* 06 May 2005 */ EDIT_dset_items( dset , ADN_prefix , prefix , ADN_datum_all , datum , ADN_nxyz , nxyz , ADN_xyzdel , dxyz , ADN_xyzorg , orgxyz , ADN_xyzorient , orixyz , ADN_malloc_type , DATABLOCK_MEM_MALLOC , ADN_view_type , iview , ADN_type , (statcode != 0) ? HEAD_FUNC_TYPE : HEAD_ANAT_TYPE , ADN_none ) ; /* copy transformation matrix to dataset structure */ /* moved after setting grid 4 Apr 2014 [rickr,drg] */ dset->daxes->ijk_to_dicom_real = ijk_to_dicom44; /* not a time dependent dataset */ if( ntt < 2 ){ EDIT_dset_items( dset , ADN_nvals , nbuc , ADN_datum_all , datum , ADN_func_type , (statcode != 0) ? FUNC_BUCK_TYPE : ANAT_BUCK_TYPE , ADN_none ) ; } else { /* is a time dependent dataset */ if( nim->time_units == NIFTI_UNITS_MSEC ){ nim->dt *= 0.001 ; nim->toffset *= 0.001 ; } else if( nim->time_units == NIFTI_UNITS_USEC ){ nim->dt *= 1.e-6 ; nim->toffset *= 1.e-6 ; } EDIT_dset_items( dset , ADN_nvals , ntt , ADN_ntt , ntt , ADN_datum_all , datum , ADN_ttorg , nim->toffset , /* 12 Oct 2007 [rickr] */ ADN_ttdel , nim->dt , ADN_ttdur , 0.0 , ADN_tunits , UNITS_SEC_TYPE , ADN_func_type , (statcode != 0) ? FUNC_FIM_TYPE : ANAT_EPI_TYPE , ADN_none ) ; /* if present, add stuff about the slice-timing offsets */ if( nim->slice_dim == 3 && /* AFNI can only deal with */ nim->slice_code > 0 && /* slice timing offsets */ nim->slice_duration > 0.0 && /* along the k-axis of */ nim->slice_start >= 0 && /* the dataset volume */ nim->slice_start < nim->nz && nim->slice_end > nim->slice_start && nim->slice_end < nim->nz ){ float *toff=(float *)calloc(sizeof(float),nim->nz) , tsl ; int kk ; if( nim->time_units == NIFTI_UNITS_MSEC ) nim->slice_duration *= 0.001; else if( nim->time_units == NIFTI_UNITS_USEC ) nim->slice_duration *= 1.e-6; /* set up slice time offsets in the divers orders */ switch( nim->slice_code ){ case NIFTI_SLICE_SEQ_INC: tsl = 0.0 ; for( kk=nim->slice_start ; kk <= nim->slice_end ; kk++ ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; case NIFTI_SLICE_SEQ_DEC: tsl = 0.0 ; for( kk=nim->slice_end ; kk >= nim->slice_end ; kk-- ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; case NIFTI_SLICE_ALT_INC: tsl = 0.0 ; for( kk=nim->slice_start ; kk <= nim->slice_end ; kk+=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } for( kk=nim->slice_start+1 ; kk <= nim->slice_end ; kk+=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; case NIFTI_SLICE_ALT_INC2: tsl = 0.0 ; for( kk=nim->slice_start+1 ; kk <= nim->slice_end ; kk+=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } for( kk=nim->slice_start ; kk <= nim->slice_end ; kk+=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; case NIFTI_SLICE_ALT_DEC: tsl = 0.0 ; for( kk=nim->slice_end ; kk >= nim->slice_start ; kk-=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } for( kk=nim->slice_end-1 ; kk >= nim->slice_start ; kk-=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; case NIFTI_SLICE_ALT_DEC2: tsl = 0.0 ; for( kk=nim->slice_end-1 ; kk >= nim->slice_start ; kk-=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } for( kk=nim->slice_end ; kk >= nim->slice_start ; kk-=2 ){ toff[kk] = tsl ; tsl += nim->slice_duration ; } break ; } EDIT_dset_items( dset , ADN_nsl , nim->nz , ADN_zorg_sl , orgxyz.xyz[2] , ADN_dz_sl , dxyz.xyz[2] , ADN_toff_sl , toff , ADN_none ) ; free(toff) ; } /* end of slice timing stuff */ } /* end of 3D+time dataset stuff */ /* set atlas space based on NIFTI s/qform code */ NIFTI_code_to_space(form_code,dset); /* add statistics, if present */ if( statcode != 0 ){ for( ibr=0 ; ibr < nvals ; ibr++ ) EDIT_STATAUX4(dset,ibr,statcode,nim->intent_p1,nim->intent_p2,nim->intent_p3,0) ; } /*-- flag to read data from disk using NIFTI functions --*/ dset->dblk->diskptr->storage_mode = STORAGE_BY_NIFTI ; strcpy( dset->dblk->diskptr->brick_name , pathname ) ; dset->dblk->diskptr->byte_order = nim->byteorder ; #if 0 for( ibr=0 ; ibr < nvals ; ibr++ ){ /* make sub-brick labels */ sprintf(prefix,"%s[%d]",tname,ibr) ; EDIT_BRICK_LABEL( dset , ibr , prefix ) ; } #endif /** 10 May 2005: see if there is an AFNI extension; if so, load attributes from it and then edit the dataset appropriately **/ { int ee ; /* extension index */ /* scan extension list to find the first AFNI extension */ for( ee=0 ; ee < nim->num_ext ; ee++ ) if( nim->ext_list[ee].ecode == NIFTI_ECODE_AFNI && nim->ext_list[ee].esize > 32 && nim->ext_list[ee].edata != NULL ) break ; /* if found an AFNI extension ... */ if( ee < nim->num_ext ){ char *buf = nim->ext_list[ee].edata , *rhs , *cpt ; int nbuf = nim->ext_list[ee].esize - 8 ; NI_stream ns ; void *nini ; NI_group *ngr , *nngr ; /* if have data, it's long enough, and starts properly, then ... */ if( buf != NULL && nbuf > 32 && strncmp(buf,"<?xml",5)==0 ){ if( buf[nbuf-1] != '\0' ) buf[nbuf-1] = '\0' ; /* for safety */ cpt = strstr(buf,"?>") ; /* find XML prolog close */ if( cpt != NULL ){ /* if found it, then ... */ ns = NI_stream_open( "str:" , "r" ) ; NI_stream_setbuf( ns , cpt+2 ) ; /* start just after prolog */ nini = NI_read_element(ns,1) ; /* get root element */ NI_stream_close(ns) ; if( NI_element_type(nini) == NI_GROUP_TYPE ){ /* must be a group */ ngr = (NI_group *)nini ; if( strcmp(ngr->name,"AFNI_attributes") == 0 ){ /* root is OK */ nngr = ngr ; } else { /* search in group for proper element */ int nn ; void **nnini ; nn = NI_search_group_deep( ngr , "AFNI_attributes" , &nnini ) ; if( nn <= 0 ) nngr = NULL ; else { nngr = (NI_group *)nnini[0]; NI_free(nnini); } } if( NI_element_type(nngr) == NI_GROUP_TYPE ){ /* have good name */ rhs = NI_get_attribute( nngr , "self_idcode" ) ; if( rhs == NULL ) rhs = NI_get_attribute( nngr , "AFNI_idcode" ) ; if( rhs != NULL ) /* set dataset ID code from XML attribute */ MCW_strncpy( dset->idcode.str , rhs , MCW_IDSIZE ) ; rhs = NI_get_attribute( nngr , "NIfTI_nums" ) ; /* check if */ if( rhs != NULL ){ /* dataset dimensions */ char buf[128] ; /* were altered */ sprintf(buf,"%ld,%ld,%ld,%ld,%ld,%d" , /* 12 May 2005 */ nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->datatype ); if( strcmp(buf,rhs) != 0 ){ static int nnn=0 ; if(nnn==0){fprintf(stderr,"\n"); nnn=1;} fprintf(stderr, "** WARNING: NIfTI file %s dimensions altered since " "AFNI extension was added\n",pathname ) ; } } THD_dblkatr_from_niml( nngr , dset->dblk ); /* load attributes */ THD_datablock_apply_atr( dset ) ; /* apply to dataset struct */ } NI_free_element( ngr ) ; /* get rid of the root element */ } /* end of if found a group element at the root */ } /* end of if extension data array had an XML prolog close */ } /* end of if had a good extension data array */ } /* end of if had an AFNI extension */ } /* end of processing extensions */ /* return unpopulated dataset */ nifti_image_free(nim) ; RETURN(dset) ; }
/* main function */ int main ( int argc , char * argv[] ) { char *inputMask, *inputSPC, *dataInAsci, *outputFile; inputMask = argv[1]; inputSPC = argv[2]; dataInAsci = argv[3]; outputFile = argv[4]; nifti_image *nim_mask = NULL; nifti_image *nim_SPC = NULL; nim_SPC = nifti_image_read(inputSPC,1); int nx=nim_SPC->nx; int ny=nim_SPC->ny; int nz=nim_SPC->nz; int nvox =(int)nim_SPC->nvox; short *pSPC=(short *)nim_SPC->data; int outSize=0; for(int i=0;i<nvox;i++){ if(pSPC[i]!=0) outSize++; } nim_mask = nifti_image_read(inputMask,1); int sizeOfMask=(int)nim_mask->nvox; if(sizeOfMask!=nvox) printf("the sizes are incorrect!\n"); short *mask=(short *)nim_mask->data; int goodValuesTest; for(int i=0;i<sizeOfMask;i++){ if(mask[i]!=0) goodValuesTest++; } FILE *file; file = fopen ( dataInAsci , "r" ); int goodValues; fscanf( file, "%i", &goodValues ); int fsize; fsize = (goodValues * (goodValues+1)) / 2; int access_counter = 0; double **mat; mat = (double**)malloc(goodValues*sizeof(double*)); for ( int i = 0 ; i < goodValues ; i++ ) mat[i] = (double*)malloc(goodValues*sizeof(double)); double d; for ( int i = 0 ; i < goodValues ; i++ ) { for ( int j = i ; j < goodValues ; j++ ) { fscanf( file, "%lf", &d); if ( i == j ) mat[i][j] = d; else { mat[i][j] = d; mat[j][i] = mat[i][j]; } } } fclose( file ); printf("preparing index:\n"); printf("goodValues = %i\n",nvox); printf("nvox = %i\n",nvox); printf("DEBUG:looping to the data pointers:\n"); int maskCounter=0; for(int i=0;i<nvox;i++){ if(mask[i]==1) maskCounter++; } printf("DEBUG:mask counter = %i\n",maskCounter); int pSPCCounter=0; for(int i=0;i<nvox;i++){ if(pSPC[i]==1) pSPCCounter++; } printf("DEBUG:pSPC counter = %i\n",pSPCCounter); printf("DEBUG:looping complete\n"); int array[goodValues]; int counter; counter=0; printf("starting loop ... \n"); for ( int i = 0 ; i < nvox ; i++ ) { if ( mask[i] != 0 && pSPC[i] != 0) { if(counter==goodValues) { printf("ERROR!!! index array overloading! exiting ... \n"); exit(1); } array[counter] = 1; counter++; } else if ( mask[i] != 0 && pSPC[i] == 0) { if(counter==goodValues) { printf("ERROR!!! index array overloading! exiting ... \n"); exit(1); } array[counter] = 0; counter++; } else if ( mask[i] == 0 && pSPC[i] == 0 ) { //printf("case entered=3\n"); } else if ( mask[i] == 0 && pSPC[i] != 0 ) { printf("THE MASKS DO NOT MATCH!!!\n"); exit(1); } else { printf("something went horribly wrong!\n"); exit(1); } } counter = 0; for ( int i = 0 ; i < goodValues ; i++ ) { if ( array[i] != 0 ) counter++; } if ( counter != outSize ) printf("counter = %i\n", counter); printf("creating output matrix\n"); double *out; out = (double*)calloc(outSize*outSize,sizeof(double)); int oCount = 0; for(int i = 0; i < goodValues ; i++ ) { for(int j = 0; j < goodValues ; j++ ) { if ( array[i] == 1 && array[j] == 1 ) { out[oCount]=mat[i][j]; oCount++; if(oCount == outSize*outSize+1) printf("indexing wrong! abort! \n"); } } } for(int i=0;i<goodValues;i++) free(mat[i]); free(mat); //printf("saving output\n"); /* const int dims[8]={3,outSize,outSize,1,1,1,1,1}; nim=nifti_make_new_nim(dims,64,1); nim->data=(double*)out; int err=nifti_set_filenames(nim,outputFile,0,1); nifti_image_write(nim); nifti_image_free(nim); */ printf("done\n"); FILE *output_asci; output_asci = fopen( outputFile, "w" ); fprintf( output_asci, "%i \n", outSize ); for(int i = 0 ; i < outSize ; i++ ) { for(int j = i ; j < outSize ; j++ ) { fprintf(output_asci, "%lf \n", out[i*outSize+j]); } } fprintf(stderr, "done!**\n"); free(out); fclose(output_asci); nifti_image_free(nim_mask); nifti_image_free(nim_SPC); return 0; }
int main(int argc, char* argv[]) { int width = 161, height = 161, layer = 80; int i, j; nifti_image *nim = NULL; char *fin = "/Users/jia/Desktop/F1_58-ed.nii"; nim = nifti_image_read(fin, 1); if (!nim) { fprintf(stderr,"** failed to read NIfTI image from '%s'\n", fin); return 2; } printf("%dD, x=%d y=%d z=%d t=%d u=%d v=%d w=%d\n", nim->ndim, nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw); printf("nvox=%d nbyper=%d\n", nim->nvox, nim->nbyper); printf("%fD x=%f y=%f z=%f t=%f u=%f v=%f w=%f\n", nim->pixdim[0], nim->dx, nim->dy, nim->dz, nim->dt, nim->du, nim->dv, nim->dw); unsigned short *q = static_cast<unsigned short *>(nim->data); unsigned short max = 0, min = 0, mean = 0; unsigned long long sum = 0; for (int i = width*height*layer; i < width*height*(layer+1); i++) { sum += q[i]; // printf("%u\n", q[i]); if (q[i] > max) max = q[i]; } mean = sum / (width*height); printf("max=%u min=%u mean=%u\n", max, min, mean); //=================================================================== // suv_max_group = max(temp_img)*weight/(decay_factor*dose); // suv_mean_group = mean(temp_img)*weight/(decay_factor*dose); //weight INPUT //dose INPUT //time INPUT //half_life INPUT //decay_factor = 2^(-time*60/half_life); //=================================================================== int weight = 156; int dose = 156; int time = 16; int half_life = 15; int decay_factor = 2^(-time*60/half_life); printf("weight=%d decay_factor=%d dose=%d\n", weight, decay_factor, dose); int suv_max = max * weight / (decay_factor * dose); int suv_mean = mean * weight / (decay_factor * dose); printf("suv_max=%d suv_mean=%d\n", suv_max, suv_mean); unsigned short p[width*height]; for (int i = 0; i < width*height; i++) { p[i] = q[width*height*layer + i] * 255 / max; } BMP Output; Output.SetSize(width, height); Output.SetBitDepth(24); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { RGBApixel NewPixel; if (check_area(i, j) == 1) { NewPixel.Red = p[i*width + j]; NewPixel.Green = p[i*width + j]; NewPixel.Blue = p[i*width + j]; } else { NewPixel.Red = 0; NewPixel.Green = 0; NewPixel.Blue = 0; } NewPixel.Alpha = 0; Output.SetPixel(i, j, NewPixel); } } Output.SetBitDepth(32); Output.WriteToFile("EasyBMPoutput32bpp.bmp"); Output.SetBitDepth(24); Output.WriteToFile("EasyBMPoutput24bpp.bmp"); Output.SetBitDepth(8); Output.WriteToFile("EasyBMPoutput8bpp.bmp"); Output.SetBitDepth(4); Output.WriteToFile("EasyBMPoutput4bpp.bmp"); Output.SetBitDepth(1); Output.WriteToFile("EasyBMPoutput1bpp.bmp"); Output.SetBitDepth(24); Rescale(Output, 'p', 50); Output.WriteToFile("EasyBMPoutput24bpp_rescaled.bmp"); /* and clean up memory */ nifti_image_free(nim); return 0; }
int main(int argc, char ** argv) { //----------------------- // Input pointers float *h_fMRI_Volumes = NULL; float *h_Quadrature_Filter_1_Real = NULL; float *h_Quadrature_Filter_2_Real = NULL; float *h_Quadrature_Filter_3_Real = NULL; float *h_Quadrature_Filter_1_Imag = NULL; float *h_Quadrature_Filter_2_Imag = NULL; float *h_Quadrature_Filter_3_Imag = NULL; void *allMemoryPointers[500]; int numberOfMemoryPointers = 0; // Default parameters int MOTION_CORRECTION_FILTER_SIZE = 7; int NUMBER_OF_ITERATIONS_FOR_MOTION_CORRECTION = 5; int OPENCL_PLATFORM = 2; int OPENCL_DEVICE = 0; int NUMBER_OF_MOTION_CORRECTION_PARAMETERS = 6; bool DEBUG = false; //bool DEBUG = true; const char* FILENAME_EXTENSION = "_mc"; bool PRINT = true; int DATA_W, DATA_H, DATA_D, DATA_T; float EPI_VOXEL_SIZE_X, EPI_VOXEL_SIZE_Y, EPI_VOXEL_SIZE_Z; //----------------------- // Output parameters const char *outputFilename; float *h_Quadrature_Filter_Response_1_Real = NULL; float *h_Quadrature_Filter_Response_1_Imag = NULL; float *h_Quadrature_Filter_Response_2_Real = NULL; float *h_Quadrature_Filter_Response_2_Imag = NULL; float *h_Quadrature_Filter_Response_3_Real = NULL; float *h_Quadrature_Filter_Response_3_Imag = NULL; float *h_Phase_Differences = NULL; float *h_Phase_Certainties = NULL; float *h_Phase_Gradients = NULL; float *h_Motion_Corrected_fMRI_Volumes = NULL; float *h_Motion_Parameters = NULL; //--------------------- /* Input arguments */ FILE *fp = NULL; // No inputs, so print help text if (argc == 1) { printf("Usage:\n\n"); printf("MotionCorrection input.nii [options]\n\n"); printf("Options:\n\n"); printf("-platform The OpenCL platform to use (default 0) \n"); printf("-device The OpenCL device to use for the specificed platform (default 0) \n"); printf("-iterations Number of iterations for the motion correction algorithm (default 5) \n"); printf("-output Set output filename (default input_mc.nii) \n"); printf("-quiet Don't print anything to the terminal (default false) \n"); printf("-debug Get additional debug information (default no) \n"); printf("\n\n"); return 1; } // Try to open file else if (argc > 1) { fp = fopen(argv[1],"r"); if (fp == NULL) { printf("Could not open file %s !\n",argv[1]); return -1; } fclose(fp); } // Loop over additional inputs int i = 2; while (i < argc) { char *input = argv[i]; char *p; if (strcmp(input,"-platform") == 0) { OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10); if (OPENCL_PLATFORM < 0) { printf("OpenCL platform must be >= 0!\n"); return -1; } i += 2; } else if (strcmp(input,"-device") == 0) { OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10); if (OPENCL_DEVICE < 0) { printf("OpenCL device must be >= 0!\n"); return -1; } i += 2; } else if (strcmp(input,"-iterations") == 0) { NUMBER_OF_ITERATIONS_FOR_MOTION_CORRECTION = (int)strtol(argv[i+1], &p, 10); if (NUMBER_OF_ITERATIONS_FOR_MOTION_CORRECTION <= 0) { printf("Number of iterations must be a positive number!\n"); return -1; } i += 2; } else if (strcmp(input,"-debug") == 0) { DEBUG = true; i += 1; } else if (strcmp(input,"-quiet") == 0) { PRINT = false; i += 1; } else if (strcmp(input,"-output") == 0) { outputFilename = argv[i+1]; i += 2; } else { printf("Unrecognized option! %s \n",argv[i]); return -1; } } // Read data nifti_image *inputData = nifti_image_read(argv[1],1); if (inputData == NULL) { printf("Could not open nifti file!\n"); return -1; } // Get data dimensions from input data DATA_W = inputData->nx; DATA_H = inputData->ny; DATA_D = inputData->nz; DATA_T = inputData->nt; // Get voxel sizes from input data EPI_VOXEL_SIZE_X = inputData->dx; EPI_VOXEL_SIZE_Y = inputData->dy; EPI_VOXEL_SIZE_Z = inputData->dz; // Calculate size, in bytes int DATA_SIZE = DATA_W * DATA_H * DATA_D * DATA_T * sizeof(float); int MOTION_PARAMETERS_SIZE = NUMBER_OF_MOTION_CORRECTION_PARAMETERS * DATA_T * sizeof(float); int FILTER_SIZE = MOTION_CORRECTION_FILTER_SIZE * MOTION_CORRECTION_FILTER_SIZE * MOTION_CORRECTION_FILTER_SIZE * sizeof(float); int VOLUME_SIZE = DATA_W * DATA_H * DATA_D * sizeof(float); // Print some info if (PRINT) { printf("Authored by K.A. Eklund \n"); printf("OpenCL Platform: %i OpenCL Device %i\n", OPENCL_PLATFORM, OPENCL_DEVICE); printf("Data size: %i x %i x %i x %i \n", DATA_W, DATA_H, DATA_D, DATA_T); printf("Voxel size: %f x %f x %f mm \n", EPI_VOXEL_SIZE_X, EPI_VOXEL_SIZE_Y, EPI_VOXEL_SIZE_Z); printf("Number of iterations for motion correction: %i \n", NUMBER_OF_ITERATIONS_FOR_MOTION_CORRECTION); } // ------------------------------------------------ // Allocate memory on the host if (!AllocateMemory(h_fMRI_Volumes, DATA_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Motion_Corrected_fMRI_Volumes, DATA_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_1_Real, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_1_Imag, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_2_Real, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_2_Imag, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_3_Real, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_3_Imag, FILTER_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Motion_Parameters, MOTION_PARAMETERS_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (DEBUG) { if (!AllocateMemory(h_Quadrature_Filter_Response_1_Real, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_Response_1_Imag, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_Response_2_Real, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_Response_2_Imag, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_Response_3_Real, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Quadrature_Filter_Response_3_Imag, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Phase_Differences, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Phase_Certainties, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } if (!AllocateMemory(h_Phase_Gradients, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers)) { FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } } // Convert data to floats if ( inputData->datatype == DT_SIGNED_SHORT ) { short int *p = (short int*)inputData->data; for (int i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++) { h_fMRI_Volumes[i] = (float)p[i]; } } else { printf("Unknown data type in input data, aborting!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } // Read quadrature filters, three real valued and three imaginary valued fp = fopen("filter1_real_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_1_Real,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter1_real_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } fp = fopen("filter1_imag_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_1_Imag,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter1_imag_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } fp = fopen("filter2_real_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_2_Real,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter2_real_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } fp = fopen("filter2_imag_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_2_Imag,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter2_imag_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } fp = fopen("filter3_real_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_3_Real,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter3_real_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } fp = fopen("filter3_imag_parametric_registration.bin","rb"); if (fp != NULL) { fread(h_Quadrature_Filter_3_Imag,sizeof(float),MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE*MOTION_CORRECTION_FILTER_SIZE,fp); fclose(fp); } else { printf("Could not open filter3_imag_parametric_registration.bin \n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } //------------------------ BROCCOLI_LIB BROCCOLI(OPENCL_PLATFORM,OPENCL_DEVICE); // Something went wrong... if (BROCCOLI.GetOpenCLInitiated() == 0) { printf("Get platform IDs error is %d \n",BROCCOLI.GetOpenCLPlatformIDsError()); printf("Get device IDs error is %d \n",BROCCOLI.GetOpenCLDeviceIDsError()); printf("Create context error is %d \n",BROCCOLI.GetOpenCLCreateContextError()); printf("Get create context info error is %d \n",BROCCOLI.GetOpenCLContextInfoError()); printf("Create command queue error is %d \n",BROCCOLI.GetOpenCLCreateCommandQueueError()); printf("Create program error is %d \n",BROCCOLI.GetOpenCLCreateProgramError()); printf("Build program error is %d \n",BROCCOLI.GetOpenCLBuildProgramError()); printf("Get program build info error is %d \n",BROCCOLI.GetOpenCLProgramBuildInfoError()); // Print create kernel errors int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (createKernelErrors[i] != 0) { printf("Create kernel error %i is %d \n",i,createKernelErrors[i]); } } // Print build info to file fp = fopen("buildinfo.txt","w"); if (fp == NULL) { printf("Could not open buildinfo.txt! \n"); } if (BROCCOLI.GetOpenCLBuildInfoChar() != NULL) { int error = fputs(BROCCOLI.GetOpenCLBuildInfoChar(),fp); if (error == EOF) { printf("Could not write to buildinfo.txt! \n"); } } fclose(fp); printf("OpenCL initialization failed, aborting! \nSee buildinfo.txt for output of OpenCL compilation!\n"); FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return -1; } // Initialization OK else if (BROCCOLI.GetOpenCLInitiated() == 1) { // Set all necessary pointers and values BROCCOLI.SetInputfMRIVolumes(h_fMRI_Volumes); BROCCOLI.SetEPIWidth(DATA_W); BROCCOLI.SetEPIHeight(DATA_H); BROCCOLI.SetEPIDepth(DATA_D); BROCCOLI.SetEPITimepoints(DATA_T); BROCCOLI.SetEPIVoxelSizeX(EPI_VOXEL_SIZE_X); BROCCOLI.SetEPIVoxelSizeY(EPI_VOXEL_SIZE_Y); BROCCOLI.SetEPIVoxelSizeZ(EPI_VOXEL_SIZE_Z); BROCCOLI.SetImageRegistrationFilterSize(MOTION_CORRECTION_FILTER_SIZE); BROCCOLI.SetParametricImageRegistrationFilters(h_Quadrature_Filter_1_Real, h_Quadrature_Filter_1_Imag, h_Quadrature_Filter_2_Real, h_Quadrature_Filter_2_Imag, h_Quadrature_Filter_3_Real, h_Quadrature_Filter_3_Imag); BROCCOLI.SetNumberOfIterationsForMotionCorrection(NUMBER_OF_ITERATIONS_FOR_MOTION_CORRECTION); BROCCOLI.SetOutputMotionCorrectedfMRIVolumes(h_Motion_Corrected_fMRI_Volumes); BROCCOLI.SetOutputMotionParameters(h_Motion_Parameters); if (DEBUG) { //BROCCOLI.SetOutputQuadratureFilterResponses(h_Quadrature_Filter_Response_1_Real, h_Quadrature_Filter_Response_1_Imag, h_Quadrature_Filter_Response_2_Real, h_Quadrature_Filter_Response_2_Imag, h_Quadrature_Filter_Response_3_Real, h_Quadrature_Filter_Response_3_Imag); BROCCOLI.SetOutputPhaseDifferences(h_Phase_Differences); BROCCOLI.SetOutputPhaseCertainties(h_Phase_Certainties); BROCCOLI.SetOutputPhaseGradients(h_Phase_Gradients); } // Run the actual motion correction BROCCOLI.PerformMotionCorrectionWrapper(); // Print create buffer errors int* createBufferErrors = BROCCOLI.GetOpenCLCreateBufferErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (createBufferErrors[i] != 0) { printf("Create buffer error %i is %d \n",i,createBufferErrors[i]); } } // Print run kernel errors int* runKernelErrors = BROCCOLI.GetOpenCLRunKernelErrors(); for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++) { if (runKernelErrors[i] != 0) { printf("Run kernel error %i is %d \n",i,runKernelErrors[i]); } } } // Find max displacement float maxDisplacement = 0.0f; int maxVolume = 0; for (int t = 1; t < DATA_T; t++) { float displacement = fabs(h_Motion_Parameters[t + 0*DATA_T]) + fabs(h_Motion_Parameters[t + 1*DATA_T]) + fabs(h_Motion_Parameters[t + 2*DATA_T]) + fabs(h_Motion_Parameters[t + 3*DATA_T]) + fabs(h_Motion_Parameters[t + 4*DATA_T]) + fabs(h_Motion_Parameters[t + 5*DATA_T]); if (displacement > maxDisplacement) { maxDisplacement = displacement; maxVolume = t; } } if (PRINT) { printf("Max displacement = %f (mm) at volume %i \n",maxDisplacement,maxVolume); } // Print motion parameters to file std::ofstream motion; motion.open("motion.1D"); if ( motion.good() ) { //motion.setf(ios::scientific); motion.precision(6); for (int t = 0; t < DATA_T; t++) { //printf("X translation for timepoint %i is %f\n",t+1,h_Motion_Parameters[t + DATA_T]); //motion << h_Motion_Parameters[t + 0*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 1*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 2*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 3*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 4*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 5*DATA_T] << std::endl; motion << h_Motion_Parameters[t + 4*DATA_T] << std::setw(2) << " " << -h_Motion_Parameters[t + 3*DATA_T] << std::setw(2) << " " << h_Motion_Parameters[t + 5*DATA_T] << std::setw(2) << " " << -h_Motion_Parameters[t + 2*DATA_T] << std::setw(2) << " " << -h_Motion_Parameters[t + 0*DATA_T] << std::setw(2) << " " << -h_Motion_Parameters[t + 1*DATA_T] << std::endl; } motion.close(); } else { printf("Could not open motion.1D for writing!\n"); } // Write motion corrected data to file WriteNifti(inputData,h_Motion_Corrected_fMRI_Volumes,FILENAME_EXTENSION,ADD_FILENAME,DONT_CHECK_EXISTING_FILE); if (DEBUG) { WriteNifti(inputData,h_Phase_Differences,"_phase_differences",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Phase_Gradients,"_phase_gradients",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Phase_Certainties,"_phase_certainties",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_1_Real,"_quadrature_filter_responses_1_real",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_1_Imag,"_quadrature_filter_responses_1_imag",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_2_Real,"_quadrature_filter_responses_2_real",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_2_Imag,"_quadrature_filter_responses_2_imag",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_3_Real,"_quadrature_filter_responses_3_real",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); WriteNifti(inputData,h_Quadrature_Filter_Response_3_Imag,"_quadrature_filter_responses_3_imag",ADD_FILENAME,DONT_CHECK_EXISTING_FILE); } // Free all memory FreeAllMemory(allMemoryPointers,numberOfMemoryPointers); nifti_image_free(inputData); return 1; }