]> Creatis software - gdcm.git/blob - Example/ReWrite.cxx
Deal with JPEG/JPEG2000 writting
[gdcm.git] / Example / ReWrite.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: ReWrite.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/08/24 10:48:08 $
7   Version:   $Revision: 1.30 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18 #include "gdcmFile.h"
19 #include "gdcmFileHelper.h"
20 #include "gdcmDebug.h"
21
22 #include "gdcmArgMgr.h"
23
24 #include <string.h> // for memcpy
25 #include <iostream>
26
27 int main(int argc, char *argv[])
28 {
29    START_USAGE(usage)
30    " \n ReWrite :\n",
31    " Re write a full gdcm-readable Dicom image                              ",
32    "     (usefull when the file header is not very straight).               ",
33    "                                                                        ",
34    " usage: ReWrite filein=inputFileName fileout=outputFileName             ", 
35    "       [mode=write mode] [monochrome1] [noshadow] [noseq][debug]        ",
36    "  --> The following line to 'rubout' a burnt-in Patient name            ",
37    "       [rubout=xBegin,xEnd,yBegin,yEnd [ruboutvalue=n (<255)] ]         ",
38    "  --> The 2 following lines, to extract a sub image within some frames  ",
39    "       [ROI=xBegin,xEnd,yBegin,yEnd]                                    ",
40    "       [firstframe=beg] [lastframe=end]                                 ", 
41    "                                                                        ",
42    "        mode = a (ACR), x (Explicit VR Dicom), r (RAW : only pixels)    ",
43    "               j (jpeg lossless), 2 (jpeg2000)                          ",
44    "        monochrome1 = user wants MONOCHROME1 photom. interp. (0=white)  ",
45    "        noshadowseq: user doesn't want to load Private Sequences        ",
46    "        noshadow : user doesn't want to load Private groups (odd number)",
47    "        noseq    : user doesn't want to load Sequences                  ",
48    "        rgb      : user wants to transform LUT (if any) to RGB pixels   ",
49    "        warning  : developper wants to run the program in 'warning mode'",
50    "        debug    : developper wants to run the program in 'debug mode'  ",
51    FINISH_USAGE
52
53    // ----- Initialize Arguments Manager ------  
54     
55    GDCM_NAME_SPACE::ArgMgr *am = new GDCM_NAME_SPACE::ArgMgr(argc, argv);
56   
57    if (argc == 1 || am->ArgMgrDefined("usage")) 
58    {
59       am->ArgMgrUsage(usage); // Display 'usage'
60       delete am;
61       return 1;
62    }
63    char *fileName = am->ArgMgrWantString("filein",usage);
64    if ( fileName == NULL )
65    {
66       std::cout << "'filein= ...' is mandatory" << std::endl;
67       delete am;
68       return 1;
69    }
70
71    char *outputFileName = am->ArgMgrWantString("fileout",usage);
72    if ( outputFileName == NULL )
73    {
74       std::cout << "'fileout= ...' is mandatory" << std::endl;
75       delete am;
76       return 1;
77    }
78
79    const char *mode = am->ArgMgrGetString("mode","X");
80
81    int loadMode = GDCM_NAME_SPACE::LD_ALL;
82    if ( am->ArgMgrDefined("noshadowseq") )
83       loadMode |= GDCM_NAME_SPACE::LD_NOSHADOWSEQ;
84    else 
85    {
86    if ( am->ArgMgrDefined("noshadow") )
87          loadMode |= GDCM_NAME_SPACE::LD_NOSHADOW;
88       if ( am->ArgMgrDefined("noseq") )
89          loadMode |= GDCM_NAME_SPACE::LD_NOSEQ;
90    }
91
92    bool rgb = ( 0 != am->ArgMgrDefined("RGB") );
93
94    bool monochrome1 = ( 0 != am->ArgMgrDefined("monochrome1") );
95    
96    if (am->ArgMgrDefined("debug"))
97       GDCM_NAME_SPACE::Debug::DebugOn();
98
99    if (am->ArgMgrDefined("warning"))
100       GDCM_NAME_SPACE::Debug::WarningOn();
101             
102    bool fail = false;
103    int *boundVal;
104    int ruboutVal;
105    bool rubout = false; 
106    if (am->ArgMgrDefined("rubout"))
107    {
108       int nbBound;
109       boundVal = am->ArgMgrGetListOfInt("rubout", &nbBound);
110
111       if (nbBound !=4)
112       {
113          std::cout << "Illegal number of 'rubout' boundary values (expected : 4, found:" 
114                    << nbBound << "); 'rubout' ignored" << std::endl;
115          fail = true;
116       }
117             
118       ruboutVal = am->ArgMgrGetInt("ruboutvalue", 0);
119       rubout = true;   
120    }
121
122    int *roiBoundVal;
123    bool roi = false; 
124    if (am->ArgMgrDefined("roi"))
125    {
126       int nbRoiBound;
127       roiBoundVal = am->ArgMgrGetListOfInt("roi", &nbRoiBound);
128
129       if (nbRoiBound !=4)
130       {
131         std::cout << "Illegal number of 'ROI' boundary values (expected : 4, found:" 
132                   << nbRoiBound << "); 'ROI' ignored" << std::endl;
133         fail = true;
134       }
135       else
136         roi = true;   
137    }
138   
139    int beg = am->ArgMgrGetInt("firstFrame",-1);
140    int end = am->ArgMgrGetInt("lastFrame",-1);
141  
142    // if unused Params we give up
143    if ( am->ArgMgrPrintUnusedLabels() )
144    { 
145       am->ArgMgrUsage(usage);
146       delete am;
147       return 0;
148    }
149
150    delete am;  // we don't need Argument Manager any longer
151
152    // ----------- End Arguments Manager ---------
153
154    GDCM_NAME_SPACE::File *f = GDCM_NAME_SPACE::File::New();
155    f->SetLoadMode( loadMode );
156
157    f->SetFileName( fileName );
158    bool res = f->Load();  
159       if ( !res )
160    {
161       f->Delete();
162       return 1;
163    }
164
165    if (!f->IsReadable())
166    {
167        std::cerr << "Sorry, not a Readable DICOM / ACR File"  <<std::endl;
168        f->Delete();
169        return 1;
170    }
171    
172    GDCM_NAME_SPACE::FileHelper *fh = GDCM_NAME_SPACE::FileHelper::New(f);
173    uint8_t *imageData; 
174    int dataSize;
175  
176    int nX,nY,nZ,sPP,planarConfig;
177    std::string pixelType, transferSyntaxName;
178    nX=f->GetXSize();
179    nY=f->GetYSize();
180    nZ=f->GetZSize();
181    
182    std::cout << " DIMX=" << nX << " DIMY=" << nY << " DIMZ=" << nZ << std::endl;
183
184    pixelType    = f->GetPixelType();
185    sPP          = f->GetSamplesPerPixel();
186    planarConfig = f->GetPlanarConfiguration();
187    
188    std::cout << " pixelType="           << pixelType 
189              << " SampleserPixel="      << sPP
190              << " PlanarConfiguration=" << planarConfig 
191              << " PhotometricInterpretation=" 
192              << f->GetEntryString(0x0028,0x0004) 
193              << std::endl;
194
195    int numberOfScalarComponents=f->GetNumberOfScalarComponents();
196    std::cout << "NumberOfScalarComponents " << numberOfScalarComponents 
197              <<std::endl;
198    transferSyntaxName = f->GetTransferSyntaxName();
199    std::cout << " TransferSyntaxName= [" << transferSyntaxName << "]" 
200              << std::endl;
201   
202    if(monochrome1)
203       fh->SetPhotometricInterpretationToMonochrome1();
204    
205    if (rgb)
206    {
207       dataSize  = fh->GetImageDataSize();
208       imageData = fh->GetImageData(); // somewhat important : Loads the Pixels in memory !
209       fh->SetWriteModeToRGB();
210    }
211    else
212    {
213       dataSize  = fh->GetImageDataRawSize();
214       imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
215       fh->SetWriteModeToRaw();
216    }
217
218    if ( imageData == 0 ) // to avoid warning
219    {
220       std::cout << "Was unable to read pixels " << std::endl;
221    }
222    printf(" dataSize %d imageData %p\n",dataSize, imageData);
223
224    // Since we just ReWrite the image, we know no modification 
225    // was performed on the pixels.
226    // We don't want this image appears as a 'Secondary Captured image'
227    fh->SetContentType(GDCM_NAME_SPACE::UNMODIFIED_PIXELS_IMAGE);
228    
229
230    /// \todo : think about rubbing out a part of a *multiframe* image!
231    if (rubout)
232    {     
233       if (boundVal[0]<0 || boundVal[0]>nX)
234       { 
235          std::cout << "xBegin out of bounds; 'rubout' ignored" << std::endl;
236          fail = true;      
237       }
238       if (boundVal[1]<0 || boundVal[1]>nX)
239       { 
240          std::cout << "xEnd out of bounds; 'rubout' ignored" << std::endl;
241          fail = true;      
242       }
243       if (boundVal[0] > boundVal[1])
244       { 
245          std::cout << "xBegin greater than xEnd; 'rubout' ignored" << std::endl;
246          fail = true;      
247       }       
248       if (boundVal[2]<0 || boundVal[2]>nY)
249       { 
250          std::cout << "yBegin out of bounds; 'rubout' ignored" << std::endl;
251          fail = true;      
252       }
253       if (boundVal[3]<0 || boundVal[3]>nY)
254       { 
255          std::cout << "yEnd out of bounds; 'rubout' ignored" << std::endl;
256          fail = true;      
257       }
258       if (boundVal[2] > boundVal[3])
259       { 
260          std::cout << "yBegin greater than yEnd; 'rubout' ignored" << std::endl;
261          fail = true;      
262       }  
263       if (!fail)
264       {
265          int pixelLength = f->GetBitsAllocated()/8;
266          int lineLength = nX * sPP * pixelLength;
267          size_t lengthToRubout = (boundVal[1]-boundVal[0])*sPP*pixelLength;
268          int offsetToBeginOfRubout = boundVal[0]*sPP*pixelLength+lineLength*boundVal[2];
269       
270          for(int rbl=boundVal[2]; rbl<boundVal[3];rbl++)
271          {
272             memset((char *)imageData+offsetToBeginOfRubout, ruboutVal, lengthToRubout);
273             offsetToBeginOfRubout += lineLength; 
274          }
275       }   
276    } 
277
278
279 //------------------------------ Set the Writing mode ---------------------------------
280
281    switch (mode[0])
282    {
283       case 'A' :
284       case 'a' :
285       // Writting an ACR file
286       // from a full gdcm readable File
287          std::cout << "WriteACR" << std::endl;
288          fh->SetWriteTypeToAcr();
289          break;
290
291       case 'D' : // Not documented in the 'usage', because the method 
292       case 'd' : //                             is known to be bugged. 
293       // Writting a DICOM Implicit VR file
294       // from a full gdcm readable File
295          std::cout << "WriteDCM Implicit VR" << std::endl;
296          fh->SetWriteTypeToDcmImplVR(); 
297          break;
298
299       case 'X' :
300       case 'x' :
301       // writting a DICOM Explicit VR 
302       // from a full gdcm readable File
303          std::cout << "WriteDCM Explicit VR" << std::endl;
304          // fh->WriteDcmExplVR(outputFileName);
305          // Try this one :
306          fh->SetWriteTypeToDcmExplVR();
307
308          break;
309
310       case 'R' :
311       case 'r' :
312       //  Writting a Raw File, 
313          std::cout << "WriteRaw" << std::endl;
314          fh->WriteRawData(outputFileName);
315          break;
316  
317       case 'J' :
318       case 'j' :
319       // writting a DICOM Jpeg Lossless 
320       // from a full gdcm readable File
321          std::cout << "WriteDCM Jpeg Lossless" << std::endl;
322          fh->SetWriteTypeToJPEG();
323          break;
324
325       case '2' :
326       // writting a DICOM Jpeg 2000 
327       // from a full gdcm readable File
328          std::cout << "WriteDCM Jpeg 2000" << std::endl;
329          fh->SetWriteTypeToJPEG2000();
330          break; 
331  
332  // Just for fun :
333  // Write a 'Video inverse' version of the file.
334  // *Not* described, on purpose,  in the USAGE  
335       case 'V' :
336       case 'v' :
337          if ( fh->GetFile()->GetBitsAllocated() == 8)
338          {
339             std::cout << "videoinv for 8 bits" << std::endl;
340             for (int i=0; i<dataSize; i++) 
341             {
342                ((uint8_t*)imageData)[i] = 255 - ((uint8_t*)imageData)[i];
343             }
344          }
345          else
346          {
347             std::cout << "videoinv for 16 bits" << std::endl;    
348             for (int i=0; i<dataSize/2; i++) 
349             {
350                ((uint16_t*)imageData)[i] =  65535 - ((uint16_t*)imageData)[i];
351             }
352          }
353          std::cout << "WriteDCM Explicit VR + VideoInv" << std::endl;
354          fh->SetWriteTypeToDcmExplVR();
355          break;
356    }
357
358
359 //
360 // user wants to keep only a part of the image (ROI, and/or some frames)
361 // ---------------------------------------------------------------------
362 // (==> this is no longer really 'ReWrite' !)
363
364     int subImDimX = nX;
365     int subImDimY = nY;    
366
367     if (roi)
368     {  
369       if (roiBoundVal[0]<0 || roiBoundVal[0]>=nX)
370       { 
371          std::cout << "xBegin out of bounds; 'roi' ignored" << std::endl;
372          fail = true;      
373       }
374       if (roiBoundVal[1]<0 || roiBoundVal[1]>=nX)
375       { 
376          std::cout << "xEnd out of bounds; 'roi' ignored" << std::endl;
377          fail = true;      
378       }
379       if (roiBoundVal[0] > roiBoundVal[1])
380       { 
381          std::cout << "xBegin greater than xEnd; 'roi' ignored" << std::endl;
382          fail = true;      
383       }
384
385       if (roiBoundVal[2]<0 || roiBoundVal[2]>=nY)
386       { 
387          std::cout << "yBegin out of bounds; 'roi' ignored" << std::endl;
388          fail = true;      
389       }
390       if (roiBoundVal[3]<0 || roiBoundVal[3]>=nY)
391       { 
392          std::cout << "yEnd out of bounds; 'roi' ignored" << std::endl;
393          fail = true;      
394       }
395       if (roiBoundVal[2] > roiBoundVal[3])
396       { 
397          std::cout << "yBegin greater than yEnd; 'roi' ignored" << std::endl;
398          fail = true;      
399       }  
400    } 
401    else
402    {  
403      roiBoundVal = new int[4];
404      roiBoundVal[0] = 0;
405      roiBoundVal[1] = nX-1;
406      roiBoundVal[2] = 0;
407      roiBoundVal[3] = nY-1;  
408   }
409
410    subImDimX = roiBoundVal[1]-roiBoundVal[0]+1;     
411    subImDimY = roiBoundVal[3]-roiBoundVal[2]+1;  
412  
413   if (roi || beg != -1 || end != -1)
414   {  
415      if (beg == -1)
416         beg = 0;  
417      if (end == -1)
418         end = nZ-1;
419      
420      std::ostringstream str;
421      
422     // Set the data that will be *actually* written.
423
424      int pixelSize = fh->GetFile()->GetPixelSize();
425      size_t lgrSubLine  = subImDimX* pixelSize * numberOfScalarComponents;
426      size_t lgrSubFrame = subImDimY*lgrSubLine;
427                       ;
428      int lgrSubImage = (end-beg+1) * lgrSubFrame;
429        
430      uint8_t * subImage = new uint8_t[lgrSubImage];
431        
432      uint8_t * srcCopy = (uint8_t *) imageData;
433      uint8_t * destCopy = subImage;
434      int lineSize = nX*pixelSize*numberOfScalarComponents;
435      int frameSize = nY*lineSize; 
436  
437      int lineOffset = roiBoundVal[0]*pixelSize * numberOfScalarComponents;
438      
439      for (int frameNb=beg, frameCount=0; frameNb<=end; frameNb++, frameCount++)
440      { 
441         for (int lineNb=roiBoundVal[2], lineCount=0; lineNb<=roiBoundVal[3]; lineNb++, lineCount++)
442         {  
443             /// \todo : increment data pointer, don't multiply so much!
444             memcpy( (void *)(destCopy + frameCount*lgrSubFrame + lineCount*lgrSubLine), 
445                     (void *)(srcCopy  + frameNb*frameSize + lineNb*lineSize + lineOffset ), 
446                     lgrSubLine);
447         }        
448      }
449  
450     // Set the image size
451      str.str("");
452      str << subImDimX ;
453      fh->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
454
455      str.str("");
456      str << subImDimY;
457      fh->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
458      str.str("");
459      str << end-beg+1; 
460      fh->InsertEntryString(str.str(),0x0028,0x0008, "IS"); // Number of Frames 
461       
462      //fh->SetImageData(subImage,lgrSubImage);
463       fh->SetUserData(subImage,lgrSubImage);   // ensures the compression (if any)    
464   }
465   else
466   {         
467       fh->SetUserData(imageData,dataSize); // ensures the compression (if any) 
468   }
469
470
471
472 //----------------------------------- Write, now! ---------------------------------
473
474    if (mode[0] != 'R' && mode[0] != 'r')
475       fh->Write(outputFileName);
476
477    f->Delete();
478    fh->Delete();
479    return 0;
480 }
481
482