示例#1
0
void reg_f3d_gpu<T>::AllocateWarped()
{
#ifndef NDEBUG
    printf("[NiftyReg DEBUG] reg_f3d_gpu<T>::AllocateWarped called.\n");
#endif
    if(this->currentReference==NULL){
        printf("[NiftyReg ERROR] Error when allocating the warped image.\n");
        exit(1);
    }
    this->ClearWarped();
    this->warped = nifti_copy_nim_info(this->currentReference);
    this->warped->dim[0]=this->warped->ndim=this->currentFloating->ndim;
    this->warped->dim[4]=this->warped->nt=this->currentFloating->nt;
    this->warped->pixdim[4]=this->warped->dt=1.0;
    this->warped->nvox = this->warped->nx *
                        this->warped->ny *
                        this->warped->nz *
                        this->warped->nt;
    this->warped->datatype = this->currentFloating->datatype;
    this->warped->nbyper = this->currentFloating->nbyper;
    NR_CUDA_SAFE_CALL(cudaMallocHost(&(this->warped->data), this->warped->nvox*this->warped->nbyper))
    if(this->warped->nt==1){
        if(cudaCommon_allocateArrayToDevice<float>(&this->warped_gpu, this->warped->dim)){
            printf("[NiftyReg ERROR] Error when allocating the warped image.\n");
            exit(1);
        }
    }
    else if(this->warped->nt==2){
        if(cudaCommon_allocateArrayToDevice<float>(&this->warped_gpu, &this->warped2_gpu, this->warped->dim)){
            printf("[NiftyReg ERROR] Error when allocating the warped image.\n");
            exit(1);
        }
    }
    else{
        printf("[NiftyReg ERROR] reg_f3d_gpu does not handle more than 2 time points in the floating image.\n");
        exit(1);
    }
#ifndef NDEBUG
    printf("[NiftyReg DEBUG] reg_f3d_gpu<T>::AllocateWarped done.\n");
#endif
    return;
}
示例#2
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;
}
示例#3
0
int main(int argc, char ** argv)
{
    //-----------------------
    // Input pointers

    float           *h_fMRI_Volumes = NULL;
    float           *h_Certainty = NULL;

    //--------------

    void*           allMemoryPointers[500];
    for (int i = 0; i < 500; i++)
    {
        allMemoryPointers[i] = NULL;
    }

    nifti_image*	allNiftiImages[500];
    for (int i = 0; i < 500; i++)
    {
        allNiftiImages[i] = NULL;
    }

    int             numberOfMemoryPointers = 0;
    int				numberOfNiftiImages = 0;

    size_t			allocatedHostMemory = 0;

    //--------------

    // Default parameters
    int             OPENCL_PLATFORM = 0;
    int             OPENCL_DEVICE = 0;
    bool            DEBUG = false;
    const char*     FILENAME_EXTENSION = "_sm";
    bool            PRINT = true;
    bool			VERBOS = false;

    size_t          DATA_W, DATA_H, DATA_D, DATA_T;
    float           EPI_VOXEL_SIZE_X, EPI_VOXEL_SIZE_Y, EPI_VOXEL_SIZE_Z;

    bool			CHANGE_OUTPUT_FILENAME = false;

    // Settings

    float           EPI_SMOOTHING_AMOUNT = 6.0f;
    bool			MASK = false;
    bool			AUTO_MASK = false;
    const char*		MASK_NAME;

    //-----------------------
    // Output parameters

    const char      *outputFilename;

    //---------------------

    /* Input arguments */
    FILE *fp = NULL;

    // No inputs, so print help text
    if (argc == 1)
    {
        printf("Usage:\n\n");
        printf("Smoothing 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(" -fwhm            Amount of smoothing to apply (in mm, default 6 mm) \n");
        printf(" -mask            Perform smoothing inside mask (normalized convolution) \n");
        printf(" -automask        Generate a mask and perform smoothing inside mask (normalized convolution) \n");
        printf(" -output          Set output filename (default input_sm.nii) \n");
        printf(" -quiet           Don't print anything to the terminal (default false) \n");
        printf(" -verbose         Print extra stuff (default false) \n");
        printf("\n\n");

        return EXIT_SUCCESS;
    }
    // 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 EXIT_FAILURE;
        }
        fclose(fp);
    }

    // Loop over additional inputs
    int i = 2;
    while (i < argc)
    {
        char *input = argv[i];
        char *p;
        if (strcmp(input,"-platform") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -platform !\n");
                return EXIT_FAILURE;
            }

            OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10);

            if (!isspace(*p) && *p != 0)
            {
                printf("OpenCL platform must be an integer! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if (OPENCL_PLATFORM < 0)
            {
                printf("OpenCL platform must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-device") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -device !\n");
                return EXIT_FAILURE;
            }

            OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10);

            if (!isspace(*p) && *p != 0)
            {
                printf("OpenCL device must be an integer! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if (OPENCL_DEVICE < 0)
            {
                printf("OpenCL device must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-fwhm") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read value after -fwhm !\n");
                return EXIT_FAILURE;
            }

            EPI_SMOOTHING_AMOUNT = (float)strtod(argv[i+1], &p);

            if (!isspace(*p) && *p != 0)
            {
                printf("Smoothing must be a float! You provided %s \n",argv[i+1]);
                return EXIT_FAILURE;
            }
            else if ( EPI_SMOOTHING_AMOUNT <= 0.0f )
            {
                printf("Smoothing must be > 0.0 !\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-mask") == 0)
        {
            if ( (i+1) >= argc  )
            {
                printf("Unable to read name after -mask !\n");
                return EXIT_FAILURE;
            }

            MASK = true;
            MASK_NAME = argv[i+1];
            i += 2;
        }
        else if (strcmp(input,"-automask") == 0)
        {
            AUTO_MASK = true;
            i += 1;
        }
        else if (strcmp(input,"-debug") == 0)
        {
            DEBUG = true;
            i += 1;
        }
        else if (strcmp(input,"-quiet") == 0)
        {
            PRINT = false;
            i += 1;
        }
        else if (strcmp(input,"-verbose") == 0)
        {
            VERBOS = true;
            i += 1;
        }
        else if (strcmp(input,"-output") == 0)
        {
            CHANGE_OUTPUT_FILENAME = true;

            if ( (i+1) >= argc  )
            {
                printf("Unable to read name after -output !\n");
                return EXIT_FAILURE;
            }

            outputFilename = argv[i+1];
            i += 2;
        }
        else
        {
            printf("Unrecognized option! %s \n",argv[i]);
            return EXIT_FAILURE;
        }
    }

    // Check if BROCCOLI_DIR variable is set
    if (getenv("BROCCOLI_DIR") == NULL)
    {
        printf("The environment variable BROCCOLI_DIR is not set!\n");
        return EXIT_FAILURE;
    }

    double startTime = GetWallTime();

    // ---------------------
    // Read data
    // ---------------------
    nifti_image *inputData = nifti_image_read(argv[1],1);

    if (inputData == NULL)
    {
        printf("Could not open nifti file!\n");
        return EXIT_FAILURE;
    }
    allNiftiImages[numberOfNiftiImages] = inputData;
    numberOfNiftiImages++;

    // -----------------------
    // Read mask
    // -----------------------

    nifti_image *inputMask;
    if (MASK)
    {
        inputMask = nifti_image_read(MASK_NAME,1);
        if (inputMask == NULL)
        {
            printf("Could not open mask volume!\n");
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
        allNiftiImages[numberOfNiftiImages] = inputMask;
        numberOfNiftiImages++;
    }

    double endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to read the nifti file\n",(float)(endTime - startTime));
    }

    // Get data dimensions
    DATA_W = inputData->nx;
    DATA_H = inputData->ny;
    DATA_D = inputData->nz;
    DATA_T = inputData->nt;

    // Check if mask volume has the same dimensions as the data
    if (MASK)
    {
        size_t TEMP_DATA_W = inputMask->nx;
        size_t TEMP_DATA_H = inputMask->ny;
        size_t TEMP_DATA_D = inputMask->nz;

        if ( (TEMP_DATA_W != DATA_W) || (TEMP_DATA_H != DATA_H) || (TEMP_DATA_D != DATA_D) )
        {
            printf("Input data has the dimensions %zu x %zu x %zu, while the mask volume has the dimensions %zu x %zu x %zu. Aborting! \n",DATA_W,DATA_H,DATA_D,TEMP_DATA_W,TEMP_DATA_H,TEMP_DATA_D);
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
    }

    // Get voxel sizes
    EPI_VOXEL_SIZE_X = inputData->dx;
    EPI_VOXEL_SIZE_Y = inputData->dy;
    EPI_VOXEL_SIZE_Z = inputData->dz;

    // Calculate size, in bytes
    size_t DATA_SIZE = DATA_W * DATA_H * DATA_D * DATA_T * sizeof(float);
    size_t VOLUME_SIZE = DATA_W * DATA_H * DATA_D * sizeof(float);

    // Print some info
    if (PRINT)
    {
        printf("Authored by K.A. Eklund \n");
        printf("Data size: %zu x %zu x %zu x %zu \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("Smoothing filter size: %f mm \n", EPI_SMOOTHING_AMOUNT);
    }

    // ------------------------------------------------

    // Allocate memory on the host

    startTime = GetWallTime();

    // If the data is in float format, we can just copy the pointer
    if ( inputData->datatype != DT_FLOAT )
    {
        AllocateMemory(h_fMRI_Volumes, DATA_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, allocatedHostMemory, "INPUT_DATA");
    }
    else
    {
        allocatedHostMemory += DATA_SIZE;
    }
    AllocateMemory(h_Certainty, VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, allocatedHostMemory, "CERTAINTY");

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to allocate memory\n",(float)(endTime - startTime));
    }

    startTime = GetWallTime();

    // Convert data to floats
    if ( inputData->datatype == DT_SIGNED_SHORT )
    {
        short int *p = (short int*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT8 )
    {
        unsigned char *p = (unsigned char*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT16 )
    {
        unsigned short int *p = (unsigned short int*)inputData->data;

        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        {
            h_fMRI_Volumes[i] = (float)p[i];
        }
    }
    // Correct data type, just copy the pointer
    else if ( inputData->datatype == DT_FLOAT )
    {
        h_fMRI_Volumes = (float*)inputData->data;

        // Save the pointer in the pointer list
        allMemoryPointers[numberOfMemoryPointers] = (void*)h_fMRI_Volumes;
        numberOfMemoryPointers++;

        //float *p = (float*)inputData->data;

        //for (size_t i = 0; i < DATA_W * DATA_H * DATA_D * DATA_T; i++)
        //{
        //    h_fMRI_Volumes[i] = p[i];
        //}
    }
    else
    {
        printf("Unknown data type in input data, aborting!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }

    // Free input fMRI data, it has been converted to floats
    if ( inputData->datatype != DT_FLOAT )
    {
        free(inputData->data);
        inputData->data = NULL;
    }
    // Pointer has been copied to h_fMRI_Volumes and pointer list, so set the input data pointer to NULL
    else
    {
        inputData->data = NULL;
    }

    // Mask is provided by user
    if (MASK)
    {
        if ( inputMask->datatype == DT_SIGNED_SHORT )
        {
            short int *p = (short int*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else if ( inputMask->datatype == DT_UINT16 )
        {
            unsigned short int *p = (unsigned short int*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else if ( inputMask->datatype == DT_FLOAT )
        {
            float *p = (float*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = p[i];
            }
        }
        else if ( inputMask->datatype == DT_UINT8 )
        {
            unsigned char *p = (unsigned char*)inputMask->data;

            for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
            {
                h_Certainty[i] = (float)p[i];
            }
        }
        else
        {
            printf("Unknown data type in mask volume, aborting!\n");
            FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
            FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
            return EXIT_FAILURE;
        }
    }
    // Mask is NOT provided by user, set all mask voxels to 1
    else
    {
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Certainty[i] = 1.0f;
        }
    }

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to convert data to floats\n",(float)(endTime - startTime));
    }

    //------------------------

    startTime = GetWallTime();

    // Initialize BROCCOLI
    BROCCOLI_LIB BROCCOLI(OPENCL_PLATFORM,OPENCL_DEVICE,2,VERBOS); // 2 = Bash wrapper

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to initiate BROCCOLI\n",(float)(endTime - startTime));
    }

    // Print build info to file (always)
    std::vector<std::string> buildInfo = BROCCOLI.GetOpenCLBuildInfo();
    std::vector<std::string> kernelFileNames = BROCCOLI.GetKernelFileNames();

    std::string buildInfoPath;
    buildInfoPath.append(getenv("BROCCOLI_DIR"));
    buildInfoPath.append("compiled/Kernels/");

    for (int k = 0; k < BROCCOLI.GetNumberOfKernelFiles(); k++)
    {
        std::string temp = buildInfoPath;
        temp.append("buildInfo_");
        temp.append(BROCCOLI.GetOpenCLPlatformName());
        temp.append("_");
        temp.append(BROCCOLI.GetOpenCLDeviceName());
        temp.append("_");
        std::string name = kernelFileNames[k];
        // Remove "kernel" and ".cpp" from kernel filename
        name = name.substr(0,name.size()-4);
        name = name.substr(6,name.size());
        temp.append(name);
        temp.append(".txt");
        fp = fopen(temp.c_str(),"w");
        if (fp == NULL)
        {
            printf("Could not open %s for writing ! \n",temp.c_str());
        }
        else
        {
            if (buildInfo[k].c_str() != NULL)
            {
                int error = fputs(buildInfo[k].c_str(),fp);
                if (error == EOF)
                {
                    printf("Could not write to %s ! \n",temp.c_str());
                }
            }
            fclose(fp);
        }
    }

    // Something went wrong...
    if (!BROCCOLI.GetOpenCLInitiated())
    {
        printf("Initialization error is \"%s\" \n",BROCCOLI.GetOpenCLInitializationError().c_str());
        printf("OpenCL error is \"%s\" \n",BROCCOLI.GetOpenCLError());

        // Print create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[i]));
            }
        }

        printf("OpenCL initialization failed, aborting! \nSee buildInfo* for output of OpenCL compilation!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }
    // Initialization OK
    else
    {
        // Set all necessary pointers and values
        BROCCOLI.SetInputfMRIVolumes(h_fMRI_Volumes);
        BROCCOLI.SetAutoMask(AUTO_MASK);
        BROCCOLI.SetInputCertainty(h_Certainty);

        BROCCOLI.SetEPISmoothingAmount(EPI_SMOOTHING_AMOUNT);
        BROCCOLI.SetAllocatedHostMemory(allocatedHostMemory);

        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);

        // Run the actual slice timing correction
        startTime = GetWallTime();
        BROCCOLI.PerformSmoothingNormalizedHostWrapper();
        endTime = GetWallTime();

        if (VERBOS)
        {
            printf("\nIt took %f seconds to run the smoothing\n",(float)(endTime - startTime));
        }

        // 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 create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[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 for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(runKernelErrors[i]));
            }
        }
    }

    // Write results to file
    startTime = GetWallTime();

    if (!CHANGE_OUTPUT_FILENAME)
    {
        WriteNifti(inputData,h_fMRI_Volumes,FILENAME_EXTENSION,ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
    }
    else
    {
        nifti_set_filenames(inputData, outputFilename, 0, 1);
        WriteNifti(inputData,h_fMRI_Volumes,"",DONT_ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
    }

    if (AUTO_MASK)
    {
        nifti_image *outputNiftifMRISingleVolume = nifti_copy_nim_info(inputData);
        outputNiftifMRISingleVolume->nt = 1;
        outputNiftifMRISingleVolume->dim[0] = 3;
        outputNiftifMRISingleVolume->dim[4] = 1;
        outputNiftifMRISingleVolume->nvox = DATA_W * DATA_H * DATA_D;
        allNiftiImages[numberOfNiftiImages] = outputNiftifMRISingleVolume;
        numberOfNiftiImages++;

        if (!CHANGE_OUTPUT_FILENAME)
        {
            WriteNifti(outputNiftifMRISingleVolume,h_Certainty,"_mask",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
        }
        else
        {
            nifti_set_filenames(outputNiftifMRISingleVolume, outputFilename, 0, 1);
            WriteNifti(outputNiftifMRISingleVolume,h_Certainty,"_mask",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
        }
    }

    endTime = GetWallTime();

    if (VERBOS)
    {
        printf("It took %f seconds to write the nifti file\n",(float)(endTime - startTime));
    }

    // Free all memory
    FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
    FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);

    return EXIT_SUCCESS;
}
示例#4
0
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;
}
示例#5
0
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;
    }                        
}
示例#6
0
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;
	nifti_image*	allNiftiImages[500];
	int				numberOfNiftiImages = 0;		
    
    // Default parameters
        
    int             OPENCL_PLATFORM = 0;
    int             OPENCL_DEVICE = 0;
	int				INTERPOLATION_MODE = 1;
    bool            DEBUG = false;
    bool            PRINT = true;
	bool			CHANGE_OUTPUT_NAME = false;    
	int 			MM_T1_Z_CUT = 0;

	const char*		outputFilename;

	bool			VERBOS = false;

    // 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(" -interpolation             The interpolation to use, 0 = nearest, 1 = trilinear (default 1) \n");
		printf(" -zcut                      Number of mm to cut from the bottom of the input volume, can be negative (default 0). Should be the same as for the call to RegisterTwoVolumes\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 EXIT_SUCCESS;
    }
    else if (argc < 6)
    {
        printf("Need one volume to warp, one reference volume and three displacement field volumes!\n\n");
		return EXIT_FAILURE;
    }
    // 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 EXIT_FAILURE;
        }
        fclose(fp);     
        
        fp = fopen(argv[2],"r");
        if (fp == NULL)
        {
            printf("Could not open file %s !\n",argv[2]);
            return EXIT_FAILURE;
        }
        fclose(fp);   

        fp = fopen(argv[3],"r");
        if (fp == NULL)
        {
            printf("Could not open file %s !\n",argv[3]);
            return EXIT_FAILURE;
        }
        fclose(fp);   

        fp = fopen(argv[4],"r");
        if (fp == NULL)
        {
            printf("Could not open file %s !\n",argv[4]);
            return EXIT_FAILURE;
        }
        fclose(fp);   

        fp = fopen(argv[5],"r");
        if (fp == NULL)
        {
            printf("Could not open file %s !\n",argv[5]);
            return EXIT_FAILURE;
        }
        fclose(fp);            
    }
    
    // Loop over additional inputs
    int i = 6;
    while (i < argc)
    {
        char *input = argv[i];
        char *p;
        if (strcmp(input,"-platform") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -platform !\n");
                return EXIT_FAILURE;
			}

            OPENCL_PLATFORM = (int)strtol(argv[i+1], &p, 10);

			if (!isspace(*p) && *p != 0)
		    {
		        printf("OpenCL platform must be an integer! You provided %s \n",argv[i+1]);
				return EXIT_FAILURE;
		    }
            else if (OPENCL_PLATFORM < 0)
            {
                printf("OpenCL platform must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
        else if (strcmp(input,"-device") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -device !\n");
                return EXIT_FAILURE;
			}

            OPENCL_DEVICE = (int)strtol(argv[i+1], &p, 10);

			if (!isspace(*p) && *p != 0)
		    {
		        printf("OpenCL device must be an integer! You provided %s \n",argv[i+1]);
				return EXIT_FAILURE;
		    }
            else if (OPENCL_DEVICE < 0)
            {
                printf("OpenCL device must be >= 0!\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }
		else if (strcmp(input,"-interpolation") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -interpolation !\n");
                return EXIT_FAILURE;
			}

            INTERPOLATION_MODE = (int)strtol(argv[i+1], &p, 10);

			if (!isspace(*p) && *p != 0)
		    {
		        printf("Interpolation mode must be an integer! You provided %s \n",argv[i+1]);
				return EXIT_FAILURE;
		    }
			if ( (INTERPOLATION_MODE != 0) && (INTERPOLATION_MODE != 1) )
            {
			    printf("Interpolation mode has to be 0 or 1!\n");
                return EXIT_FAILURE;          	
			}
			i += 2;
        }      
        else if (strcmp(input,"-zcut") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -zcut !\n");
                return EXIT_FAILURE;
			}

            MM_T1_Z_CUT = (int)strtol(argv[i+1], &p, 10);

			if (!isspace(*p) && *p != 0)
		    {
		        printf("zcut must be an integer! You provided %s \n",argv[i+1]);
				return EXIT_FAILURE;
		    }

            i += 2;
        }
        else if (strcmp(input,"-quiet") == 0)
        {
            PRINT = false;
            i += 1;
        }
        else if (strcmp(input,"-output") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read name after -output !\n");
                return EXIT_FAILURE;
			}
			CHANGE_OUTPUT_NAME = true;
            outputFilename = argv[i+1];
            i += 2;
        }
        else
        {
            printf("Unrecognized option! %s \n",argv[i]);
            return EXIT_FAILURE;
        }                
    }
        
	// Check if BROCCOLI_DIR variable is set
	if (getenv("BROCCOLI_DIR") == NULL)
	{
        printf("The environment variable BROCCOLI_DIR is not set!\n");
        return EXIT_FAILURE;
	}

    // Read data
    nifti_image *inputVolume = nifti_image_read(argv[1],1);    
    if (inputVolume == NULL)
    {
        printf("Could not open volume to transform!\n");
        return EXIT_FAILURE;
    }
	allNiftiImages[numberOfNiftiImages] = inputVolume;
	numberOfNiftiImages++;

    nifti_image *referenceVolume = nifti_image_read(argv[2],1);    
    if (referenceVolume == NULL)
    {
        printf("Could not open reference volume!\n");
        return EXIT_FAILURE;
    }
   	allNiftiImages[numberOfNiftiImages] = referenceVolume;
	numberOfNiftiImages++;

    nifti_image *inputDisplacementX = nifti_image_read(argv[3],1);   
    if (inputDisplacementX == NULL)
    {
        printf("Could not open displacement X volume!\n");
        return EXIT_FAILURE;
    }
	allNiftiImages[numberOfNiftiImages] = inputDisplacementX;
	numberOfNiftiImages++;

    nifti_image *inputDisplacementY = nifti_image_read(argv[4],1);   
    if (inputDisplacementY == NULL)
    {
        printf("Could not open displacement Y volume!\n");
        return EXIT_FAILURE;
    }
	allNiftiImages[numberOfNiftiImages] = inputDisplacementY;
	numberOfNiftiImages++;

    nifti_image *inputDisplacementZ = nifti_image_read(argv[5],1);   
    if (inputDisplacementZ == NULL)
    {
        printf("Could not open displacement Z volume!\n");
        return EXIT_FAILURE;
    }
	allNiftiImages[numberOfNiftiImages] = inputDisplacementZ;
	numberOfNiftiImages++;
    
    // 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);
    }
           
    // ------------------------------------------------
    
    // Allocate memory on the host        

	AllocateMemory(h_Input_Volume, INPUT_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, "INPUT_VOLUME");
	AllocateMemory(h_Interpolated_Volume, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, "INTERPOLATED_VOLUME");
	AllocateMemory(h_Displacement_Field_X, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, "DISPLACEMENT_FIELD_X");
	AllocateMemory(h_Displacement_Field_Y, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, "DISPLACEMENT_FIELD_Y");
	AllocateMemory(h_Displacement_Field_Z, REFERENCE_VOLUME_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, "DISPLACEMENT_FIELD_Z");
			           
    // 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 if ( inputVolume->datatype == DT_UINT8 )
    {
        unsigned char *p = (unsigned char*)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
    {
        printf("Unknown data type in volume to transform, aborting!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }
    
    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);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }

    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);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }

    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);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }
            
    //------------------------
    
    BROCCOLI_LIB BROCCOLI(OPENCL_PLATFORM,OPENCL_DEVICE,2,VERBOS); // 2 = Bash wrapper    

    // Print build info to file (always)
	std::vector<std::string> buildInfo = BROCCOLI.GetOpenCLBuildInfo();
	std::vector<std::string> kernelFileNames = BROCCOLI.GetKernelFileNames();

	for (int k = 0; k < BROCCOLI.GetNumberOfKernelFiles(); k++)
	{
		std::string temp = "buildInfo";
		std::string name = kernelFileNames[k];
		// Remove "kernel" and ".cpp" from kernel filename
		name = name.substr(0,name.size()-4);
		name = name.substr(6,name.size());
		temp.append(name);
		temp.append(".txt");
		fp = fopen(temp.c_str(),"w");
		if (fp == NULL)
		{     
		    printf("Could not open %s for writing ! \n",temp.c_str());
		}
		else
		{	
			if (buildInfo[k].c_str() != NULL)
			{
			    int error = fputs(buildInfo[k].c_str(),fp);
			    if (error == EOF)
			    {
			        printf("Could not write to %s ! \n",temp.c_str());
			    }
			}
			fclose(fp);
		}
	}

    // Something went wrong...
    if ( !BROCCOLI.GetOpenCLInitiated() )
    {              
        printf("Initialization error is \"%s\" \n",BROCCOLI.GetOpenCLInitializationError().c_str());
		printf("OpenCL error is \"%s\" \n",BROCCOLI.GetOpenCLError());

        // Print create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[i]));
            }
        }                
                      
        printf("OpenCL initialization failed, aborting! \nSee buildInfo* for output of OpenCL compilation!\n");      
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }
    // Initialization OK
    else
    {
        // 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(MM_T1_Z_CUT); 
        BROCCOLI.SetInterpolationMode(INTERPOLATION_MODE);  

		BROCCOLI.SetOutputDisplacementField(h_Displacement_Field_X,h_Displacement_Field_Y,h_Displacement_Field_Z);      
        BROCCOLI.SetOutputInterpolatedT1Volume(h_Interpolated_Volume);
                
        if (DEBUG)
        {
            BROCCOLI.SetDebug(true);            
        }
                          
        // Run the actual transformation
        BROCCOLI.TransformVolumesNonLinearWrapper();
		
        // 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 create kernel errors
        int* createKernelErrors = BROCCOLI.GetOpenCLCreateKernelErrors();
        for (int i = 0; i < BROCCOLI.GetNumberOfOpenCLKernels(); i++)
        {
            if (createKernelErrors[i] != 0)
            {
                printf("Create kernel error for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(createKernelErrors[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 for kernel '%s' is '%s' \n",BROCCOLI.GetOpenCLKernelName(i),BROCCOLI.GetOpenCLErrorMessage(runKernelErrors[i]));
            }
        } 
    }        
   
    // Copy information from input data
	nifti_image* outputNifti = nifti_copy_nim_info(referenceVolume);    	
	allNiftiImages[numberOfNiftiImages] = outputNifti;
	numberOfNiftiImages++;    

	// Change filename and write transformed data to file
	if (!CHANGE_OUTPUT_NAME)
	{
    	nifti_set_filenames(outputNifti, inputVolume->fname, 0, 1);
	    WriteNifti(outputNifti,h_Interpolated_Volume,"_warped",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
	}
	else 
	{
    	nifti_set_filenames(outputNifti, outputFilename, 0, 1);    	
	    WriteNifti(outputNifti,h_Interpolated_Volume,"",ADD_FILENAME,DONT_CHECK_EXISTING_FILE);    
	}
                             
    // Free all memory
	FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);	   
	FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
    
	return EXIT_SUCCESS;
}
示例#7
0
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]);
    }
示例#8
0
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;
    }
示例#9
0
int main(int argc, char ** argv)
{
    //-----------------------
    // Input pointers
    
    float           *h_Volume = NULL;

	//--------------

    void*           allMemoryPointers[500];
	for (int i = 0; i < 500; i++)
	{
		allMemoryPointers[i] = NULL;
	}
    
	nifti_image*	allNiftiImages[500];
	for (int i = 0; i < 500; i++)
	{
		allNiftiImages[i] = NULL;
	}

    int             numberOfMemoryPointers = 0;
	int				numberOfNiftiImages = 0;

	size_t			allocatedHostMemory = 0;

	//--------------
  
    // Default parameters
    const char*     FILENAME_EXTENSION = "_roi";
    bool            PRINT = true;
	bool			VERBOS = false;
    
    size_t          DATA_W, DATA_H, DATA_D, DATA_T;
    float           VOXEL_SIZE_X, VOXEL_SIZE_Y, VOXEL_SIZE_Z;

	bool			CHANGE_OUTPUT_FILENAME = false;

	// Settings
	float			RADIUS = 5.0f;	
	float			RADIUSV = 5.0f;	

	float			XCOORDINATE = 0.0f;
	float			YCOORDINATE = 0.0f;
	float			ZCOORDINATE = 0.0f;

	float			XCOORDINATEV = 0.0f;
	float			YCOORDINATEV = 0.0f;
	float			ZCOORDINATEV = 0.0f;
	
	bool			MMRADIUS = false;
	bool			VOXELSRADIUS = false;

	bool			MMCOORDINATE = false;
	bool			VOXELSCOORDINATE = false;

    //-----------------------
    // Output parameters
    
    const char      *outputFilename;
       
    //---------------------
    
    /* Input arguments */
    FILE *fp = NULL; 
    
    // No inputs, so print help text
    if (argc == 1)
    {        
        printf("Usage:\n\n");
        printf("MakeROI input.nii [options]\n\n");
        printf("Options:\n\n");
        printf(" -coordinate      Center of ROI (x,y,z), in mm  \n");
        printf(" -coordinatev     Center of ROI (x,y,z), in voxels  \n");
        printf(" -radius          Radius of ROI, in millimeters \n");
        printf(" -radiusv         Radius of ROI, in voxels \n");
		printf(" -output      	  Set filename of nifti file  \n");
        printf("\n\n");
        
        return EXIT_SUCCESS;
    }
    // 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 EXIT_FAILURE;
        }
        fclose(fp);        
    }
    
    // Loop over additional inputs
    int i = 2;
    while (i < argc)
    {
        char *input = argv[i];
        char *p;
        if (strcmp(input,"-coordinate") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read first value after -coordinate !\n");
                return EXIT_FAILURE;
			}

			if ( (i+2) >= argc  )
			{
			    printf("Unable to read second value after -coordinate !\n");
                return EXIT_FAILURE;
			}

			if ( (i+3) >= argc  )
			{
			    printf("Unable to read third value after -coordinate !\n");
                return EXIT_FAILURE;
			}
            
			MMCOORDINATE = true;
            XCOORDINATE = (float)strtod(argv[i+1], &p);
			YCOORDINATE = (float)strtod(argv[i+2], &p);
			ZCOORDINATE = (float)strtod(argv[i+3], &p);
            
            i += 4;
        }        
        else if (strcmp(input,"-coordinatev") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read first value after -coordinatev !\n");
                return EXIT_FAILURE;
			}

			if ( (i+2) >= argc  )
			{
			    printf("Unable to read second value after -coordinatev !\n");
                return EXIT_FAILURE;
			}

			if ( (i+3) >= argc  )
			{
			    printf("Unable to read third value after -coordinatev !\n");
                return EXIT_FAILURE;
			}
            
			VOXELSCOORDINATE = true;
            XCOORDINATEV = (float)strtod(argv[i+1], &p);
			YCOORDINATEV = (float)strtod(argv[i+2], &p);
			ZCOORDINATEV = (float)strtod(argv[i+3], &p);
            
            i += 4;
        }        
        else if (strcmp(input,"-radius") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -radius !\n");
                return EXIT_FAILURE;
			}
            
            RADIUS = (float)strtod(argv[i+1], &p);
			MMRADIUS = true;
            
			if (!isspace(*p) && *p != 0)
		    {
		        printf("Radius must be a float! You provided %s \n",argv[i+1]);
				return EXIT_FAILURE;
		    }
  			else if ( RADIUS <= 0.0f )
            {
                printf("Radius must be > 0.0 !\n");
                return EXIT_FAILURE;
            }
            i += 2;
        } 
        else if (strcmp(input,"-radiusv") == 0)
        {
			if ( (i+1) >= argc  )
			{
			    printf("Unable to read value after -radiusv !\n");
                return EXIT_FAILURE;
			}
            
            RADIUSV = (float)strtod(argv[i+1], &p);
			VOXELSRADIUS = true;
            
  			if ( RADIUSV <= 0.0f )
            {
                printf("Radius must be > 0 !\n");
                return EXIT_FAILURE;
            }
            i += 2;
        }        
        else if (strcmp(input,"-output") == 0)
        {
			CHANGE_OUTPUT_FILENAME = true;

			if ( (i+1) >= argc  )
			{
			    printf("Unable to read name after -output !\n");
                return EXIT_FAILURE;
			}

            outputFilename = argv[i+1];
            i += 2;
        }
        else
        {
            printf("Unrecognized option! %s \n",argv[i]);
            return EXIT_FAILURE;
        }                
    }
    
    double startTime = GetWallTime();

    if (!MMCOORDINATE && !VOXELSCOORDINATE)
    {
        printf("Have to define center in mm or in voxels!\n");
        return EXIT_FAILURE;
    }
    if (MMCOORDINATE && VOXELSCOORDINATE)
    {
        printf("Cannot define center in both mm and in voxels!\n");
        return EXIT_FAILURE;
    }


    if (!MMRADIUS && !VOXELSRADIUS)
    {
        printf("Have to define radius in mm or in voxels!\n");
        return EXIT_FAILURE;
    }
    if (MMRADIUS && VOXELSRADIUS)
    {
        printf("Cannot define radius in both mm and in voxels!\n");
        return EXIT_FAILURE;
    }

	// ---------------------
    // Read data
	// ---------------------
    nifti_image *inputData = nifti_image_read(argv[1],1);
    
    if (inputData == NULL)
    {
        printf("Could not open nifti file!\n");
        return EXIT_FAILURE;
    }
    allNiftiImages[numberOfNiftiImages] = inputData;
	numberOfNiftiImages++;

	double endTime = GetWallTime();

	if (VERBOS)
 	{
		printf("It took %f seconds to read the nifti file\n",(float)(endTime - startTime));
	}

    // Get data dimensions
    DATA_W = inputData->nx;
    DATA_H = inputData->ny;
    DATA_D = inputData->nz;
    DATA_T = inputData->nt;

	XCOORDINATE = (float)DATA_W - XCOORDINATE - 1.0f;
	YCOORDINATE = (float)DATA_H - YCOORDINATE - 1.0f;

	if (VOXELSCOORDINATE)
	{
		//XCOORDINATEV = (float)DATA_W - XCOORDINATE - 1.0f;
		//YCOORDINATEV = (float)DATA_H - YCOORDINATE - 1.0f;
		//ZCOORDINATE -= 1.0f;
	}

    // Get voxel sizes
    VOXEL_SIZE_X = inputData->dx;
    VOXEL_SIZE_Y = inputData->dy;
    VOXEL_SIZE_Z = inputData->dz;
    	
    // Calculate size, in bytes
    size_t DATA_SIZE = DATA_W * DATA_H * DATA_D * sizeof(float);
    size_t VOLUME_SIZE = DATA_W * DATA_H * DATA_D * sizeof(float);
    
    // Print some info
    if (PRINT)
    {
        printf("Authored by K.A. Eklund \n");
        printf("Data size: %zu x %zu x %zu \n",  DATA_W, DATA_H, DATA_D);
        printf("Voxel size: %f x %f x %f mm \n", VOXEL_SIZE_X, VOXEL_SIZE_Y, VOXEL_SIZE_Z);   
    } 
   
    // ------------------------------------------------
    
    // Allocate memory on the host
    
	startTime = GetWallTime();

	AllocateMemory(h_Volume, DATA_SIZE, allMemoryPointers, numberOfMemoryPointers, allNiftiImages, numberOfNiftiImages, allocatedHostMemory, "INPUT_DATA");

	endTime = GetWallTime();
    
	if (VERBOS)
 	{
		printf("It took %f seconds to allocate memory\n",(float)(endTime - startTime));
	}

	startTime = GetWallTime();

    // Convert data to floats
    if ( inputData->datatype == DT_SIGNED_SHORT )
    {
        short int *p = (short int*)inputData->data;
    
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Volume[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT8 )
    {
        unsigned char *p = (unsigned char*)inputData->data;
    
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Volume[i] = (float)p[i];
        }
    }
    else if ( inputData->datatype == DT_UINT16 )
    {
        unsigned short int *p = (unsigned short int*)inputData->data;
    
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Volume[i] = (float)p[i];
        }
    }
	// Correct data type, just copy the pointer
	else if ( inputData->datatype == DT_FLOAT )
    {
        float *p = (float*)inputData->data;
    
        for (size_t i = 0; i < DATA_W * DATA_H * DATA_D; i++)
        {
            h_Volume[i] = p[i];
        }
    }
    else
    {
        printf("Unknown data type in input data, aborting!\n");
        FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);
        FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
        return EXIT_FAILURE;
    }

	endTime = GetWallTime();

	if (VERBOS)
 	{
		printf("It took %f seconds to convert data to floats\n",(float)(endTime - startTime));
	}

    //------------------------

	if (MMRADIUS)
	{
		for (int x = 0; x < DATA_W; x++)
		{
			for (int y = 0; y < DATA_H; y++)
			{
				for (int z = 0; z < DATA_D; z++)
				{
					float distance = sqrt( ((float) x - XCOORDINATE)*((float) x - XCOORDINATE)*VOXEL_SIZE_X*VOXEL_SIZE_X + ((float) y - YCOORDINATE)*((float) y - YCOORDINATE)*VOXEL_SIZE_Y*VOXEL_SIZE_Y + ((float) z - ZCOORDINATE)*((float) z - ZCOORDINATE)*VOXEL_SIZE_Z*VOXEL_SIZE_Z   );
					if ( distance <= RADIUS )
					{
						h_Volume[x + y * DATA_W + z * DATA_W * DATA_H] = 1.0f;
					}
					else
					{
						h_Volume[x + y * DATA_W + z * DATA_W * DATA_H] = 0.0f;
					}
				}
			}
		}
	}
	else if (VOXELSRADIUS)
	{
		for (int x = 0; x < DATA_W; x++)
		{
			for (int y = 0; y < DATA_H; y++)
			{
				for (int z = 0; z < DATA_D; z++)
				{
					float distance = sqrt( ((float) x - XCOORDINATE)*((float) x - XCOORDINATE) + ((float) y - YCOORDINATE)*((float) y - YCOORDINATE) + ((float) z - ZCOORDINATE)*((float) z - ZCOORDINATE) );
					if ( distance <= RADIUSV )
					{
						h_Volume[x + y * DATA_W + z * DATA_W * DATA_H] = 1.0f;
					}
					else
					{
						h_Volume[x + y * DATA_W + z * DATA_W * DATA_H] = 0.0f;
					}
				}
			}
		}
	}



    //------------------------
         
    // Write results to file            

    nifti_image *outputNifti = nifti_copy_nim_info(inputData);
    outputNifti->nt = 1;	
    outputNifti->dim[0] = 3;
    outputNifti->dim[4] = 1;
    outputNifti->nvox = DATA_W * DATA_H * DATA_D;
    allNiftiImages[numberOfNiftiImages] = outputNifti;
	numberOfNiftiImages++;

    startTime = GetWallTime();

	if (!CHANGE_OUTPUT_FILENAME)
	{
	    WriteNifti(outputNifti,h_Volume,FILENAME_EXTENSION,ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
	}
	else
	{
		nifti_set_filenames(outputNifti, outputFilename, 0, 1);
		WriteNifti(outputNifti,h_Volume,"",DONT_ADD_FILENAME,DONT_CHECK_EXISTING_FILE);
	}

	endTime = GetWallTime();

	if (VERBOS)
 	{
		printf("It took %f seconds to write the nifti file\n",(float)(endTime - startTime));
	}
    
    // Free all memory
    FreeAllMemory(allMemoryPointers,numberOfMemoryPointers);            
    FreeAllNiftiImages(allNiftiImages,numberOfNiftiImages);
    
    return EXIT_SUCCESS;
}
示例#10
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;
}