_reg_tools.cpp 103 KB
Newer Older
1 2 3 4 5
/**
 * @file _reg_tools.cpp
 * @author Marc Modat
 * @date 25/03/2009
 * @brief Set of useful functions
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 *  Copyright (c) 2009, University College London. All rights reserved.
 *  Centre for Medical Image Computing (CMIC)
 *  See the LICENSE.txt file in the nifty_reg root folder
 *
 */

#ifndef _REG_TOOLS_CPP
#define _REG_TOOLS_CPP

#include "_reg_tools.h"

/* *************************************************************** */
/* *************************************************************** */
void reg_checkAndCorrectDimension(nifti_image *image)
{
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
   // Ensure that no dimension is set to zero
   if(image->nx<1 || image->dim[1]<1) image->dim[1]=image->nx=1;
   if(image->ny<1 || image->dim[2]<1) image->dim[2]=image->ny=1;
   if(image->nz<1 || image->dim[3]<1) image->dim[3]=image->nz=1;
   if(image->nt<1 || image->dim[4]<1) image->dim[4]=image->nt=1;
   if(image->nu<1 || image->dim[5]<1) image->dim[5]=image->nu=1;
   if(image->nv<1 || image->dim[6]<1) image->dim[6]=image->nv=1;
   if(image->nw<1 || image->dim[7]<1) image->dim[7]=image->nw=1;
   // Set the slope to 1 if undefined
   if(image->scl_slope==0) image->scl_slope=1.f;
   // Ensure that no spacing is set to zero
   if(image->ny==1 && (image->dy==0 || image->pixdim[2]==0))
      image->dy=image->pixdim[2]=1;
   if(image->nz==1 && (image->dz==0 || image->pixdim[3]==0))
      image->dz=image->pixdim[3]=1;
   // Create the qform matrix if required
   if(image->qform_code==0 && image->sform_code==0)
   {
      image->qto_xyz=nifti_quatern_to_mat44(image->quatern_b,
                                            image->quatern_c,
                                            image->quatern_d,
                                            image->qoffset_x,
                                            image->qoffset_y,
                                            image->qoffset_z,
                                            image->dx,
                                            image->dy,
                                            image->dz,
                                            image->qfac);
      image->qto_ijk=nifti_mat44_inverse(image->qto_xyz);
   }
52 53 54
}
/* *************************************************************** */
/* *************************************************************** */
55 56
bool reg_isAnImageFileName(char *name)
{
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
   std::string n(name);
   if(n.find( ".nii") != std::string::npos)
      return true;
   if(n.find( ".nii.gz") != std::string::npos)
      return true;
   if(n.find( ".hdr") != std::string::npos)
      return true;
   if(n.find( ".img") != std::string::npos)
      return true;
   if(n.find( ".img.gz") != std::string::npos)
      return true;
   if(n.find( ".nrrd") != std::string::npos)
      return true;
   if(n.find( ".png") != std::string::npos)
      return true;
   return false;
73 74 75
}
/* *************************************************************** */
/* *************************************************************** */
76
template<class DTYPE>
77
void reg_intensityRescale_core(nifti_image *image,
78 79 80
                           int timePoint,
                           float newMin,
                           float newMax
81
                          )
82
{
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
   DTYPE *imagePtr = static_cast<DTYPE *>(image->data);
   unsigned int voxelNumber = image->nx*image->ny*image->nz;

   // The rescasling is done for each volume independtly
   DTYPE *volumePtr = &imagePtr[timePoint*voxelNumber];
   DTYPE currentMin=0;
   DTYPE currentMax=0;
   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
      currentMin=(DTYPE)std::numeric_limits<unsigned char>::max();
      currentMax=0;
      break;
   case NIFTI_TYPE_INT8:
      currentMin=(DTYPE)std::numeric_limits<char>::max();
      currentMax=(DTYPE)-std::numeric_limits<char>::max();
      break;
   case NIFTI_TYPE_UINT16:
      currentMin=(DTYPE)std::numeric_limits<unsigned short>::max();
      currentMax=0;
      break;
   case NIFTI_TYPE_INT16:
      currentMin=(DTYPE)std::numeric_limits<char>::max();
      currentMax=-(DTYPE)std::numeric_limits<char>::max();
      break;
   case NIFTI_TYPE_UINT32:
      currentMin=(DTYPE)std::numeric_limits<unsigned int>::max();
      currentMax=0;
      break;
   case NIFTI_TYPE_INT32:
      currentMin=(DTYPE)std::numeric_limits<int>::max();
      currentMax=-(DTYPE)std::numeric_limits<int>::max();
      break;
   case NIFTI_TYPE_FLOAT32:
      currentMin=(DTYPE)std::numeric_limits<float>::max();
      currentMax=-(DTYPE)std::numeric_limits<float>::max();
      break;
   case NIFTI_TYPE_FLOAT64:
      currentMin=(DTYPE)std::numeric_limits<double>::max();
      currentMax=-(DTYPE)std::numeric_limits<double>::max();
      break;
   }

126 127 128 129 130
   std::cout << "Slope:" << image->scl_slope << std::endl;
   std::cout << "Inter:" << image->scl_inter << std::endl;
   std::cout << "Before Min:" << currentMin << std::endl;
   std::cout << "Before Max:" << currentMax << std::endl;

131 132 133 134 135 136 137 138 139 140 141 142
   // Extract the minimal and maximal values from the current volume
   if(image->scl_slope==0) image->scl_slope=1.0f;
   for(unsigned int index=0; index<voxelNumber; index++)
   {
      DTYPE value = (DTYPE)(*volumePtr++ * image->scl_slope + image->scl_inter);
      if(value==value)
      {
         currentMin=(currentMin<value)?currentMin:value;
         currentMax=(currentMax>value)?currentMax:value;
      }
   }

143 144 145
   std::cout << "After Min:" << currentMin << std::endl;
   std::cout << "After Max:" << currentMax << std::endl;

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
   // Compute constant values to rescale image intensities
   double currentDiff = (double)(currentMax-currentMin);
   double newDiff = (double)(newMax-newMin);

   // Set the image header information for appropriate display
   image->cal_min=newMin;
   image->cal_max=newMax;

   // Reset the volume pointer to the start of the current volume
   volumePtr = &imagePtr[timePoint*voxelNumber];

   // Iterates over all voxels in the current volume
   for(unsigned int index=0; index<voxelNumber; index++)
   {
      double value = (double)*volumePtr * image->scl_slope + image->scl_inter;
      // Check if the value is defined
      if(value==value)
      {
         // Normalise the value between 0 and 1
         value = (value-(double)currentMin)/currentDiff;
         // Rescale the value using the specified range
167
         value = value * newDiff + newMin;
168 169 170
      }
      *volumePtr++=(DTYPE)value;
   }
171 172
   image->scl_slope=1.f;
   image->scl_inter=0.f;
173 174
}
/* *************************************************************** */
175 176 177 178
void reg_intensityRescale(nifti_image *image,
                          int timepoint,
                          float newMin,
                          float newMax
179
                         )
180
{
181 182 183
   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
184
      reg_intensityRescale_core<unsigned char>(image, timepoint, newMin, newMax);
185 186
      break;
   case NIFTI_TYPE_INT8:
187
      reg_intensityRescale_core<char>(image, timepoint, newMin, newMax);
188 189
      break;
   case NIFTI_TYPE_UINT16:
190
      reg_intensityRescale_core<unsigned short>(image, timepoint, newMin, newMax);
191 192
      break;
   case NIFTI_TYPE_INT16:
193
      reg_intensityRescale_core<short>(image, timepoint, newMin, newMax);
194 195
      break;
   case NIFTI_TYPE_UINT32:
196
      reg_intensityRescale_core<unsigned int>(image, timepoint, newMin, newMax);
197 198
      break;
   case NIFTI_TYPE_INT32:
199
      reg_intensityRescale_core<int>(image, timepoint, newMin, newMax);
200 201
      break;
   case NIFTI_TYPE_FLOAT32:
202
      reg_intensityRescale_core<float>(image, timepoint, newMin, newMax);
203 204
      break;
   case NIFTI_TYPE_FLOAT64:
205
      reg_intensityRescale_core<double>(image, timepoint, newMin, newMax);
206 207 208 209 210
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_intensityRescale\tThe image data type is not supported\n");
      exit(1);
   }
211 212 213 214
}
/* *************************************************************** */
/* *************************************************************** */
template<class DTYPE>
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
void reg_tools_removeSCLInfo_core(nifti_image *image)
{
   if(image->scl_slope==1.f && image->scl_inter==0.f)
      return;
   DTYPE *imgPtr = static_cast<DTYPE *>(image->data);
   for(size_t i=0;i<image->nvox; ++i){
      *imgPtr=*imgPtr*(DTYPE)image->scl_slope+(DTYPE)image->scl_inter;
      imgPtr++;
   }
   image->scl_slope=1.f;
   image->scl_inter=0.f;
}
/* *************************************************************** */
void reg_tools_removeSCLInfo(nifti_image *image)
{
   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_removeSCLInfo_core<unsigned char>(image);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_removeSCLInfo_core<char>(image);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_removeSCLInfo_core<unsigned short>(image);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_removeSCLInfo_core<short>(image);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_removeSCLInfo_core<unsigned int>(image);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_removeSCLInfo_core<int>(image);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_removeSCLInfo_core<float>(image);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_removeSCLInfo_core<double>(image);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_removeSCLInfo\tThe image data type is not supported\n");
      exit(1);
   }
   return;
}
/* *************************************************************** */
/* *************************************************************** */
template<class DTYPE>
265 266 267
void reg_getRealImageSpacing(nifti_image *image,
                             DTYPE *spacingValues)
{
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
   double indexVoxel1[3]= {0,0,0};
   double indexVoxel2[3], realVoxel1[3], realVoxel2[3];
   reg_mat44_mul(&(image->sto_xyz), indexVoxel1, realVoxel1);

   indexVoxel2[1]=indexVoxel2[2]=0;
   indexVoxel2[0]=1;
   reg_mat44_mul(&(image->sto_xyz), indexVoxel2, realVoxel2);
   spacingValues[0]=(DTYPE)sqrt(reg_pow2(realVoxel1[0]-realVoxel2[0])+reg_pow2(realVoxel1[1]-realVoxel2[1])+reg_pow2(realVoxel1[2]-realVoxel2[2]));

   indexVoxel2[0]=indexVoxel2[2]=0;
   indexVoxel2[1]=1;
   reg_mat44_mul(&(image->sto_xyz), indexVoxel2, realVoxel2);
   spacingValues[1]=(DTYPE)sqrt(reg_pow2(realVoxel1[0]-realVoxel2[0])+reg_pow2(realVoxel1[1]-realVoxel2[1])+reg_pow2(realVoxel1[2]-realVoxel2[2]));

   if(image->nz>1)
   {
      indexVoxel2[0]=indexVoxel2[1]=0;
      indexVoxel2[2]=1;
      reg_mat44_mul(&(image->sto_xyz), indexVoxel2, realVoxel2);
      spacingValues[2]=(DTYPE)sqrt(reg_pow2(realVoxel1[0]-realVoxel2[0])+reg_pow2(realVoxel1[1]-realVoxel2[1])+reg_pow2(realVoxel1[2]-realVoxel2[2]));
   }
289 290 291 292 293 294 295 296 297
}
template void reg_getRealImageSpacing<float>(nifti_image *, float *);
template void reg_getRealImageSpacing<double>(nifti_image *, double *);
/* *************************************************************** */
/* *************************************************************** */
//this function will threshold an image to the values provided,
//set the scl_slope and sct_inter of the image to 1 and 0 (SSD uses actual image data values),
//and sets cal_min and cal_max to have the min/max image data values
template<class T,class DTYPE>
298 299 300
void reg_thresholdImage2(nifti_image *image,
                         T lowThr,
                         T upThr
301
                        )
302
{
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
   DTYPE *imagePtr = static_cast<DTYPE *>(image->data);
   T currentMin=std::numeric_limits<T>::max();
   T currentMax=-std::numeric_limits<T>::max();

   if(image->scl_slope==0)image->scl_slope=1.0;

   for(unsigned int index=0; index<image->nvox; index++)
   {
      T value = (T)(*imagePtr * image->scl_slope + image->scl_inter);
      if(value==value)
      {
         if(value<lowThr)
         {
            value = lowThr;
         }
         else if(value>upThr)
         {
            value = upThr;
         }
         currentMin=(currentMin<value)?currentMin:value;
         currentMax=(currentMax>value)?currentMax:value;
      }
      *imagePtr++=(DTYPE)value;
   }

   image->cal_min = currentMin;
   image->cal_max = currentMax;
330 331 332 333 334 335
}
/* *************************************************************** */
template<class T>
void reg_thresholdImage(nifti_image *image,
                        T lowThr,
                        T upThr
336
                       )
337
{
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_thresholdImage2<T,unsigned char>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_INT8:
      reg_thresholdImage2<T,char>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_UINT16:
      reg_thresholdImage2<T,unsigned short>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_INT16:
      reg_thresholdImage2<T,short>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_UINT32:
      reg_thresholdImage2<T,unsigned int>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_INT32:
      reg_thresholdImage2<T,int>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_thresholdImage2<T,float>(image, lowThr, upThr);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_thresholdImage2<T,double>(image, lowThr, upThr);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_thresholdImage\tThe image data type is not supported\n");
      exit(1);
   }
368 369 370 371 372 373 374 375
}
template void reg_thresholdImage<float>(nifti_image *, float, float);
template void reg_thresholdImage<double>(nifti_image *, double, double);
/* *************************************************************** */
/* *************************************************************** */
template <class PrecisionTYPE, class DTYPE>
PrecisionTYPE reg_getMaximalLength2D(nifti_image *image)
{
376 377 378 379 380 381 382 383 384 385 386 387 388
   DTYPE *dataPtrX = static_cast<DTYPE *>(image->data);
   DTYPE *dataPtrY = &dataPtrX[image->nx*image->ny*image->nz];

   PrecisionTYPE max=0.0;

   for(int i=0; i<image->nx*image->ny*image->nz; i++)
   {
      PrecisionTYPE valX = (PrecisionTYPE)(*dataPtrX++);
      PrecisionTYPE valY = (PrecisionTYPE)(*dataPtrY++);
      PrecisionTYPE length = (PrecisionTYPE)(sqrt(valX*valX + valY*valY));
      max = (length>max)?length:max;
   }
   return max;
389 390 391 392 393
}
/* *************************************************************** */
template <class PrecisionTYPE, class DTYPE>
PrecisionTYPE reg_getMaximalLength3D(nifti_image *image)
{
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
   DTYPE *dataPtrX = static_cast<DTYPE *>(image->data);
   DTYPE *dataPtrY = &dataPtrX[image->nx*image->ny*image->nz];
   DTYPE *dataPtrZ = &dataPtrY[image->nx*image->ny*image->nz];

   PrecisionTYPE max=0.0;

   for(int i=0; i<image->nx*image->ny*image->nz; i++)
   {
      PrecisionTYPE valX = (PrecisionTYPE)(*dataPtrX++);
      PrecisionTYPE valY = (PrecisionTYPE)(*dataPtrY++);
      PrecisionTYPE valZ = (PrecisionTYPE)(*dataPtrZ++);
      PrecisionTYPE length = (PrecisionTYPE)(sqrt(valX*valX + valY*valY + valZ*valZ));
      max = (length>max)?length:max;
   }
   return max;
409 410 411 412 413
}
/* *************************************************************** */
template <class PrecisionTYPE>
PrecisionTYPE reg_getMaximalLength(nifti_image *image)
{
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
   if(image->nz==1)
   {
      switch(image->datatype)
      {
      case NIFTI_TYPE_FLOAT32:
         return reg_getMaximalLength2D<PrecisionTYPE,float>(image);
         break;
      case NIFTI_TYPE_FLOAT64:
         return reg_getMaximalLength2D<PrecisionTYPE,double>(image);
         break;
      }
   }
   else
   {
      switch(image->datatype)
      {
      case NIFTI_TYPE_FLOAT32:
         return reg_getMaximalLength3D<PrecisionTYPE,float>(image);
         break;
      case NIFTI_TYPE_FLOAT64:
         return reg_getMaximalLength3D<PrecisionTYPE,double>(image);
         break;
      }
   }
   return 0;
439 440 441 442 443 444 445
}
/* *************************************************************** */
template float reg_getMaximalLength<float>(nifti_image *);
template double reg_getMaximalLength<double>(nifti_image *);
/* *************************************************************** */
/* *************************************************************** */
template <class NewTYPE, class DTYPE>
Marc Modat's avatar
Marc Modat committed
446
void reg_tools_changeDatatype1(nifti_image *image,int type)
447
{
448 449 450 451 452
   // the initial array is saved and freeed
   DTYPE *initialValue = (DTYPE *)malloc(image->nvox*sizeof(DTYPE));
   memcpy(initialValue, image->data, image->nvox*sizeof(DTYPE));

   // the new array is allocated and then filled
Marc Modat's avatar
Marc Modat committed
453 454 455 456 457 458 459 460 461 462 463 464
   if(type>-1){
      image->datatype=type;
   }
   else{
      if(sizeof(NewTYPE)==sizeof(unsigned char)) image->datatype = NIFTI_TYPE_UINT8;
      else if(sizeof(NewTYPE)==sizeof(float)) image->datatype = NIFTI_TYPE_FLOAT32;
      else if(sizeof(NewTYPE)==sizeof(double)) image->datatype = NIFTI_TYPE_FLOAT64;
      else
      {
         fprintf(stderr,"[NiftyReg ERROR] reg_tools_changeDatatype\tOnly change to unsigned char, float or double are supported\n");
         exit(1);
      }
465 466 467 468 469 470 471 472 473 474
   }
   free(image->data);
   image->nbyper = sizeof(NewTYPE);
   image->data = (void *)calloc(image->nvox,sizeof(NewTYPE));
   NewTYPE *dataPtr = static_cast<NewTYPE *>(image->data);
   for(size_t i=0; i<image->nvox; i++)
      dataPtr[i] = (NewTYPE)(initialValue[i]);

   free(initialValue);
   return;
475 476 477
}
/* *************************************************************** */
template <class NewTYPE>
Marc Modat's avatar
Marc Modat committed
478
void reg_tools_changeDatatype(nifti_image *image, int type)
479
{
480 481 482
   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
Marc Modat's avatar
Marc Modat committed
483
      reg_tools_changeDatatype1<NewTYPE,unsigned char>(image,type);
484 485
      break;
   case NIFTI_TYPE_INT8:
Marc Modat's avatar
Marc Modat committed
486
      reg_tools_changeDatatype1<NewTYPE,char>(image,type);
487 488
      break;
   case NIFTI_TYPE_UINT16:
Marc Modat's avatar
Marc Modat committed
489
      reg_tools_changeDatatype1<NewTYPE,unsigned short>(image,type);
490 491
      break;
   case NIFTI_TYPE_INT16:
Marc Modat's avatar
Marc Modat committed
492
      reg_tools_changeDatatype1<NewTYPE,short>(image,type);
493 494
      break;
   case NIFTI_TYPE_UINT32:
Marc Modat's avatar
Marc Modat committed
495
      reg_tools_changeDatatype1<NewTYPE,unsigned int>(image,type);
496 497
      break;
   case NIFTI_TYPE_INT32:
Marc Modat's avatar
Marc Modat committed
498
      reg_tools_changeDatatype1<NewTYPE,int>(image,type);
499 500
      break;
   case NIFTI_TYPE_FLOAT32:
Marc Modat's avatar
Marc Modat committed
501
      reg_tools_changeDatatype1<NewTYPE,float>(image,type);
502 503
      break;
   case NIFTI_TYPE_FLOAT64:
Marc Modat's avatar
Marc Modat committed
504
      reg_tools_changeDatatype1<NewTYPE,double>(image,type);
505 506 507 508 509
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_changeDatatype\tThe initial image data type is not supported\n");
      exit(1);
   }
510 511
}
/* *************************************************************** */
Marc Modat's avatar
Marc Modat committed
512 513 514 515 516 517 518 519
template void reg_tools_changeDatatype<unsigned char>(nifti_image *, int);
template void reg_tools_changeDatatype<unsigned short>(nifti_image *, int);
template void reg_tools_changeDatatype<unsigned int>(nifti_image *, int);
template void reg_tools_changeDatatype<char>(nifti_image *, int);
template void reg_tools_changeDatatype<short>(nifti_image *, int);
template void reg_tools_changeDatatype<int>(nifti_image *, int);
template void reg_tools_changeDatatype<float>(nifti_image *, int);
template void reg_tools_changeDatatype<double>(nifti_image *, int);
520 521 522 523 524 525 526 527
/* *************************************************************** */
/* *************************************************************** */
template <class TYPE1>
void reg_tools_operationImageToImage(nifti_image *img1,
                                     nifti_image *img2,
                                     nifti_image *res,
                                     int type)
{
528 529 530
   TYPE1 *img1Ptr = static_cast<TYPE1 *>(img1->data);
   TYPE1 *resPtr = static_cast<TYPE1 *>(res->data);
   TYPE1 *img2Ptr = static_cast<TYPE1 *>(img2->data);
531 532


533 534 535 536 537 538
   if(img1->scl_slope==0)
   {
      img1->scl_slope=1.f;
   }
   if(img2->scl_slope==0)
      img2->scl_slope=1.f;
539

540 541
   res->scl_slope=img1->scl_slope;
   res->scl_inter=img1->scl_inter;
542

543

544
#ifdef _WIN32
545
   int  i;
546
#else
547
   size_t  i;
548
#endif
549

550 551 552
   switch(type)
   {
   case 0:
553
#if defined (NDEBUG) && defined (_OPENMP)
554 555 556
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img2Ptr,img1,img2)
557
#endif // _OPENMP
558 559 560 561 562 563
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) +
                              ((double)img2Ptr[i] * (double)img2->scl_slope + (double)img2->scl_inter) -
                              (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 1:
564
#if defined (NDEBUG) && defined (_OPENMP)
565 566 567
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img2Ptr,img1,img2)
568
#endif // _OPENMP
569 570 571 572 573 574
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) -
                              ((double)img2Ptr[i] * (double)img2->scl_slope + (double)img2->scl_inter) -
                              (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 2:
575
#if defined (NDEBUG) && defined (_OPENMP)
576 577 578
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img2Ptr,img1,img2)
579
#endif // _OPENMP
580 581 582 583 584 585
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) *
                              ((double)img2Ptr[i] * (double)img2->scl_slope + (double)img2->scl_inter) -
                              (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 3:
586
#if defined (NDEBUG) && defined (_OPENMP)
587 588 589
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img2Ptr,img1,img2)
590
#endif // _OPENMP
591 592 593 594 595 596
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) /
                              ((double)img2Ptr[i] * (double)img2->scl_slope + (double)img2->scl_inter) -
                              (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   }
597 598 599 600 601 602
}
/* *************************************************************** */
void reg_tools_addImageToImage(nifti_image *img1,
                               nifti_image *img2,
                               nifti_image *res)
{
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
   if(img1->datatype != res->datatype || img2->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addImageToImage\tAll images do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox || img2->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addImageToImage\tAllimages do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationImageToImage<unsigned char>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationImageToImage<char>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationImageToImage<unsigned short>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationImageToImage<short>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationImageToImage<unsigned int>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationImageToImage<int>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationImageToImage<float>(img1, img2, res, 0);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationImageToImage<double>(img1, img2, res, 0);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addImageToImage\tImage data type is not supported\n");
      reg_exit(1);
   }
643 644 645 646 647 648
}
/* *************************************************************** */
void reg_tools_substractImageToImage(nifti_image *img1,
                                     nifti_image *img2,
                                     nifti_image *res)
{
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
   if(img1->datatype != res->datatype || img2->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substractImageToImage\tAll images do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox || img2->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substractImageToImage\tAllimages do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationImageToImage<unsigned char>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationImageToImage<char>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationImageToImage<unsigned short>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationImageToImage<short>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationImageToImage<unsigned int>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationImageToImage<int>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationImageToImage<float>(img1, img2, res, 1);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationImageToImage<double>(img1, img2, res, 1);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substractImageToImage\tImage data type is not supported\n");
      reg_exit(1);
   }
689 690 691 692 693 694
}
/* *************************************************************** */
void reg_tools_multiplyImageToImage(nifti_image *img1,
                                    nifti_image *img2,
                                    nifti_image *res)
{
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
   if(img1->datatype != res->datatype || img2->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyImageToImage\tAll images do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox || img2->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyImageToImage\tAllimages do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationImageToImage<unsigned char>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationImageToImage<char>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationImageToImage<unsigned short>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationImageToImage<short>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationImageToImage<unsigned int>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationImageToImage<int>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationImageToImage<float>(img1, img2, res, 2);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationImageToImage<double>(img1, img2, res, 2);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyImageToImage\tImage data type is not supported\n");
      reg_exit(1);
   }
735 736 737 738 739 740
}
/* *************************************************************** */
void reg_tools_divideImageToImage(nifti_image *img1,
                                  nifti_image *img2,
                                  nifti_image *res)
{
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
   if(img1->datatype != res->datatype || img2->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideImageToImage\tAll images do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox || img2->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideImageToImage\tAllimages do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationImageToImage<unsigned char>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationImageToImage<char>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationImageToImage<unsigned short>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationImageToImage<short>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationImageToImage<unsigned int>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationImageToImage<int>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationImageToImage<float>(img1, img2, res, 3);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationImageToImage<double>(img1, img2, res, 3);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideImageToImage\tImage data type is not supported\n");
      reg_exit(1);
   }
781 782 783 784 785 786 787 788 789
}
/* *************************************************************** */
/* *************************************************************** */
template <class TYPE1>
void reg_tools_operationValueToImage(nifti_image *img1,
                                     nifti_image *res,
                                     float val,
                                     int type)
{
790 791
   TYPE1 *img1Ptr = static_cast<TYPE1 *>(img1->data);
   TYPE1 *resPtr = static_cast<TYPE1 *>(res->data);
792

793 794 795 796
   if(img1->scl_slope==0)
   {
      img1->scl_slope=1.f;
   }
797

798 799
   res->scl_slope=img1->scl_slope;
   res->scl_inter=img1->scl_inter;
800

801
#ifdef _WIN32
802
   int  i;
803
#else
804
   size_t  i;
805
#endif
806

807 808 809
   switch(type)
   {
   case 0:
810
#if defined (NDEBUG) && defined (_OPENMP)
811 812 813
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img1,val)
814
#endif // _OPENMP
815 816 817 818 819
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)(((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) +
                               (double)val) - (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 1:
820
#if defined (NDEBUG) && defined (_OPENMP)
821 822 823
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img1,val)
824
#endif // _OPENMP
825 826 827 828 829
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)(((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) -
                               (double)val) - (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 2:
830
#if defined (NDEBUG) && defined (_OPENMP)
831 832 833
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img1,val)
834
#endif // _OPENMP
835 836 837 838 839
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)(((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) *
                               (double)val) - (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   case 3:
840
#if defined (NDEBUG) && defined (_OPENMP)
841 842 843
      #pragma omp parallel for default(none) \
      private(i) \
      shared(res,resPtr,img1Ptr,img1,val)
844
#endif // _OPENMP
845 846 847 848 849
      for(i=0; i<res->nvox; i++)
         resPtr[i] = (TYPE1)(((((double)img1Ptr[i] * (double)img1->scl_slope + (double)img1->scl_inter) /
                               (double)val) - (double)img1->scl_inter)/(double)img1->scl_slope);
      break;
   }
850 851 852 853 854 855
}
/* *************************************************************** */
void reg_tools_addValueToImage(nifti_image *img1,
                               nifti_image *res,
                               float val)
{
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
   if(img1->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addValueToImage\tInput and result image do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addValueToImage\tInput and result image do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationValueToImage<unsigned char>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationValueToImage<char>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationValueToImage<unsigned short>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationValueToImage<short>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationValueToImage<unsigned int>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationValueToImage<int>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationValueToImage<float>(img1, res, val, 0);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationValueToImage<double>(img1, res, val, 0);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_addValueToImage\t Image data type is not supported\n");
      reg_exit(1);
   }
896 897 898
}
/* *************************************************************** */
void reg_tools_substractValueToImage(nifti_image *img1,
899 900
                                     nifti_image *res,
                                     float val)
901
{
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
   if(img1->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substractValueToImage\tInput and result image do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substracValueToImage\tInput and result image do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationValueToImage<unsigned char>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationValueToImage<char>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationValueToImage<unsigned short>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationValueToImage<short>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationValueToImage<unsigned int>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationValueToImage<int>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationValueToImage<float>(img1, res, val, 1);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationValueToImage<double>(img1, res, val, 1);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_substractValueToImage\t Image data type is not supported\n");
      reg_exit(1);
   }
942 943 944
}
/* *************************************************************** */
void reg_tools_multiplyValueToImage(nifti_image *img1,
945 946
                                    nifti_image *res,
                                    float val)
947
{
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
   if(img1->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyValueToImage\tInput and result image do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyValueToImage\tInput and result image do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationValueToImage<unsigned char>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationValueToImage<char>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationValueToImage<unsigned short>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationValueToImage<short>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationValueToImage<unsigned int>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationValueToImage<int>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationValueToImage<float>(img1, res, val, 2);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationValueToImage<double>(img1, res, val, 2);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_multiplyValueToImage\t Image data type is not supported\n");
      reg_exit(1);
   }
988 989 990
}
/* *************************************************************** */
void reg_tools_divideValueToImage(nifti_image *img1,
991 992
                                  nifti_image *res,
                                  float val)
993
{
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
   if(img1->datatype != res->datatype)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideValueToImage\tInput and result image do not have the same data type\n");
      reg_exit(1);
   }
   if(img1->nvox != res->nvox)
   {
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideValueToImage\tInput and result image do not have the same size\n");
      reg_exit(1);
   }
   switch(img1->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_operationValueToImage<unsigned char>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_operationValueToImage<char>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_operationValueToImage<unsigned short>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_operationValueToImage<short>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_operationValueToImage<unsigned int>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_operationValueToImage<int>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_operationValueToImage<float>(img1, res, val, 3);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_operationValueToImage<double>(img1, res, val, 3);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_tools_divideValueToImage\t Image data type is not supported\n");
      reg_exit(1);
   }
1034 1035 1036
}
/* *************************************************************** */
/* *************************************************************** */
1037 1038 1039 1040
template <class DTYPE>
void reg_tools_kernelConvolution_core(nifti_image *image,
                                      float *size,
                                      int kernelType,
1041
                                      int *mask,
1042 1043
                                      bool *timePoint,
                                      bool *axis)
1044
{
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
   DTYPE *imagePtr = static_cast<DTYPE *>(image->data);
   size_t voxelNumber = (size_t)image->nx*image->ny*image->nz;
   int imageDim[3]= {image->nx,image->ny,image->nz};

   bool *nanImagePtr = (bool *)malloc(voxelNumber*sizeof(bool));
   float *densityPtr = (float *)malloc(voxelNumber*sizeof(float));

   // Loop over the dimension higher than 3
   for(int t=0; t<image->nt*image->nu; t++)
   {
      if(timePoint[t])
      {
         DTYPE *intensityPtr = &imagePtr[t * voxelNumber];
         int index;
1059
#if defined (_OPENMP)
1060 1061 1062
         #pragma omp parallel for default(none) \
         shared(densityPtr, intensityPtr, mask, nanImagePtr, voxelNumber) \
         private(index)
1063
#endif
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
         for(index=0; index<voxelNumber; index++)
         {
            densityPtr[index] = (intensityPtr[index]==intensityPtr[index])?1:0;
            densityPtr[index] *= (mask[index]>=0)?1:0;
            nanImagePtr[index] = static_cast<bool>(densityPtr[index]);
            if(nanImagePtr[index]==0)
               intensityPtr[index]=static_cast<DTYPE>(0);
         }
         // Loop over the x, y and z dimensions
         for(int n=0; n<3; n++)
         {
            if(axis[n] && image->dim[n]>1)
            {
               double temp;
               if(size[t]>0) temp=size[t]/image->pixdim[n+1]; // mm to voxel
               else temp=fabs(size[t]); // voxel based if negative value
               int radius;
               // Define the kernel size
               if(kernelType==2)
               {
                  // Mean filtering
                  radius = static_cast<int>(temp);
               }
               else if(kernelType==1)
               {
                  // Cubic Spline kernel
                  radius = static_cast<int>(temp*2.0f);
               }
               else
               {
                  // Gaussian kernel
                  radius=static_cast<int>(temp*3.0f);
               }
               if(radius>0)
               {
                  // Allocate the kernel
                  float kernel[2024];
                  double kernelSum=0;
                  // Fill the kernel
                  if(kernelType==2)
                  {
                     // No kernel is required for the mean filtering
                     NULL;
                  }
                  else if(kernelType==1)
                  {
                     // Compute the Cubic Spline kernel
                     for(int i=-radius; i<=radius; i++)
                     {
                        // temp contains the kernel node spacing
                        double relative = (double)(fabs((double)(double)i/(double)temp));
                        if(relative<1.0) kernel[i+radius] = (float)(2.0/3.0 - relative*relative + 0.5*relative*relative*relative);
                        else if (relative<2.0) kernel[i+radius] = (float)(-(relative-2.0)*(relative-2.0)*(relative-2.0)/6.0);
                        else kernel[i+radius]=0;
                        kernelSum += kernel[i+radius];
                     }
                  }
                  else
                  {
                     // Compute the Gaussian kernel
                     for(int i=-radius; i<=radius; i++)
                     {
                        // 2.506... = sqrt(2*pi)
                        // temp contains the sigma in voxel
                        kernel[radius+i]=static_cast<float>(exp(-(double)(i*i)/(2.0*reg_pow2(temp))) /
                                                            (temp*2.506628274631));
                        kernelSum += kernel[radius+i];
                     }
                  }
                  // No need for kernel normalisation as this is handle by the density function
1134
#ifndef NDEBUG
1135
                  printf("[NiftyReg DEBUG] Convolution type[%i] dim[%i] tp[%i] radius[%i] kernelSum[%g]\n", kernelType, n, t, radius, kernelSum);
1136
#endif
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
                  unsigned int k, planeNumber, lineIndex, lineOffset;
                  int planeIndex;
                  switch(n)
                  {
                  case 0:
                     planeNumber=imageDim[1]*imageDim[2];
                     lineOffset  = 1;
                     break;
                  case 1:
                     planeNumber = imageDim[0]*imageDim[2];
                     lineOffset  = imageDim[0];
                     break;
                  case 2:
                     planeNumber = imageDim[0]*imageDim[1];
                     lineOffset  = planeNumber;
                     break;
                  }

                  int shiftPre, shiftPst;
                  size_t realIndex;
                  float *kernelPtr, kernelValue;
                  double densitySum, intensitySum;
                  DTYPE *currentIntensityPtr=NULL;
                  float *currentDensityPtr = NULL;
                  DTYPE bufferIntensity[2048];;
                  float bufferDensity[2048];
                  DTYPE bufferIntensitycur;
                  float bufferDensitycur;
1165 1166

#if defined (_OPENMP)
1167 1168 1169 1170 1171 1172
                  #pragma omp parallel for default(none) \
                  shared(imageDim, intensityPtr, densityPtr, radius, kernel, lineOffset, n, \
                         planeNumber,kernelSum) \
                  private(realIndex,currentIntensityPtr,currentDensityPtr,lineIndex,bufferIntensity, \
                          bufferDensity,shiftPre,shiftPst,kernelPtr,kernelValue,densitySum,intensitySum, \
                          k, bufferIntensitycur,bufferDensitycur, planeIndex)
1173
#endif // _OPENMP
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
                  // Loop over the different voxel
                  for(planeIndex=0; planeIndex<planeNumber; ++planeIndex)
                  {

                     switch(n)
                     {
                     case 0:
                        realIndex = planeIndex * imageDim[0];
                        break;
                     case 1:
                        realIndex = (planeIndex/imageDim[0]) *
                                    imageDim[0]*imageDim[1] +
                                    planeIndex%imageDim[0];
                        break;
                     case 2:
                        realIndex = planeIndex;
                        break;
                     }
                     // Fetch the current line into a stack buffer
                     currentIntensityPtr= &intensityPtr[realIndex];
                     currentDensityPtr  = &densityPtr[realIndex];
                     for(lineIndex=0; lineIndex<imageDim[n]; ++lineIndex)
                     {
                        bufferIntensity[lineIndex] = *currentIntensityPtr;
                        bufferDensity[lineIndex]   = *currentDensityPtr;
                        currentIntensityPtr       += lineOffset;
                        currentDensityPtr         += lineOffset;
                     }
                     if(kernelSum>0)
                     {
                        // Perform the kernel convolution along 1 line
                        for(lineIndex=0; lineIndex<imageDim[n]; ++lineIndex)
                        {
                           // Define the kernel boundaries
                           shiftPre = lineIndex - radius;
                           shiftPst = lineIndex + radius + 1;
                           if(shiftPre<0)
                           {
                              kernelPtr = &kernel[-shiftPre];
                              shiftPre=0;
                           }
                           else kernelPtr = &kernel[0];
                           if(shiftPst>imageDim[n]) shiftPst=imageDim[n];
                           // Set the current values to zero
                           intensitySum=0;
                           densitySum=0;
                           // Increment the current value by performing the weighted sum
                           for(k=shiftPre; k<shiftPst; ++k)
                           {
                              kernelValue   = *kernelPtr++;
                              intensitySum +=  kernelValue * bufferIntensity[k];
                              densitySum   +=  kernelValue * bufferDensity[k];
                           }
                           // Store the computed value inplace
                           intensityPtr[realIndex] = static_cast<DTYPE>(intensitySum);
                           densityPtr[realIndex] = static_cast<float>(densitySum);
                           realIndex += lineOffset;
                        } // line convolution
                     } // kernel type
                     else
                     {
                        for(lineIndex=1; lineIndex<imageDim[n]; ++lineIndex)
                        {
                           bufferIntensity[lineIndex]+=bufferIntensity[lineIndex-1];
                           bufferDensity[lineIndex]+=bufferDensity[lineIndex-1];
                        }
                        shiftPre = -radius - 1;
                        shiftPst = radius;
                        for(lineIndex=0; lineIndex<imageDim[n]; ++lineIndex,++shiftPre,++shiftPst)
                        {
                           if(shiftPre>-1)
                           {
                              if(shiftPst<imageDim[n])
                              {
                                 bufferIntensitycur = (DTYPE)(bufferIntensity[shiftPre]-bufferIntensity[shiftPst]);
                                 bufferDensitycur = (DTYPE)(bufferDensity[shiftPre]-bufferDensity[shiftPst]);
                              }
                              else
                              {
                                 bufferIntensitycur = (DTYPE)(bufferIntensity[shiftPre]-bufferIntensity[imageDim[n]-1]);
                                 bufferDensitycur = (DTYPE)(bufferDensity[shiftPre]-bufferDensity[imageDim[n]-1]);
                              }
                           }
                           else
                           {
                              if(shiftPst<imageDim[n])
                              {
                                 bufferIntensitycur = (DTYPE)(-bufferIntensity[shiftPst]);
                                 bufferDensitycur = (DTYPE)(-bufferDensity[shiftPst]);
                              }
                           }
                           intensityPtr[realIndex]=bufferIntensitycur;
                           densityPtr[realIndex]=bufferDensitycur;

                           realIndex += lineOffset;
                        } // line convolution of mean filter
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304

//								// Compute the mean at the first point
//								intensitySum=0;
//								densitySum = 0;
//								if(imageDim[n]<=radius){
//									for(k=0;k<imageDim[n];++k){
//										intensitySum += bufferIntensity[k];
//										densitySum   += bufferDensity[k];
//									}
//								}
//								else{
//									for(k=0;k<=radius;++k){
//										intensitySum += bufferIntensity[k];
//										densitySum   += bufferDensity[k];
//									}
//								}
//								intensityPtr[realIndex] = static_cast<DTYPE>(intensitySum);
//								densityPtr[realIndex]   = static_cast<float>(densitySum);
//								realIndex += lineOffset;
//								// Compute the mean along 1 line from the second point onward
//								shiftPre = 1 - radius - 1; // to be removed
//								shiftPst = 1 + radius; // to be added
//								for(lineIndex=1;lineIndex<imageDim[n];++lineIndex,++shiftPre,++shiftPst){
//									if(shiftPre>=0){
//										intensitySum -= bufferIntensity[shiftPre];
//										densitySum   -= bufferDensity[shiftPre];
//									}
//									if(shiftPst<imageDim[n]){
//										intensitySum += bufferIntensity[shiftPst];
//										densitySum   += bufferDensity[shiftPst];
//									}
//									intensityPtr[realIndex] = static_cast<DTYPE>(intensitySum);
//									densityPtr[realIndex] = static_cast<float>(densitySum);
//									realIndex += lineOffset;
//								} // line convolution of mean filter
1305 1306 1307 1308 1309 1310
                     } // No kernel computation
                  } // pixel in starting plane
               } // radius > 0
            } // active axis
         } // axes
         // Normalise per timepoint
1311
#if defined (NDEBUG) && defined (_OPENMP)
1312 1313 1314
         #pragma omp parallel for default(none) \
         shared(voxelNumber, intensityPtr, densityPtr, nanImagePtr) \
         private(index)
1315
#endif
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
         for(index=0; index<voxelNumber; ++index)
         {
            if(nanImagePtr[index]!=0)
               intensityPtr[index] = static_cast<DTYPE>((float)intensityPtr[index]/densityPtr[index]);
            else intensityPtr[index] = std::numeric_limits<DTYPE>::quiet_NaN();
         }
      } // check if the time point is active
   } // loop over the time points
   free(nanImagePtr);
   free(densityPtr);
1326 1327
}
/* *************************************************************** */
1328
void reg_tools_kernelConvolution(nifti_image *image,
1329 1330 1331 1332 1333
                                 float *sigma,
                                 int kernelType,
                                 int *mask,
                                 bool *timePoint,
                                 bool *axis)
1334
{
1335 1336


1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
   if(image->nt<=0) image->nt=image->dim[4]=1;
   if(image->nu<=0) image->nu=image->dim[5]=1;

   bool *axisToSmooth = new bool[3];
   bool *activeTimePoint = new bool[image->nt*image->nu];
   if(axis==NULL)
   {
      // All axis are smoothed by default
      for(int i=0; i<3; i++) axisToSmooth[i]=true;
   }
   else for(int i=0; i<3; i++) axisToSmooth[i]=axis[i];

   if(timePoint==NULL)
   {
      // All time points are considered as active
      for(int i=0; i<image->nt*image->nu; i++) activeTimePoint[i]=true;
   }
   else for(int i=0; i<image->nt*image->nu; i++) activeTimePoint[i]=timePoint[i];

   int *currentMask=NULL;
   if(mask==NULL)
   {
      currentMask=(int *)calloc(image->nx*image->ny*image->nz,sizeof(int));
   }
   else currentMask=mask;

   switch(image->datatype)
   {
   case NIFTI_TYPE_UINT8:
      reg_tools_kernelConvolution_core<unsigned char>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_INT8:
      reg_tools_kernelConvolution_core<char>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_UINT16:
      reg_tools_kernelConvolution_core<unsigned short>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_INT16:
      reg_tools_kernelConvolution_core<short>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_UINT32:
      reg_tools_kernelConvolution_core<unsigned int>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_INT32:
      reg_tools_kernelConvolution_core<int>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_FLOAT32:
      reg_tools_kernelConvolution_core<float>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_tools_kernelConvolution_core<double>(image, sigma, kernelType, currentMask, activeTimePoint, axisToSmooth);
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_gaussianSmoothing\tThe image data type is not supported\n");
      reg_exit(1);
   }

   if(mask==NULL) free(currentMask);
   delete []axisToSmooth;
   delete []activeTimePoint;
1397 1398 1399 1400 1401 1402
}
/* *************************************************************** */
/* *************************************************************** */
template <class PrecisionTYPE, class ImageTYPE>
void reg_downsampleImage1(nifti_image *image, int type, bool *downsampleAxis)
{
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527