File: fileio_nifti.cpp

package info (click to toggle)
odin 2.0.5-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,196 kB
  • sloc: cpp: 62,638; sh: 4,541; makefile: 779
file content (402 lines) | stat: -rw-r--r-- 16,100 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
330
331
332
333
334
335
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#include "fileio.h"
#include "filter.h"

#ifdef NIFTISUPPORT

#include <nifti1_io.h>

/////////////////////////////////////////////////////////////

struct NiftiFormat : public FileFormat{

  STD_string description() const {return "NIFTI/ANALYZE";}
  svector suffix() const{
    svector result; result.resize(3);
    result[0]="nii";
    result[1]="hdr";
    result[2]="analyze"; // for disambiguation
    return result;
  }

  svector dialects() const{
    svector result; result.resize(1);
    result[0]="fsl";
    return result;
  }

  bool read_orientation(const nifti_image &ni,Geometry &geometry, const FileReadOpts& opts) {
    Log<FileIO> odinlog("NiftiFormat","read_orientation");

    float spatscale=1.0;
    if(ni.xyz_units==NIFTI_UNITS_METER) spatscale=1.0e3;
    if(ni.xyz_units==NIFTI_UNITS_MICRON) spatscale=1.0e-3;
    //@todo check me

    geometry.set_FOV(readDirection,ni.dx*spatscale*ni.dim[1]);
    geometry.set_FOV(phaseDirection,ni.dy*spatscale*ni.dim[2]);
    geometry.set_sliceThickness(ni.dz*spatscale);
    geometry.set_sliceDistance(ni.dz*spatscale);     //no interslice distance in nifti - so use thickness
    geometry.set_nSlices(ni.dim[3]);

    if(ni.nifti_type>0) { // only for non-ANALYZE

      dvector readvec(3),phasevec(3),slicevec(3),centervec(3);

//      RotMatrix scaleMat;//method 2
      if(ni.qform_code>0) {// just tranform to the nominal space of the scanner
        ODINLOG(odinlog,normalDebug) << "Reading orientation from qform" << STD_endl;
        for(unsigned short i=0;i<3;i++) {
          readvec[i]  =ni.qto_xyz.m[i][0]/ni.dx;
          phasevec[i] =ni.qto_xyz.m[i][1]/ni.dy;
          slicevec[i] =ni.qto_xyz.m[i][2]/ni.dz;
          centervec[i]=ni.qto_xyz.m[i][3]*spatscale;
        }
      } else if(ni.sform_code>0) { // method 3
        ODINLOG(odinlog,normalDebug) << "Reading orientation from sform" << STD_endl;
        for(unsigned short i=0;i<3;i++) {
          readvec[i]  =ni.sto_xyz.m[i][0]/ni.dx;
          phasevec[i] =ni.sto_xyz.m[i][1]/ni.dy;
          slicevec[i] =ni.sto_xyz.m[i][2]/ni.dz;
          centervec[i]=ni.sto_xyz.m[i][3]*spatscale;
        }
      } else {
        ODINLOG(odinlog,infoLog) << "can't read Orientation"<< STD_endl;
      }

      const dvector ivector =//diagonale trougth the image in "normal" space
          (geometry.get_FOV(readDirection)-ni.dx)*readvec+
          (geometry.get_FOV(phaseDirection)-ni.dy)*phasevec+
          (geometry.get_FOV(sliceDirection)-ni.dz)*slicevec;
      centervec+=ivector/2;

      ODINLOG(odinlog,normalDebug) << "FOV read/phase/slice:"<< geometry.get_FOV(readDirection) << "/" << geometry.get_FOV(phaseDirection) << "/" << geometry.get_FOV(sliceDirection) << STD_endl;

      ODINLOG(odinlog,normalDebug) << "readvec:" << readvec.printbody()  << STD_endl;
      ODINLOG(odinlog,normalDebug) << "phasevec:"<< phasevec.printbody() << STD_endl;
      ODINLOG(odinlog,normalDebug) << "slicevec:"<< slicevec.printbody() << STD_endl;
      ODINLOG(odinlog,normalDebug) << "image diagonale "<< ivector.printbody() <<"/" << sqrt(ivector[0]*ivector[0]+ivector[1]*ivector[1]+ivector[2]*ivector[2])<< STD_endl;
      ODINLOG(odinlog,normalDebug) << "center " << centervec.printbody() << STD_endl;
    //		@todo should be set here
    // 		for(unsigned short i=0;i<3;i++)
    // 			scaleMat[i][i]=1/ni.pixdim[i+1];

      geometry.set_orientation_and_offset(readvec,phasevec,slicevec,centervec);

      ODINLOG(odinlog,normalDebug) << "set up gradrot matrix " << geometry.get_gradrotmatrix().print() << STD_endl;
      ODINLOG(odinlog,normalDebug) << "set up center (offset) " << geometry.get_center().printbody() << STD_endl;
    }
    return true;
  }

  template<class T> void copy_from(const T* src,Data<float,4> &dst, const FileReadOpts& opts) {
    convert_from_ptr(dst, src, dst.shape());
  }


  int read(Data<float,4>& data, const STD_string& filename, const FileReadOpts& opts, Protocol& prot) {
    Log<FileIO> odinlog("NiftiFormat","read");

    nifti_image* ni=nifti_image_read(filename.c_str(), true);

    if(!read_orientation(*ni,prot.geometry,opts)) return -1;

    data.resize(
        ni->ndim>=4 ? ni->dim[4]:1,
        ni->ndim>=3 ? ni->dim[3]:1,
        ni->ndim>=2 ? ni->dim[2]:1,
        ni->dim[1]
    );
    const TinyVector<int, 4> shape(data.shape());
    ODINLOG(odinlog,normalDebug) << "shape/ndim=" << shape << "/" << ni->ndim << STD_endl;
    if(int(ni->nvox)!=product(shape)) {
      ODINLOG(odinlog,errorLog)  << "ni->nvox=" << ni->nvox << " != product(shape)=" << product(shape) << STD_endl;
    }

    STD_string type;
    //copy ni->data to data
    switch(ni->datatype) {
      case DT_UINT8:
        type=TypeTraits::type2label((u8bit)0);
        copy_from((u8bit*)ni->data, data,opts);
        break;
      case DT_INT8:
        type=TypeTraits::type2label((s8bit)0);
        copy_from((s8bit*)ni->data, data,opts);
        break;
      case DT_UINT16:
        type=TypeTraits::type2label((u16bit)0);
        copy_from((u16bit*)ni->data, data,opts);
        break;
      case DT_INT16:
        type=TypeTraits::type2label((s16bit)0);
        copy_from((s16bit*)ni->data, data,opts);
        break;
      case DT_UINT32:
        type=TypeTraits::type2label((u32bit)0);
        copy_from((u32bit*)ni->data, data,opts);
        break;
      case DT_INT32:
        type=TypeTraits::type2label((s32bit)0);
        copy_from((s32bit*)ni->data, data,opts);
        break;
      case DT_FLOAT32:
        type=TypeTraits::type2label((float)0);
        copy_from((float*)ni->data, data,opts);
        break;
      case DT_FLOAT64:
        type=TypeTraits::type2label((double)0);
        copy_from((double*)ni->data, data,opts);
        break;
      default:
        ODINLOG(odinlog,errorLog) << "Unsupported datatype " << ni->datatype << STD_endl;
        return -1;
        break;
    }
    ODINLOG(odinlog,normalDebug) << "type=" << type << STD_endl;
    if(type=="")return -1;

    if(ni->nifti_type>0) { // only for non-ANALYZE
      if(ni->scl_slope!=1.0 || ni->scl_inter!=0.0) {
        ODINLOG(odinlog,normalDebug) << "ni->scl_slope/ni->scl_inter=" << ni->scl_slope << "/" <<ni->scl_inter << STD_endl;
        if(ni->scl_slope) { // apply only if slope is non-zero
          data=data*ni->scl_slope+ni->scl_inter;
        }
      }
    }

    //set some metadata
    prot.system.set_data_type(type);
    prot.seqpars.set_NumOfRepetitions(ni->dim[4]);

    float timescale=1.0;
    if(ni->time_units==NIFTI_UNITS_SEC) timescale=1.0e3;
    if(ni->time_units==NIFTI_UNITS_USEC) timescale=1.0e-3;
    ODINLOG(odinlog,normalDebug) << "ni->time_units/timescale/ni->dt=" << ni->time_units << "/" << timescale << "/" << ni->dt << STD_endl;
    prot.seqpars.set_RepetitionTime(timescale*ni->dt);

    nifti_image_free(ni);
    return shape(0)*shape(1);
  }

  void store_orientation(nifti_image &ni,const Data<float,4>& data,const Geometry &geometry, const FileWriteOpts& opts) {
    Log<FileIO> odinlog("NiftiFormat","store_orientation");
    ni.sform_code=ni.qform_code=NIFTI_XFORM_SCANNER_ANAT; //set scanner aligned space

    const RotMatrix rot(geometry.get_gradrotmatrix());//orientation of the image in "normal" space
    const TinyVector<int, 4> shape(data.shape());//size of the image in voxels
    const dvector center(geometry.get_center());//position of the image in "normal" space

    ni.dx=ni.pixdim[1]=voxel_extent(geometry,readDirection, shape(3));
    ni.dy=ni.pixdim[2]=voxel_extent(geometry,phaseDirection, shape(2));
    ni.dz=ni.pixdim[3]=voxel_extent(geometry,sliceDirection, shape(1));

    const dvector ivector =//diagonale trougth the image (from first voxel, to the last) in "normal" space
        (geometry.get_FOV(readDirection)-ni.dx)*geometry.get_readVector()+
        (geometry.get_FOV(phaseDirection)-ni.dy)*geometry.get_phaseVector()+
        (geometry.get_FOV(sliceDirection)-ni.dz)*geometry.get_sliceVector();

//    double heightAng,azimutAng,inplaneAng;
//    geometry.get_orientation(heightAng,azimutAng,inplaneAng);


    ODINLOG(odinlog,normalDebug) << "get_gradrotmatrix "<< rot.print() << STD_endl;
    ODINLOG(odinlog,normalDebug) << "get_readVector "<< geometry.get_readVector().printbody() << STD_endl;
    ODINLOG(odinlog,normalDebug) << "get_phaseVector "<< geometry.get_phaseVector().printbody() << STD_endl;
    ODINLOG(odinlog,normalDebug) << "get_sliceVector "<< geometry.get_sliceVector().printbody() << STD_endl;
    ODINLOG(odinlog,normalDebug) << "get_center "<< center.printbody() << STD_endl;
    ODINLOG(odinlog,normalDebug) << "FOV read/phase/slice "<< geometry.get_FOV(readDirection) << "/" << geometry.get_FOV(phaseDirection) << "/" << geometry.get_FOV(sliceDirection) << STD_endl;
    ODINLOG(odinlog,normalDebug) << "image diagonale "<< ivector.printbody() <<"/" << sqrt(ivector[0]*ivector[0]+ivector[1]*ivector[1]+ivector[2]*ivector[2])<< STD_endl;
//    ODINLOG(odinlog,normalDebug) << "heightAng,azimutAng,inplaneAng " << heightAng << "," << azimutAng << "," << inplaneAng << STD_endl;

    //create space tranformation matrices - transforms the space when reading _NOT_ the data
    //@todo maybe we can get the quaternions directly from the given rotation angles
    for(int y =0;y<3;y++) {
      ni.qto_xyz.m[0][y]=rot[0][y];
      ni.qto_xyz.m[1][y]=rot[1][y];
      ni.qto_xyz.m[2][y]=rot[2][y];
      ni.qto_xyz.m[y][3]=center[y]-ivector[y]/2;
    }

    memcpy(ni.sto_xyz.m,ni.qto_xyz.m,sizeof(ni.sto_xyz.m));

    //add scaling to the sform
    for(int y =0;y<3;y++){
      ni.sto_xyz.m[0][y]*=ni.pixdim[1+y];
      ni.sto_xyz.m[1][y]*=ni.pixdim[1+y];
      ni.sto_xyz.m[2][y]*=ni.pixdim[1+y];
    }

    ni.dx=ni.pixdim[1];
    ni.dy=ni.pixdim[2];
    ni.dz=ni.pixdim[3];
    //generate matching quaternions
    nifti_mat44_to_quatern(
      ni.qto_xyz,
      &ni.quatern_b,&ni.quatern_c,&ni.quatern_d,
      &ni.qoffset_x,&ni.qoffset_y,&ni.qoffset_z,
      NULL,NULL,NULL,
      &ni.qfac);
  }

  template<typename T> void* copy_to(Data<float,4> &src,Data<T,4> &dst,nifti_image &ni, Geometry& geo,const FileWriteOpts& opts) {
    Log<FileIO> odinlog("NiftiFormat","copy_to");

    src.convert_to(dst,!opts.noscale);

    const TinyVector<int, 4> shape(src.shape());

    ni.ndim=ni.dim[0]=shape(0)>1 ? 4:3;
    ni.nx=ni.dim[1]=shape(3);
    ni.ny=ni.dim[2]=shape(2);
    ni.nz=ni.dim[3]=shape(1);
    ni.nt=ni.dim[4]=shape(0);

    //@todo - is already done in autoscaled conversion - waste of time
    ni.cal_max = max(dst);
    ni.cal_min = min(dst);

    ni.nvox=product(shape);
    //and return pointer to the converted data
    return dst.c_array();
  }


  int write(const Data<float,4>& data, const STD_string& filename, const FileWriteOpts& opts, const Protocol& prot) {
    Log<FileIO> odinlog("NiftiFormat","write");
    STD_string type=select_write_datatype(prot,opts);
    ODINLOG(odinlog,normalDebug) << "type=" << type << STD_endl;

    LDRfileName fname(filename);

    Protocol protcopy(prot);
    Geometry& geo=protcopy.geometry;

    Data<float,4> src(data);

    nifti_image ni;
    memset(&ni,0, sizeof(nifti_image));           //set everything to zero - default value for "not used"
    ni.nu=ni.nv=ni.nw=1;

    if(tolowerstr(opts.dialect)=="fsl") {
      bool do_transform=false;
      STD_string sppart="s,p";
      if(geo.get_orientation()==sagittal || geo.get_orientation()==coronal) {
        ODINLOG(odinlog,infoLog) << "Rotating around read axis for fsl dialect" << STD_endl;
        sppart="p-,s";
        do_transform=true;
      }
      STD_string rsign;
      double heightAng, azimutAng, inplaneAng;
      bool revSlice;
      geo.get_orientation(heightAng, azimutAng, inplaneAng, revSlice);
      if(!revSlice) { // FSL needs 'radiological' handness
        ODINLOG(odinlog,infoLog) << "Reversing handness for fsl dialect" << STD_endl;
        rsign="-";
        do_transform=true;
      }

      if(do_transform) FilterChain("-swapdim "+sppart+",r"+rsign+"").apply(protcopy,src);
    }

    // Compatabilty with FSL
    STD_string newtype;
    if(IS_TYPE(s8bit,type))       newtype=TypeTraits::type2label((u8bit)0);
    else if(IS_TYPE(u16bit,type)) newtype=TypeTraits::type2label((s16bit)0);
    else if(IS_TYPE(u32bit,type)) newtype=TypeTraits::type2label((s32bit)0);

    if(newtype!="") {
      if(tolowerstr(opts.dialect)=="fsl" || fname.get_suffix()=="hdr") {
        ODINLOG(odinlog,infoLog) << "data type " << type << " is not supported, falling back to " << newtype << STD_endl;
        type=newtype;
      } else {
        ODINLOG(odinlog,warningLog) << "data type " << type << " is not supported in FSL, use '-wdialect fsl' to correct this" << STD_endl;
      }
    }


    store_orientation(ni,src,geo,opts);

    //dummies to keep the data ni.data points to
    Data< u8bit,4>  u8bit_data;
    Data< s8bit,4>  s8bit_data;
    Data<u16bit,4> u16bit_data;
    Data<s16bit,4> s16bit_data;
    Data<u32bit,4> u32bit_data;
    Data<s32bit,4> s32bit_data;
    Data< float,4>  float_data;
    Data<double,4> double_data;


    ni.datatype=DT_UNKNOWN;
    if(     IS_TYPE( u8bit,type)) {ni.datatype=DT_UINT8;  ni.data=copy_to(src, u8bit_data,ni,geo,opts);}
    else if(IS_TYPE( s8bit,type)) {ni.datatype=DT_INT8;   ni.data=copy_to(src, s8bit_data,ni,geo,opts);}
    else if(IS_TYPE(u16bit,type)) {ni.datatype=DT_UINT16; ni.data=copy_to(src,u16bit_data,ni,geo,opts);}
    else if(IS_TYPE(s16bit,type)) {ni.datatype=DT_INT16;  ni.data=copy_to(src,s16bit_data,ni,geo,opts);}
    else if(IS_TYPE(u32bit,type)) {ni.datatype=DT_UINT32; ni.data=copy_to(src,u32bit_data,ni,geo,opts);}
    else if(IS_TYPE(s32bit,type)) {ni.datatype=DT_INT32;  ni.data=copy_to(src,s32bit_data,ni,geo,opts);}
    else if(IS_TYPE(float,type))  {ni.datatype=DT_FLOAT32;ni.data=copy_to(src, float_data,ni,geo,opts);}
    else if(IS_TYPE(double,type)) {ni.datatype=DT_FLOAT64;ni.data=copy_to(src,double_data,ni,geo,opts);}

    ni.nbyper=TypeTraits::typesize(type);
    ODINLOG(odinlog,normalDebug) << "nbyper/datatype=" << ni.nbyper << "/" << ni.datatype << STD_endl;

    ODINLOG(odinlog,normalDebug) << "ni.pixdim[1/2/3]=" << ni.pixdim[1] << "/" << ni.pixdim[2] << "/" << ni.pixdim[3] << STD_endl;

    if(src.extent(0)) ni.dt=ni.pixdim[4] = prot.seqpars.get_RepetitionTime();

    //@todo we could save scale and offset here - intead of autoscale
    ni.scl_slope=1;
    ni.scl_inter=0.0;// http://209.85.135.104/search?q=cache:AxBp5gn9GzoJ:nifti.nimh.nih.gov/board/read.php%3Ff%3D1%26i%3D57%26t%3D57+nifti-1+scl_slope&hl=en&ct=clnk&cd=1&client=iceweasel-a

    ni.freq_dim=1;
    ni.phase_dim=2;
    ni.slice_dim=3;

    ni.xyz_units=NIFTI_UNITS_MM;
    ni.time_units=NIFTI_UNITS_MSEC;

    ni.fname=(char*)filename.c_str();

    STD_string imgfile; // Keep in scope for valid char* pointer
    if(fname.get_suffix()=="hdr") {
      ni.nifti_type=0; // ANALYZE
      imgfile=fname.get_dirname()+SEPARATOR_STR+fname.get_basename_nosuffix()+".img";
      ODINLOG(odinlog,normalDebug) << "imgfile=" << imgfile << STD_endl;
      ni.iname=(char*)imgfile.c_str();
    } else {
      ni.nifti_type=1; // NIFTI
      ni.iname=(char*)filename.c_str();
    }

    STD_string studydescr;
    STD_string physician;
    prot.study.get_Context(studydescr, physician);
    snprintf(ni.descrip, 80, "%s", studydescr.c_str());

    STD_string seriesdescr;
    int seriesnr;
    prot.study.get_Series(seriesdescr, seriesnr);
    snprintf(ni.intent_name, 16, "%s", seriesdescr.c_str());


    errno=0;                                      //reset errno
    nifti_image_write(&ni);                       //write the image - in case of a failure errno should be set
    if(errno) {
      //if so, tell the user, clean up and return -1
      ODINLOG(odinlog,errorLog) << "Could not write to "<< filename << "(" <<strerror(errno) << ")" << STD_endl;
      rmfile(filename.c_str());
      return -1;
    }
    else return 1;
  }
};
#endif                                            // NIFTISUPPORT

//////////////////////////////////////////////////////////////

void register_nifti_format() {
#ifdef NIFTISUPPORT
  static NiftiFormat nf;
  nf.register_format();
#endif
}