]> Creatis software - gdcm.git/blob - Doc/Website/HowToUseGdcm.html
Add a (very) small User Guide.
[gdcm.git] / Doc / Website / HowToUseGdcm.html
1 <pre>
2 {{{
3 This is a vi-able/notepad-able document to (try to) explain in a few words 
4 how to use efficently gdcm.
5 -->Feel free to send/add your comments/suggestions/modifications.
6 -->Don't try to 'beautify' this page.
7 (I plane to rewrite it, and add it to the gdcm site as soon as 
8 there is enough 'content' within it)
9
10 HTH
11 Jean-Pierre Roux
12
13 ------------------------------------------------------------------------
14 0) Intro
15 1) How to Read a DICOM file
16 1-1) using raw C++
17 1-1-1) A single file
18 1-1-2) A File Set
19 1-2) using VTK
20 1-2-1) A single file
21 1-2-2) A File Set
22 1-3) using ITK
23 1-3-1) A single file
24 1-3-2) A File Set
25 1-4) Retrictions for Python users
26
27 2) How to write DICOM file
28 2-1) using raw C++
29 2-1-1) A single file
30 2-1-2) A File Set
31 2-2) using VTK
32 2-3) using ITK
33
34 ----------------------------------------------------------------------------
35
36 0) Intro
37 --------
38
39 If you are not familiar with DICOM files , use :
40
41 PrintFile filein=yourDicomFile.dcm
42
43 and have a look at the output.
44 You'll see a lot of self explanatory (?) lines, e.g.
45
46 D 0008|0021 [DA]   [Series Date]     [20020524]
47 D 0008|0060 [CS]   [Modality]        [US]
48 D 0018|602c [FD]   [Physical Delta X][0]
49 D 0020|0013 [IS]   [Instance Number] [5 ]
50 D 0028|0010 [US]   [Rows]            [480]
51 D 0011|0010 [  ]   [gdcm::Unknown]   [DLX_PATNT_01]
52
53 0008|0021 : 'Group Number'|'Element Number' -> The Element identifier
54 Have a look at gdcm/Dicts/dicomV3.dic for the whole list of Elements
55  
56 DA        : The 'Value Representation' : DA for Date, US for Unsigned Short, ...
57 Have a look at gdcm/Dicts/dicomVR.dic for the set of possible values
58  
59 [Series Date] : The 'official' English name of the Element
60 (When *you* have to deal with a given Element, its meaning should be clear for
61 *you*)
62
63 [20020524] : the value, printed in a human readable way.
64
65 If something like :
66 D 0028|1222 [OW] [Segmented Green Palette Color Lookup Table Data]
67                                  ===> [gdcm::Binary data loaded;length = 113784]
68 is displayed, it means that it's a 'long' binary area, gdcm (I) decided not to
69 show.
70
71 D 0011|0010 [  ]   [gdcm::Unknown]   [DLX_PATNT_01]
72 is a 'Private (or Shadow) Element', depending on the manufacturer.
73 It's *not* known within the 'official' Dicom Dictionnary.
74 Except if someone told you, you cannot guess the meaning of such an element.
75 Probabely, you'll never have to deal with Shadow Elements (hope so!).
76
77 You can find also something like : 
78
79 S 0018|6011 [SQ]                       [Sequence of Ultrasound Regions]
80    |  --- SQItem number 0
81    | D fffe|e000 [UL]                               [Item]
82    | D 0018|6018 [UL]             [Region Location Min X0] [32]
83    | D 0018|601a [UL]             [Region Location Min Y0] [24]
84    | D 0018|601c [UL]             [Region Location Max X1] [335]
85    | D 0018|601e [UL]             [Region Location Max Y1] [415]
86    | D 0018|602c [FD]                   [Physical Delta X] [0.0382653]
87    | D 0018|602e [FD]                   [Physical Delta Y] [0.0382653]
88    |  --- SQItem number 1
89    | D fffe|e000 [UL]                               [Item]
90    | D 0018|6018 [UL]             [Region Location Min X0] [336]
91    | D 0018|601a [UL]             [Region Location Min Y0] [24]
92    | D 0018|601c [UL]             [Region Location Max X1] [639]
93    | D 0018|601e [UL]             [Region Location Max Y1] [415]
94    | D 0018|602c [FD]                   [Physical Delta X] [0.0382653]
95    | D 0018|602e [FD]                   [Physical Delta Y] [0.0382653]
96    |  --- SQItem number 2
97    | D fffe|e000 [UL]                               [Item]
98    | D 0018|6018 [UL]             [Region Location Min X0] [32]
99    | D 0018|601a [UL]             [Region Location Min Y0] [40]
100    | D 0018|601c [UL]             [Region Location Max X1] [63]
101    | D 0018|601e [UL]             [Region Location Max Y1] [103]
102    | D 0018|6024 [US]         [Physical Units X Direction] [0]
103    | D 0018|6026 [US]         [Physical Units Y Direction] [0]
104    | D 0018|602c [FD]                   [Physical Delta X] [0]
105    | D 0018|602e [FD]                   [Physical Delta Y] [0]
106
107 0018|6011 is a 'Sequence' (SQ), composed of various Sequence Items(SQItem)
108 Each SQItem is a set of Elements (an Element may be a DataElement (D) or a
109 Sequence (S), recursively.
110 Probabely, you'll never have to deal with Sequences (hope so!).
111
112 1) How to Read a DICOM File
113 ===========================
114
115 1-1) using raw C++
116 ------------------
117
118 1-1-1) A single file
119 --------------------
120
121 The first step is to load the file header :
122
123            gdcm::File *f = new gdcm::File();
124                   f->SetLoadMode(NO_SEQ);            | depending on what
125                   f->SetLoadMode(NO_SHADOW);         | you want *not* 
126                   f->SetLoadMode(NO_SEQ | NO_SHADOW);| to load from the
127                   f->SetLoadMode(NO_SHADOWSEQ);      | target file
128             f->SetFileName(fileName);
129             f->Load( );
130     
131 Except if someone told you -he knows the file headers are bugged-, 
132 do *not* use SetLoadMode().
133
134 Check if the file is gdcm-readable.
135
136            if ( !f->IsReadable() )
137              std::cout << "major troubles on [" << f->GetFileName() <<"]"
138                        << std::endl;
139
140 Decide if this is a 'File Of Interest' for you.
141 Check some fields, e.g
142
143            std::string StudyDate           = f->GetEntryString(0x0008,0x0020);
144            std::string PatientName         = f->GetEntryString(0x0010,0x0010);
145            std::string PatientID           = f->GetEntryString(0x0010,0x0020);
146            std::string PatientSex          = f->GetEntryString(0x0010,0x0040);
147            std::string Modality            = f->GetEntryString(0x0008,0x0060);
148
149 (or whatever you feel like ...)
150
151 Next step is to load the pixels in memory.
152 Uncompression (JPEG lossless, JPEG lossy, JPEG 2000, RLE, ...) 
153 is automatically performed if necessary.
154
155            gdcm::FileHelper *fh = gdcm::FileHelper::New(f);
156            void *imageData = fh->GetImageDataRaw();
157            uint32_t dataSize = fh->GetImageDataRawSize();
158
159 Generally, you work on 'Grey level' images (as opposed to RGB images).
160 Depending on the Pixel size (8/16/32 bits) and the Pixel Type (signed/unsigned),
161 you cast the imageData
162
163           std::string pixelType = f->GetPixelType();
164   
165 Possible values are : 
166
167 - "8U"  unsigned  8 bit,
168 - "8S"    signed  8 bit,
169 - "16U" unsigned 16 bit,
170 - "16S"   signed 16 bit,
171 - "32U" unsigned 32 bit,
172 - "32S"   signed 32 bit,
173
174    
175            int dimX = f->GetXcurrentFileName[i]Size();
176            int dimY = f->GetYSize();
177            int dimZ = f->GetZSize();
178            int dimT = f->GetTSize();
179
180 Now, you can enjoy your image !
181
182 Sometimes, you deal with 'colour' images :-(
183 They may be stored, on disc, as RGB pixels, RGB planes, YBR pixels, YBR planes
184 Grey level images + LUT.
185
186 You'll get an 'RGB Pixels' image in memory if you use: 
187
188            gdcm::FileHelper *fh = gdcm::FileHelper::New(f);
189            void *imageData = fh->GetImageData();
190            uint32_t dataSize = fh->GetImageDataSize();
191
192
193 1-1-2) A File Set
194 -----------------
195
196 If you are 150 % sure of the files you're dealing with, just read the files you
197 feel like, and concatenate the pixels.
198
199 Sometimes you are not sure at all (say : you were given a CDROM with an amount
200 of images, laying in a Directories tree-like structure, you don't know anything
201 about the Patients, and so on)
202
203 A class gdcm::SerieHelper is designed to help solving this problem.
204 Use it as follows.
205
206     gdcm::SerieHelper *sh = gdcm::SerieHelper::New();
207     while (int i=0; i<nbOfFiles; i++) {
208        sh->AddFileName(currentFileName[i]);
209     }
210     
211 You can also pass a 'root directory', and ask or not for recursive parsing.
212     gdcm::SerieHelper *sh = gdcm::SerieHelper::New();
213     sh->SetDirectory(yourRootDirectoryName, true); // true : recursive parsing
214
215 Files are 'splitted' into as many 'Single Serie UID File Set' 
216   as Series Instance UID ( 0020|000e );
217   
218 If you want to 'order' the files within each 'Single Serie UID File Set'
219 (to build a volume, for instance), use :
220   
221    gdcm::FileList *l = sh->GetFirstSingleSerieUIDFileSet();
222    while (l)
223    { 
224       sh->OrderFileList(l);  // sort the list
225       l = sh->GetNextSingleSerieUIDFileSet();
226    } 
227     
228   The sorting will be performed on the ImagePositionPatient;
229   if not found, on ImageNumber;
230   if not found, on the File Name.
231   
232   Aware user is allowed to pass his own comparison function 
233   (if he knows, for instance, the files must be sorted on 'Trigger Time')
234   He will use the method
235   void SerieHelper::SetUserLessThanFunction( bool(*) userFunc((File *,File *) ); 
236   He may ask for a reverse sorting : 
237   sh->SetSortOrderToReverse();
238   or back to Direct Order 
239   sh->SetSortOrderToDirect();
240   
241   If, for any reason of is own, user already get the file headers,
242   he may add the gdcm::File (instead of the file name) to the SerieHelper.
243
244     gdcm::SerieHelper *sh = gdcm::SerieHelper::New();
245     while (int i=0; i<nbOfFiles; i++) {
246        sh->AddFile(currentFile[i]);
247     }                           
248  * \warning : this method should be used by aware users only!
249  *            User is supposed to know the files he want to deal with
250  *           and consider them they belong to the same Set
251  *           (even if their Serie UID is different)
252  *           user will probabely OrderFileList() this list (actually, ordering
253  *           user choosen gdm::File is the sole interest of this method)
254  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
255  *           vtkGdcmReader parsing twice the same files.
256  *           *no* coherence check is performed, but those specified
257  *           by SerieHelper::AddRestriction()
258  
259    User may want to exclude some files.
260    He will use
261     void SerieHelper::AddRestriction(uint16_t group, uint16_t elem,
262                                  std::string const &value, int op);
263 op belongs to :
264
265 /// \brief comparaison operators
266    GDCM_EQUAL ,
267    GDCM_DIFFERENT,
268    GDCM_GREATER,
269    GDCM_GREATEROREQUAL,
270    GDCM_LESS,
271    GDCM_LESSOREQUAL
272 e.g. 
273     gdcm::SerieHelper *sh = gdcm::SerieHelper::New();
274     sh->AddRestriction(0x0010,0x0040,"F",GDCM_EQUAL);      // Patient's Sex
275     sh->AddRestriction(0x0008,0x0060,"MR",GDCM_DIFFERENT); // Modality 
276     while (int i=0; i<nbOfFiles; i++) { 
277     ...
278 User wants to deal only with Female patient, any Modality but MR (why not?)
279
280 Sometimes the previous stuff is *not enough* !
281
282 Within a SingleSerieUIDFileSet, you can have have various orientations,
283 or various positions, at various times. (not only various position , at a single
284 time, for a single orientation).
285
286 User may consider that dealing only with the 'Series Instance UID' 
287 is not enough and wishes to 'refine' the image selection :
288
289 Suppose he has a Single Serie UID File Set (gdcm::FileList).
290 He may ask to split it into several 'X Coherent File Sets' (X stands for
291 'Extra').
292
293 gdcm::SerieHelper *s;
294 gdcm::XCoherentFileSetmap xcm;
295 gdcm::FileList *l = s->GetFirstSingleSerieUIDFileSet(); // or what you want
296
297
298  The following methods must be called by user, depending on 
299  what *he* wants to do, at application time.
300   - *he* only  knows what his Series contain ! - 
301  They return a std::map of Filesets (actually : std::vector of gdcm::File*).
302  
303 He may ask for 'splitting' on the Orientation:
304            xcm = s->SplitOnOrientation(l);
305    
306 He may ask for 'splitting' on the Position:
307            xcm = s->SplitOnPosition(l);
308    
309 He may ask for 'splitting' on the any DataElement you feel like :   
310            xcm = s->SplitOnTagValue(l, groupelem[0],groupelem[1]);
311
312  
313 He can now work on each 'X Coherent File Set' within the std::map
314
315 for (gdcm::XCoherentFileSetmap::iterator i = xcm.begin();
316                                          i != xcm.end();
317                                        ++i)
318 {
319
320    // ask for 'ordering' according to the 'Image Position Patient'
321    s->OrderFileList((*i).second);  // sort the XCoherent Fileset
322 }  
323
324 (have a look at gdcm/Examples/exXCoherentFileSet.cxx for an exmaple)
325
326 1-2) using VTK
327 --------------
328 a vtkGdcmReader() method ( derived from vtkReader() ) is available.
329
330
331
332 1-2-1) A single file
333 --------------------
334
335    vtkGdcmReader *reader = vtkGdcmReader::New();
336    reader->SetFileName( yourDicomFilename );      
337    reader->SetLoadMode( yourLoadMode); // See C++ part 
338    reader->Update();
339    vtkImageData* ima = reader->GetOutput();
340    int* Size = ima->GetDimensions();   
341  // -> Enjoy it.     
342
343 1-2-2) A File Set
344 -----------------
345
346 If you are 150 % sure of the files you're dealing with, just 'add' the files you
347 feel like:
348
349    vtkGdcmReader *reader = vtkGdcmReader::New();
350    for(int i=1; i< yourNumberOfFiles; i++)
351          reader->AddFileName( yourTableOfFileNames[i] );     
352    reader->SetLoadMode( yourLoadMode); // See C++ part 
353    reader->Update();
354    vtkImageData* ima = reader->GetOutput();
355    int* Size = ima->GetDimensions();
356  // -> Enjoy it.
357  
358  Warning : The first file is assumed to be the reference file.
359  All the inconsistent files (different sizes, pixel types, etc) are discarted
360  and replaced by a black image ! 
361  
362       User is allowed to pass a Pointer to a function of his own
363       to allow modification of pixel order (i.e. : Mirror, TopDown, )
364       to gdcm::FileHeleper, using SetUserFunction(userSuppliedFunction)
365
366       described as : void userSuppliedFunction(uint8_t *im, gdcm::File *f);
367
368       NB : the "uint8_t *" type of first param is just for prototyping.
369         User will Cast it according what he found with f->GetPixelType()
370         See vtkgdcmSerieViewer for an example
371  
372
373 Many users expect from vtkGdcmReader it 'orders' the images 
374 (Actually, that's the job of gdcm::SerieHelper ...)
375 When user knows the files with same Serie UID have same sizes, 
376 same 'pixel' type, same color convention, ... 
377 the right way to proceed is as follow :
378
379         gdcm::SerieHelper *sh= new gdcm::SerieHelper();
380    //      if user wants *not* to load some parts of the file headers
381         sh->SetLoadMode(yourLoadMode);
382
383    //      if user wants *not* to load some files
384         sh->AddRestriction(group, element, value, operator);
385         sh->AddRestriction( ...
386         sh->SetDirectory(directoryWithImages);
387
388    //      if user *knows* how to order his files
389         sh->SetUserLessThanFunction(userSuppliedComparisonFunction);
390    //      or/and
391    //      if user wants to sort reverse order
392         sh->SetSortOrderToReverse();
393    
394    //      here, we suppose only the first 'Single SerieUID' Fileset is of interest
395    //      Just iterate using sh->NextSingleSerieUIDFileSet()
396    //      if you want to get all of them
397         gdcm::FileList *l = sh->GetFirstSingleSerieUIDFileSet();
398
399    //      if user is doesn't trust too much the files with same Serie UID
400         if ( !sh->IsCoherent(l) )
401            return; // not same sizes, or not same 'pixel type' -> stop
402
403         sh->OrderFileList(l);        // sort the list (*)
404
405         vtkGdcmReader *reader = vtkGdcmReader::New();
406    //      if user wants to modify pixel order (Mirror, TopDown, ...)
407    //      he has to supply the function that does the job
408    //      (a *very* simple example is given in vtkgdcmSerieViewer.cxx)
409         reader->SetUserFunction (userSuppliedFunction);
410
411    //      to pass a 'Single SerieUID' Fileset as produced by gdcm::SerieHelper
412         reader->SetCoherentFileList(l);
413         reader->Update();
414
415
416 //-----------------
417 (*)
418 User may also pass an 'X Coherent Fileset', created by one of the following
419 methods : (see 1-1-2 for more details)
420  
421            xcm = sh->SplitOnOrientation(l); 
422            xcm = sh->SplitOnPosition(l);   
423            xcm = sh->SplitOnTagValue(l, groupelem[0],groupelem[1]);
424 //----------------
425
426 You can see a full example in vtk/vtkgdcmSerieViewer.cxx
427 e.g.
428 vtkgdcmSerieViewer dirname=Dentist mirror
429 vtkgdcmSerieViewer dirname=Dentist reverse
430 vtkgdcmSerieViewer dirname=Dentist reverse upsidedown
431
432
433 1-4) Retrictions for Python users
434 ---------------------------------
435
436 None of the methods receiving a function pointer, or a gdcm::File as a parameter
437 is wrapable by swig.
438 :-(
439
440
441 2) How to write DICOM file
442 ==========================
443
444    // gdcm cannot guess how user built his image 
445    //  (and therefore cannot be clever about some Dicom fields)
446    // It's up to the user to tell gdcm what he did.
447    // -1) user created ex nihilo his own image and wants to write it 
448    //     as a Dicom image.
449    // USER_OWN_IMAGE
450    // -2) user modified the pixels of an existing image.
451    // FILTERED_IMAGE
452    // -3) user created a new image, using existing a set of images 
453    //    (eg MIP, MPR, cartography image)
454    //  CREATED_IMAGE
455    // -4) user modified/added some tags *without processing* the pixels 
456    //     (anonymization..
457    //  UNMODIFIED_PIXELS_IMAGE
458    // -Probabely some more to be added
459    //(see gdcmFileHelper.h for more explanations)
460    
461    // User is allowed to use the following methods:
462    
463    void SetContentTypeToUserOwnImage()         
464                     {SetContentType(VTK_GDCM_WRITE_TYPE_USER_OWN_IMAGE);}
465    void SetContentTypeToFilteredImage()        
466                     {SetContentType(VTK_GDCM_WRITE_TYPE_FILTERED_IMAGE);}
467    void SetContentTypeToUserCreatedImage()     
468                     {SetContentType(VTK_GDCM_WRITE_TYPE_CREATED_IMAGE);}
469    void SetContentTypeToUnmodifiedPixelsImage()
470                     {SetContentType(VTK_GDCM_WRITE_TYPE_UNMODIFIED_PIXELS_IMAGE);}
471
472 2-1) using raw C++
473 ------------------
474 In C++, if you have already the pixels in main memory, 
475 you just have to process as follow :
476
477 --> Create an empty gdcm::File
478         gdcm::File *file = gdcm::File::New();
479
480         std::ostringstream str;
481
482 // --> Set the mandatory fields
483 // Set the image size
484         str.str("");
485         str << sizeX;
486         file->InsertEntryString(str.c_str(),0x0028,0x0011,"US"); // Columns
487         str.str("");
488         str << sizeY;
489         file->InsertEntryString(str.c_str(),0x0028,0x0011,"US"); // Columns
490         str.str("");
491         str << sizeZ;
492         file->InsertEntryString(str.c_str(),0x0028,0x0008, "IS"); // Nbr of Frames
493           // Set the pixel type
494         str.str("");
495         str << componentSize; //8, 16, 32
496         file->InsertEntryString(str.c_str(),0x0028,0x0100,"US"); // Bits Allocated
497         str.str("");
498         str << componentUse; // may be 12 or 16 if componentSize =16
499         file->InsertEntryString(str.c_str(),0x0028,0x0101,"US"); // Bits Stored
500         str.str("");
501         str << componentSize - 1 ;
502         file->InsertEntryString(str.c_str(),0x0028,0x0102,"US"); // High Bit
503   // Set the pixel representation // 0/1
504         str.str("");
505         str << img.sign;
506         file->InsertEntryString(str.c_str(),0x0028,0x0103, "US"); // Pixel Representation
507   // Set the samples per pixel // 1:Grey level, 3:RGB
508         str.str("");
509         str << components;
510         file->InsertEntryString(str.c_str(),0x0028,0x0002, "US"); // Samples per Pixel
511
512 //--> Set Optional fields
513 //(patient name, patient ID, modality, or what you want
514 //Have look at gdcm/Dict/dicomV3.dic to see what are the various DICOM fields)
515
516 //--> Create a gdcm::FileHelper
517
518        gdcm::FileHelper *fileH = gdcm::FileHelper::New(file);
519        fileH->SetImageData((unsigned char *)imageData,size);
520        
521 //casting as 'unsigned char *' is just to avoid warnings.
522 // It doesn't change the values.
523
524       fileH->SetWriteModeToRaw();
525       fileH->SetWriteTypeToDcmExplVR();
526       fileH->Write(fileName.str());
527
528 //This works for a single image (singleframe or multiframe)
529
530 // If you deal with a Serie of images, it up to you to tell gdcm, for each image,
531 // what are the values of
532 // 0020 0032 DS 3 Image Position (Patient)
533 // 0020 0037 DS 6 Image Orientation (Patient) 
534
535 2-1-1) A single file
536 --------------------
537 /// \todo : write it!
538
539 2-1-2) A File Set
540 -----------------
541 /// \todo : write it!
542
543
544
545 2-2) using VTK
546 --------------
547
548 2-2-1) A single file
549 --------------------
550
551 // User of the CVS version of VTK 5 may set some 'Medical Image Properties'
552 // Only the predefined DataElements are available :
553 // PatientName, PatientID, PatientAge, PatientSex, PatientBirthDate, StudyID
554 // It's reasonablt enough for any 'decent use'
555 vtkMedicalImageProperties
556
557    // Aware user is allowed to pass his own gdcm::File *, 
558    //  so he may set *any Dicom field* he wants.
559    // (including his own Shadow Eleents, or any gdcm::SeqEntry)
560    // gdcm::FileHelper::CheckMandatoryElements() will check inconsistencies,
561    // as far as it knows how.
562    // Sorry, not yet available under Python.
563 vtkSetMacro(GdcmFile, gdcm::File *);
564
565
566 2-2-2) A File Set
567 -----------------
568 /// \todo : write it!
569
570
571 2-3) using ITK
572 --------------
573 /// \todo : write it!
574
575 }}}
576 </pre>