0
# C++ Library API
1
2
Core DICOM conversion engine for integration into C++ applications. The library provides low-level access to DICOM metadata and image data with full control over conversion parameters.
3
4
## Installation
5
6
### From Source
7
8
```bash
9
git clone https://github.com/rordenlab/dcm2niix.git
10
cd dcm2niix
11
mkdir build && cd build
12
cmake -DZLIB_IMPLEMENTATION=Cloudflare -DUSE_JPEGLS=ON -DUSE_OPENJPEG=ON ..
13
make
14
```
15
16
### Integration
17
18
Include the necessary headers in your C++ project:
19
20
```cpp
21
#include "nii_dicom_batch.h" // Main processing functions
22
#include "nii_dicom.h" // DICOM reading functions
23
#include "nifti1_io_core.h" // NIfTI structures
24
```
25
26
Link against the dcm2niix library or compile the source files directly into your project.
27
28
## Basic Usage
29
30
```cpp
31
#include "nii_dicom_batch.h"
32
33
int main() {
34
struct TDCMopts opts;
35
36
// Initialize with defaults
37
setDefaultOpts(&opts, NULL);
38
39
// Configure options
40
strcpy(opts.indir, "/path/to/dicom");
41
strcpy(opts.outdir, "/path/to/output");
42
opts.isGz = true; // Enable compression
43
opts.isCreateBIDS = true; // Generate BIDS sidecar
44
opts.isVerbose = 1; // Enable verbose output
45
46
// Process directory
47
int result = nii_loadDir(&opts);
48
49
if (result == EXIT_SUCCESS) {
50
printf("Conversion completed successfully\n");
51
} else {
52
printf("Conversion failed with code: %d\n", result);
53
}
54
55
return result;
56
}
57
```
58
59
## Capabilities
60
61
### Main Processing Functions
62
63
Core functions for directory and file processing.
64
65
```cpp { .api }
66
/**
67
* Main directory processing function
68
* @param opts - Configuration options for conversion
69
* @return Exit code (0=success, see exit codes for other values)
70
*/
71
int nii_loadDir(struct TDCMopts *opts);
72
73
/**
74
* Core directory processing implementation
75
* @param indir - Input directory path
76
* @param opts - Configuration options
77
* @return Exit code
78
*/
79
int nii_loadDirCore(char *indir, struct TDCMopts *opts);
80
81
/**
82
* Process single DICOM file
83
* @param opts - Configuration options (outdir, etc.)
84
* @param fname - Path to DICOM file
85
* @return Exit code
86
*/
87
int singleDICOM(struct TDCMopts *opts, char *fname);
88
```
89
90
**Usage Example:**
91
92
```cpp
93
struct TDCMopts opts;
94
setDefaultOpts(&opts, NULL);
95
96
// Process entire directory
97
strcpy(opts.indir, "/data/dicom");
98
int result = nii_loadDir(&opts);
99
100
// Process single file
101
strcpy(opts.outdir, "/data/output");
102
result = singleDICOM(&opts, "/data/dicom/image.dcm");
103
```
104
105
### DICOM Reading Functions
106
107
Low-level DICOM file reading and validation.
108
109
```cpp { .api }
110
/**
111
* Check if file is valid DICOM
112
* @param fname - Path to file
113
* @return 0=not DICOM, 1=valid DICOM, 2=uncertain (not Part 10 compliant)
114
*/
115
int isDICOMfile(const char *fname);
116
117
/**
118
* Read DICOM file with verbose output
119
* @param fname - Path to DICOM file
120
* @param isVerbose - Verbosity level (0-2)
121
* @param compressFlag - Compression handling flags
122
* @param dti4D - DTI/DWI data structure (can be NULL)
123
* @return TDICOMdata structure with metadata and image info
124
*/
125
struct TDICOMdata readDICOMv(char *fname, int isVerbose, int compressFlag, struct TDTI4D *dti4D);
126
127
/**
128
* Read DICOM file with preferences
129
* @param fname - Path to DICOM file
130
* @param prefs - Reading preferences
131
* @param dti4D - DTI/DWI data structure (can be NULL)
132
* @return TDICOMdata structure with metadata
133
*/
134
struct TDICOMdata readDICOMx(char *fname, struct TDCMprefs *prefs, struct TDTI4D *dti4D);
135
```
136
137
**Usage Example:**
138
139
```cpp
140
// Check if file is DICOM
141
if (isDICOMfile("image.dcm") == 1) {
142
// Read DICOM with verbose output
143
struct TDTI4D dti4D;
144
struct TDICOMdata dcm = readDICOMv("image.dcm", 1, 0, &dti4D);
145
146
printf("Series: %ld, Dimensions: %dx%dx%d\n",
147
dcm.seriesNum, dcm.xyzDim[1], dcm.xyzDim[2], dcm.xyzDim[3]);
148
}
149
```
150
151
### NIfTI Conversion Functions
152
153
Convert DICOM metadata to NIfTI format.
154
155
```cpp { .api }
156
/**
157
* Convert DICOM header to NIfTI header
158
* @param d - DICOM metadata
159
* @param h - NIfTI header structure to populate
160
* @param isComputeSForm - Whether to compute spatial transform
161
* @return Status code
162
*/
163
int headerDcm2Nii(struct TDICOMdata d, struct nifti_1_header *h, bool isComputeSForm);
164
165
/**
166
* Convert dual-echo DICOM headers to NIfTI
167
* @param d - First DICOM dataset
168
* @param d2 - Second DICOM dataset
169
* @param h - NIfTI header to populate
170
* @param isVerbose - Verbosity level
171
* @return Status code
172
*/
173
int headerDcm2Nii2(struct TDICOMdata d, struct TDICOMdata d2, struct nifti_1_header *h, int isVerbose);
174
175
/**
176
* Load image data from DICOM
177
* @param imgname - Path to image file
178
* @param hdr - NIfTI header with dimensions
179
* @param dcm - DICOM metadata
180
* @param iVaries - Whether intensity varies across slices
181
* @param compressFlag - Compression flags
182
* @param isVerbose - Verbosity level
183
* @param dti4D - DTI data (can be NULL)
184
* @return Pointer to image data buffer
185
*/
186
unsigned char *nii_loadImgXL(char *imgname, struct nifti_1_header *hdr,
187
struct TDICOMdata dcm, bool iVaries,
188
int compressFlag, int isVerbose, struct TDTI4D *dti4D);
189
```
190
191
**Usage Example:**
192
193
```cpp
194
struct TDICOMdata dcm = readDICOMv("image.dcm", 1, 0, NULL);
195
struct nifti_1_header hdr;
196
197
// Convert to NIfTI header
198
if (headerDcm2Nii(dcm, &hdr, true) == EXIT_SUCCESS) {
199
// Load image data
200
unsigned char *img = nii_loadImgXL("image.dcm", &hdr, dcm, false, 0, 1, NULL);
201
202
if (img) {
203
printf("Loaded image: %dx%dx%d, %d bytes per voxel\n",
204
hdr.dim[1], hdr.dim[2], hdr.dim[3], hdr.bitpix/8);
205
free(img);
206
}
207
}
208
```
209
210
### Configuration Functions
211
212
Manage conversion options and settings.
213
214
```cpp { .api }
215
/**
216
* Initialize options with default values
217
* @param opts - Options structure to initialize
218
* @param argv - Command line arguments (can be NULL)
219
*/
220
void setDefaultOpts(struct TDCMopts *opts, const char *argv[]);
221
222
/**
223
* Read configuration from INI file
224
* @param opts - Options structure to populate
225
* @param argv - Command line arguments for paths
226
*/
227
void readIniFile(struct TDCMopts *opts, const char *argv[]);
228
229
/**
230
* Save current options to INI file
231
* @param opts - Options to save
232
*/
233
void saveIniFile(struct TDCMopts opts);
234
235
/**
236
* Set default preferences for DICOM reading
237
* @param prefs - Preferences structure to initialize
238
*/
239
void setDefaultPrefs(struct TDCMprefs *prefs);
240
```
241
242
**Usage Example:**
243
244
```cpp
245
struct TDCMopts opts;
246
setDefaultOpts(&opts, NULL);
247
248
// Customize options
249
opts.isGz = true;
250
opts.gzLevel = 9;
251
opts.isCreateBIDS = true;
252
strcpy(opts.filename, "%p_%s_%t");
253
254
// Save configuration
255
saveIniFile(opts);
256
257
// Later, restore from file
258
readIniFile(&opts, NULL);
259
```
260
261
### Output Functions
262
263
Generate NIfTI files and BIDS metadata.
264
265
```cpp { .api }
266
/**
267
* Save NIfTI file with compression options
268
* @param niiFilename - Output filename
269
* @param hdr - NIfTI header
270
* @param im - Image data buffer
271
* @param opts - Conversion options
272
* @return Status code
273
*/
274
int nii_saveNIIx(char *niiFilename, struct nifti_1_header hdr,
275
unsigned char *im, struct TDCMopts opts);
276
277
/**
278
* Generate BIDS sidecar JSON file
279
* @param pathoutname - Output path and base name
280
* @param d - DICOM metadata
281
* @param opts - Conversion options
282
* @param h - NIfTI header
283
* @param filename - Input filename
284
*/
285
void nii_SaveBIDS(char pathoutname[], struct TDICOMdata d, struct TDCMopts opts,
286
struct nifti_1_header *h, const char *filename);
287
288
/**
289
* Create output filename from DICOM metadata
290
* @param dcm - DICOM metadata
291
* @param niiFilename - Buffer for generated filename
292
* @param opts - Options including filename format
293
* @return Status code
294
*/
295
int nii_createFilename(struct TDICOMdata dcm, char *niiFilename, struct TDCMopts opts);
296
```
297
298
**Usage Example:**
299
300
```cpp
301
struct nifti_1_header hdr;
302
unsigned char *img = /* loaded image data */;
303
struct TDICOMdata dcm = /* DICOM metadata */;
304
305
// Generate filename
306
char filename[512];
307
nii_createFilename(dcm, filename, opts);
308
309
// Save NIfTI file
310
nii_saveNIIx(filename, hdr, img, opts);
311
312
// Save BIDS sidecar
313
nii_SaveBIDS(filename, dcm, opts, &hdr, "source.dcm");
314
```
315
316
### FreeSurfer Wrapper (Optional)
317
318
Static wrapper class for MGZ-oriented conversion.
319
320
```cpp { .api }
321
/**
322
* FreeSurfer wrapper class for dcm2niix
323
*/
324
class dcm2niix_fswrapper {
325
public:
326
/**
327
* Set options for MGZ orientation output
328
* @param dcmindir - Input directory path
329
* @param dcm2niixopts - Additional options string
330
*/
331
static void setOpts(const char *dcmindir, const char *dcm2niixopts = NULL);
332
333
/**
334
* Check if file is DICOM
335
* @param file - File path to check
336
* @return true if DICOM, false otherwise
337
*/
338
static bool isDICOM(const char *file);
339
340
/**
341
* Convert one DICOM series
342
* @param dcmfile - Path to representative DICOM file
343
* @param convert - Whether to convert (true) or just analyze (false)
344
* @return Status code
345
*/
346
static int dcm2NiiOneSeries(const char *dcmfile, bool convert = true);
347
348
/**
349
* Convert single DICOM file
350
* @param dcmfile - Path to DICOM file
351
* @return Status code
352
*/
353
static int dcm2NiiSingleFile(const char* dcmfile);
354
355
/**
356
* Get conversion results structure
357
* @return Pointer to results structure
358
*/
359
static MRIFSSTRUCT *getMrifsStruct(void);
360
361
/**
362
* Get NIfTI header from results
363
* @return Pointer to NIfTI header
364
*/
365
static nifti_1_header *getNiiHeader(void);
366
367
/**
368
* Get image data from results
369
* @return Pointer to image data
370
*/
371
static const unsigned char *getMRIimg(void);
372
};
373
```
374
375
## Data Structures
376
377
### TDCMopts - Main Configuration
378
379
```cpp { .api }
380
/**
381
* Main configuration structure for dcm2niix
382
*/
383
struct TDCMopts {
384
// === Boolean Options ===
385
bool isDumpNotConvert; // Dump info instead of convert
386
bool isIgnoreTriggerTimes; // Ignore trigger timing
387
bool isAddNamePostFixes; // Add postfixes to filenames
388
bool isSaveNativeEndian; // Use native byte order
389
bool isOneDirAtATime; // Process one directory at a time
390
bool isRenameNotConvert; // Rename files instead of convert
391
bool isSave3D; // Save as 3D instead of 4D
392
bool isGz; // Enable gzip compression
393
bool isPipedGz; // Use piped compression
394
bool isFlipY; // Flip Y axis
395
bool isCreateBIDS; // Generate BIDS sidecar
396
bool isSortDTIbyBVal; // Sort DTI by b-value
397
bool isAnonymizeBIDS; // Anonymize BIDS output
398
bool isOnlyBIDS; // Generate only BIDS (no NIfTI)
399
bool isCreateText; // Create text output
400
bool isForceOnsetTimes; // Force onset times
401
bool isIgnoreDerivedAnd2D; // Ignore derived and 2D images
402
bool isPhilipsFloatNotDisplayScaling; // Philips float scaling
403
bool isTiltCorrect; // Apply tilt correction
404
bool isRGBplanar; // RGB planar format
405
bool isOnlySingleFile; // Process only single file
406
bool isForceStackDCE; // Force stack DCE
407
bool isIgnoreSeriesInstanceUID; // Ignore Series Instance UID
408
bool isRotate3DAcq; // Rotate 3D acquisitions
409
bool isCrop; // Crop images
410
bool isGuessBidsFilename; // Guess BIDS filename
411
412
// === Integer Options ===
413
int saveFormat; // Output format (NIfTI=0, NRRD=1, etc.)
414
int isMaximize16BitRange; // 16-bit scaling behavior
415
int isForceStackSameSeries; // Force stack same series
416
int nameConflictBehavior; // Name conflict resolution
417
int isVerbose; // Verbosity level (0-2)
418
int isProgress; // Progress reporting
419
int compressFlag; // Compression flags
420
int dirSearchDepth; // Directory search depth (0-9)
421
int onlySearchDirForDICOM; // Search behavior
422
int gzLevel; // Compression level (1-9)
423
int diffCyclingModeGE; // GE diffusion cycling mode
424
425
// === String Paths ===
426
char filename[512]; // Filename format template
427
char outdir[512]; // Output directory
428
char indir[512]; // Input directory
429
char pigzname[512]; // Pigz executable path
430
char optsname[512]; // Options file path
431
char indirParent[512]; // Parent directory
432
char imageComments[24]; // Image comments
433
char bidsSubject[512]; // BIDS subject ID
434
char bidsSession[512]; // BIDS session ID
435
436
// === Series Selection ===
437
double seriesNumber[16]; // Series numbers to convert
438
long numSeries; // Number of series specified
439
};
440
```
441
442
### TDICOMdata - DICOM Metadata
443
444
```cpp { .api }
445
/**
446
* DICOM metadata and image information
447
*/
448
struct TDICOMdata {
449
// === Basic Information ===
450
long seriesNum; // Series number
451
int xyzDim[5]; // Image dimensions [0,x,y,z,t]
452
uint32_t coilCrc; // Coil CRC
453
uint32_t seriesUidCrc; // Series UID CRC
454
uint32_t instanceUidCrc; // Instance UID CRC
455
456
// === Image Properties ===
457
int imageBytes; // Size of image data
458
int bitsStored; // Bits stored per pixel
459
int bitsAllocated; // Bits allocated per pixel
460
int samplesPerPixel; // Samples per pixel (1=grayscale, 3=RGB)
461
int compressionScheme; // Compression method
462
463
// === Spatial Information ===
464
float pixelSpacing[3]; // Voxel spacing [x,y,z]
465
float sliceThickness; // Slice thickness
466
float fieldStrength; // Magnetic field strength
467
float flipAngle; // Flip angle in degrees
468
float TE; // Echo time (ms)
469
float TR; // Repetition time (ms)
470
float TI; // Inversion time (ms)
471
472
// === Acquisition Parameters ===
473
int manufacturer; // Vendor code (Siemens=1, GE=2, etc.)
474
int modality; // Modality (MR=3, CT=2, etc.)
475
int echoNum; // Echo number
476
int acquNum; // Acquisition number
477
int frameNum; // Frame number
478
int imageNum; // Image number
479
int phaseNumber; // Phase number
480
481
// === String Fields ===
482
char protocolName[64]; // Acquisition protocol name
483
char seriesDescription[64]; // Series description
484
char scanningSequence[16]; // Scanning sequence
485
char sequenceVariant[16]; // Sequence variant
486
char scanOptions[32]; // Scan options
487
char institutionName[64]; // Institution name
488
char referringPhysicianName[64]; // Referring physician
489
char studyDate[12]; // Study date YYYYMMDD
490
char studyTime[16]; // Study time HHMMSS
491
char patientName[64]; // Patient name
492
char patientID[64]; // Patient ID
493
char patientBirthDate[12]; // Birth date YYYYMMDD
494
char patientSex[4]; // Patient sex (M/F/O)
495
char studyInstanceUID[128]; // Study Instance UID
496
char seriesInstanceUID[128]; // Series Instance UID
497
char imageOrientationPatient[6]; // Image orientation
498
char imagePositionPatient[3]; // Image position
499
500
// === Advanced Fields ===
501
int sliceOrient; // Slice orientation code
502
int converted2NII; // Conversion status
503
int locationsInAcquisition; // Number of locations
504
int phaseEncodingLines; // Phase encoding lines
505
int frequencyEncodingSteps; // Frequency encoding steps
506
int echoTrainLength; // Echo train length
507
};
508
```
509
510
### TDTI4D - DTI/DWI Data
511
512
```cpp { .api }
513
/**
514
* Diffusion tensor imaging data for 4D volumes
515
*/
516
struct TDTI4D {
517
struct TDTI S[16384]; // DTI gradient information
518
int sliceOrder[65535]; // Slice ordering for 4D reconstruction
519
size_t offsetTable[65535]; // Basic offset table for slices
520
int gradDynVol[16384]; // Volume organization info
521
};
522
523
/**
524
* Individual DTI gradient information
525
*/
526
struct TDTI {
527
float V[4]; // Gradient vector [x,y,z] + b-value
528
};
529
```
530
531
### TDCMprefs - Reading Preferences
532
533
```cpp { .api }
534
/**
535
* DICOM reading preferences
536
*/
537
struct TDCMprefs {
538
int isVerbose; // Verbosity level (0-2)
539
int compressFlag; // Compression handling flags
540
int isIgnoreTriggerTimes; // Ignore trigger timing values
541
};
542
```
543
544
## Exit Codes
545
546
```cpp { .api }
547
// Standard exit codes
548
#define EXIT_SUCCESS 0 // Success
549
#define EXIT_FAILURE 1 // General failure
550
551
// dcm2niix specific exit codes
552
#define kEXIT_NO_VALID_FILES_FOUND 2 // No valid DICOM files
553
#define kEXIT_REPORT_VERSION 3 // Version reported
554
#define kEXIT_CORRUPT_FILE_FOUND 4 // Corrupt file encountered
555
#define kEXIT_INPUT_FOLDER_INVALID 5 // Invalid input folder
556
#define kEXIT_OUTPUT_FOLDER_INVALID 6 // Invalid output folder
557
#define kEXIT_OUTPUT_FOLDER_READ_ONLY 7 // Read-only output folder
558
#define kEXIT_SOME_OK_SOME_BAD 8 // Partial success
559
#define kEXIT_RENAME_ERROR 9 // File rename error
560
#define kEXIT_INCOMPLETE_VOLUMES_FOUND 10 // Incomplete volumes
561
#define kEXIT_NOMINAL 11 // Nominal (no conversion expected)
562
```
563
564
## Constants
565
566
```cpp { .api }
567
// Manufacturer codes
568
#define kMANUFACTURER_UNKNOWN 0
569
#define kMANUFACTURER_SIEMENS 1
570
#define kMANUFACTURER_GE 2
571
#define kMANUFACTURER_PHILIPS 3
572
#define kMANUFACTURER_TOSHIBA 4
573
#define kMANUFACTURER_UIH 5
574
#define kMANUFACTURER_BRUKER 6
575
#define kMANUFACTURER_HITACHI 7
576
#define kMANUFACTURER_CANON 8
577
578
// Save format codes
579
#define kSaveFormatNIfTI 0
580
#define kSaveFormatNRRD 1
581
#define kSaveFormatMGH 2
582
#define kSaveFormatJNII 3
583
#define kSaveFormatBNII 4
584
585
// Name conflict behavior
586
#define kNAME_CONFLICT_SKIP 0 // Skip existing files
587
#define kNAME_CONFLICT_OVERWRITE 1 // Overwrite existing files
588
#define kNAME_CONFLICT_ADD_SUFFIX 2 // Add suffix to avoid conflicts
589
590
// 16-bit scaling options
591
#define kMaximize16BitRange_False 0 // Preserve original range
592
#define kMaximize16BitRange_True 1 // Scale to full range
593
#define kMaximize16BitRange_Raw 2 // Keep raw data type
594
```
595
596
## Error Handling
597
598
```cpp
599
#include "nii_dicom_batch.h"
600
#include <iostream>
601
602
int processDirectory(const char* inputDir, const char* outputDir) {
603
struct TDCMopts opts;
604
setDefaultOpts(&opts, NULL);
605
606
strcpy(opts.indir, inputDir);
607
strcpy(opts.outdir, outputDir);
608
opts.isVerbose = 1; // Enable error reporting
609
610
int result = nii_loadDir(&opts);
611
612
switch (result) {
613
case EXIT_SUCCESS:
614
std::cout << "Conversion completed successfully" << std::endl;
615
break;
616
case kEXIT_NO_VALID_FILES_FOUND:
617
std::cerr << "No valid DICOM files found in " << inputDir << std::endl;
618
break;
619
case kEXIT_CORRUPT_FILE_FOUND:
620
std::cerr << "Corrupt DICOM file encountered" << std::endl;
621
break;
622
case kEXIT_INPUT_FOLDER_INVALID:
623
std::cerr << "Input folder is invalid: " << inputDir << std::endl;
624
break;
625
case kEXIT_OUTPUT_FOLDER_INVALID:
626
std::cerr << "Output folder is invalid: " << outputDir << std::endl;
627
break;
628
case kEXIT_SOME_OK_SOME_BAD:
629
std::cerr << "Some files converted successfully, others failed" << std::endl;
630
break;
631
default:
632
std::cerr << "Conversion failed with exit code: " << result << std::endl;
633
}
634
635
return result;
636
}
637
```
638
639
## Build Configuration
640
641
### CMake Options
642
643
```cmake
644
# Basic build
645
cmake ..
646
647
# With enhanced format support
648
cmake -DUSE_JPEGLS=ON -DUSE_OPENJPEG=ON -DUSE_TURBOJPEG=ON ..
649
650
# Build FreeSurfer wrapper library
651
cmake -DBUILD_DCM2NIIXFSLIB=ON ..
652
653
# Use system zlib
654
cmake -DZLIB_IMPLEMENTATION=System ..
655
```
656
657
### Preprocessor Definitions
658
659
```cpp
660
// Enable specific features during compilation
661
#define USING_DCM2NIIXFSWRAPPER // FreeSurfer wrapper
662
#define myEnableJPEGLS // JPEG-LS support
663
#define myEnableJasper // JPEG2000 via Jasper
664
#define myTurboJPEG // TurboJPEG support
665
#define myEnableJNIFTI // JSON NIfTI support
666
```