]> Creatis software - gdcm.git/blob - Example/ReWrite.cxx
Allow user to extract a subimage, within a limited number of frames.
[gdcm.git] / Example / ReWrite.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: ReWrite.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/03/06 10:19:00 $
7   Version:   $Revision: 1.21 $
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] [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 withon 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    "        noshadowseq: user doesn't want to load Private Sequences        ",
44    "        noshadow : user doesn't want to load Private groups (odd number)",
45    "        noseq    : user doesn't want to load Sequences                  ",
46    "        rgb      : user wants to tranform LUT (if any) to RGB pixels    ",
47    "        debug    : developper wants to run the program in 'debug mode'  ",
48    FINISH_USAGE
49
50    // ----- Initialize Arguments Manager ------   
51    gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
52   
53    if (argc == 1 || am->ArgMgrDefined("usage")) 
54    {
55       am->ArgMgrUsage(usage); // Display 'usage'
56       delete am;
57       return 0;
58    }
59    char *fileName = am->ArgMgrWantString("filein",usage);
60    if ( fileName == NULL )
61    {
62       std::cout << "'filein= ...' is mandatory" << std::endl;
63       delete am;
64       return 0;
65    }
66
67    char *outputFileName = am->ArgMgrWantString("fileout",usage);
68    if ( outputFileName == NULL )
69    {
70       std::cout << "'fileout= ...' is mandatory" << std::endl;
71       delete am;
72       return 0;
73    }
74
75    const char *mode = am->ArgMgrGetString("mode","X");
76
77    int loadMode = gdcm::LD_ALL;
78    if ( am->ArgMgrDefined("noshadowseq") )
79       loadMode |= gdcm::LD_NOSHADOWSEQ;
80    else 
81    {
82    if ( am->ArgMgrDefined("noshadow") )
83          loadMode |= gdcm::LD_NOSHADOW;
84       if ( am->ArgMgrDefined("noseq") )
85          loadMode |= gdcm::LD_NOSEQ;
86    }
87
88    bool rgb = ( 0 != am->ArgMgrDefined("RGB") );
89
90    if (am->ArgMgrDefined("debug"))
91       gdcm::Debug::DebugOn();
92       
93    bool fail = false;
94    int *boundVal;
95    int ruboutVal;
96    bool rubout = false; 
97    if (am->ArgMgrDefined("rubout"))
98    {
99       int nbBound;
100       boundVal = am->ArgMgrGetListOfInt("rubout", &nbBound);
101
102       if (nbBound !=4)
103       {
104          std::cout << "Illegal number of 'rubout' boundary values (expected : 4, found:" 
105                    << nbBound << "); 'rubout' ignored" << std::endl;
106          fail = true;
107       }
108             
109       ruboutVal = am->ArgMgrGetInt("ruboutvalue", 0);
110       rubout = true;   
111    }
112
113    int *roiBoundVal;
114    bool roi = false; 
115    if (am->ArgMgrDefined("roi"))
116    {
117       int nbRoiBound;
118       roiBoundVal = am->ArgMgrGetListOfInt("roi", &nbRoiBound);
119
120       if (nbRoiBound !=4)
121       {
122         std::cout << "Illegal number of 'ROI' boundary values (expected : 4, found:" 
123                   << nbRoiBound << "); 'ROI' ignored" << std::endl;
124         fail = true;
125       }
126       else
127         roi = true;   
128    }
129   
130    int beg = am->ArgMgrGetInt("firstFrame",-1);
131    int end = am->ArgMgrGetInt("lastFrame",-1);
132  
133    // if unused Params we give up
134    if ( am->ArgMgrPrintUnusedLabels() )
135    { 
136       am->ArgMgrUsage(usage);
137       delete am;
138       return 0;
139    }
140
141    delete am;  // we don't need Argument Manager any longer
142
143    // ----------- End Arguments Manager ---------
144
145    gdcm::File *f = gdcm::File::New();
146    f->SetLoadMode( loadMode );
147    f->SetFileName( fileName );
148    bool res = f->Load();  
149    if ( !res )
150    {
151       f->Delete();
152       return 0;
153    }
154
155    if (!f->IsReadable())
156    {
157        std::cerr << "Sorry, not a Readable DICOM / ACR File"  <<std::endl;
158        f->Delete();
159        return 0;
160    }
161  
162    
163    gdcm::FileHelper *fh = gdcm::FileHelper::New(f);
164    void *imageData; 
165    int dataSize;
166  
167     int nX,nY,nZ,sPP,planarConfig;
168    std::string pixelType, transferSyntaxName;
169    nX=f->GetXSize();
170    nY=f->GetYSize();
171    nZ=f->GetZSize();
172    
173    std::cout << " DIMX=" << nX << " DIMY=" << nY << " DIMZ=" << nZ << std::endl;
174
175    pixelType    = f->GetPixelType();
176    sPP          = f->GetSamplesPerPixel();
177    planarConfig = f->GetPlanarConfiguration();
178    
179    std::cout << " pixelType="           << pixelType 
180              << " SampleserPixel="      << sPP
181              << " PlanarConfiguration=" << planarConfig 
182              << " PhotometricInterpretation=" 
183              << f->GetEntryString(0x0028,0x0004) 
184              << std::endl;
185
186    int numberOfScalarComponents=f->GetNumberOfScalarComponents();
187    std::cout << "NumberOfScalarComponents " << numberOfScalarComponents 
188              <<std::endl;
189    transferSyntaxName = f->GetTransferSyntaxName();
190    std::cout << " TransferSyntaxName= [" << transferSyntaxName << "]" 
191              << std::endl;
192  
193    
194    if (rgb)
195    {
196       dataSize  = fh->GetImageDataSize();
197       imageData = fh->GetImageData(); // somewhat important : Loads the Pixels in memory !
198       fh->SetWriteModeToRGB();
199    }
200    else
201    {
202       dataSize  = fh->GetImageDataRawSize();
203       imageData = fh->GetImageDataRaw();// somewhat important : Loads the Pixels in memory !
204       fh->SetWriteModeToRaw();
205    }
206
207    if ( imageData == 0 ) // to avoid warning
208    {
209       std::cout << "Was unable to read pixels " << std::endl;
210    }
211    printf(" dataSize %d imageData %p\n",dataSize, imageData);
212
213    // Since we just ReWrite the image, we know no modification 
214    // was performed on the pixels.
215    // We don't want this image appears as a 'Secondary Captured image'
216    fh->SetContentType(gdcm::UNMODIFIED_PIXELS_IMAGE);
217    
218
219    /// \todo : think about rubbing out a part of a *multiframe* image!
220    if (rubout)
221    {     
222       if (boundVal[0]<0 || boundVal[0]>nX)
223       { 
224          std::cout << "xBegin out of bounds; 'rubout' ignored" << std::endl;
225          fail = true;      
226       }
227       if (boundVal[1]<0 || boundVal[1]>nX)
228       { 
229          std::cout << "xEnd out of bounds; 'rubout' ignored" << std::endl;
230          fail = true;      
231       }
232       if (boundVal[0] > boundVal[1])
233       { 
234          std::cout << "xBegin greater than xEnd; 'rubout' ignored" << std::endl;
235          fail = true;      
236       }       
237       if (boundVal[2]<0 || boundVal[2]>nY)
238       { 
239          std::cout << "yBegin out of bounds; 'rubout' ignored" << std::endl;
240          fail = true;      
241       }
242       if (boundVal[3]<0 || boundVal[3]>nY)
243       { 
244          std::cout << "yEnd out of bounds; 'rubout' ignored" << std::endl;
245          fail = true;      
246       }
247       if (boundVal[2] > boundVal[3])
248       { 
249          std::cout << "yBegin greater than yEnd; 'rubout' ignored" << std::endl;
250          fail = true;      
251       }  
252       if (!fail)
253       {
254          int pixelLength = f->GetBitsAllocated()/8;
255          int lineLength = nX * sPP * pixelLength;
256          size_t lengthToRubout = (boundVal[1]-boundVal[0])*sPP*pixelLength;
257          int offsetToBeginOfRubout = boundVal[0]*sPP*pixelLength+lineLength*boundVal[2];
258       
259          for(int rbl=boundVal[2]; rbl<boundVal[3];rbl++)
260          {
261             memset((char *)imageData+offsetToBeginOfRubout, ruboutVal, lengthToRubout);
262             offsetToBeginOfRubout += lineLength; 
263          }
264       }   
265    } 
266
267 //
268 // user wants to keep only a part of the image (ROI, and/or some frames)
269 // ---------------------------------------------------------------------
270 // (==> this is no longer really 'ReWrite' !)
271
272     int subImDimX = nX;
273     int subImDimY = nY;    
274
275     if (roi)
276     {  
277       if (roiBoundVal[0]<0 || roiBoundVal[0]>=nX)
278       { 
279          std::cout << "xBegin out of bounds; 'roi' ignored" << std::endl;
280          fail = true;      
281       }
282       if (roiBoundVal[1]<0 || roiBoundVal[1]>=nX)
283       { 
284          std::cout << "xEnd out of bounds; 'roi' ignored" << std::endl;
285          fail = true;      
286       }
287       if (roiBoundVal[0] > roiBoundVal[1])
288       { 
289          std::cout << "xBegin greater than xEnd; 'roi' ignored" << std::endl;
290          fail = true;      
291       }
292
293       if (roiBoundVal[2]<0 || roiBoundVal[2]>=nY)
294       { 
295          std::cout << "yBegin out of bounds; 'roi' ignored" << std::endl;
296          fail = true;      
297       }
298       if (roiBoundVal[3]<0 || roiBoundVal[3]>=nY)
299       { 
300          std::cout << "yEnd out of bounds; 'roi' ignored" << std::endl;
301          fail = true;      
302       }
303       if (roiBoundVal[2] > roiBoundVal[3])
304       { 
305          std::cout << "yBegin greater than yEnd; 'roi' ignored" << std::endl;
306          fail = true;      
307       }  
308    } 
309    else
310    {  
311      roiBoundVal = new int(4);
312      roiBoundVal[0] = 0;
313      roiBoundVal[1] = nX-1;
314      roiBoundVal[2] = 0;
315      roiBoundVal[3] = nY-1;  
316   }
317
318    subImDimX = roiBoundVal[1]-roiBoundVal[0]+1;     
319    subImDimY = roiBoundVal[3]-roiBoundVal[2]+1;  
320  
321   if (roi || beg != -1 || end != -1)
322   {  
323      if (beg == -1)
324       beg = 0;  
325      if (end == -1)
326       end = nZ;
327      
328      std::ostringstream str;
329      
330     // Set the data that will be *actually* written.
331
332      int pixelSize = fh->GetFile()->GetPixelSize();
333      size_t lgrSubLine  = subImDimX* pixelSize * numberOfScalarComponents;
334      size_t lgrSubFrame = subImDimY*lgrSubLine;
335                       ;
336      int lgrSubImage = (end-beg+1) * lgrSubFrame;
337        
338      uint8_t * subImage = new uint8_t[lgrSubImage];
339        
340      uint8_t * srcCopy = (uint8_t *) imageData;
341      uint8_t * destCopy = subImage;
342      int lineSize = nX*pixelSize*numberOfScalarComponents;
343      int frameSize = nY*lineSize; 
344  
345      int lineOffset = roiBoundVal[0]*pixelSize * numberOfScalarComponents;
346      
347      for (unsigned int frameNb=beg, frameCount=0; frameNb<=end; frameNb++, frameCount++)
348      { 
349          for (unsigned int lineNb=roiBoundVal[2], lineCount=0; lineNb<=roiBoundVal[3]; lineNb++, lineCount++)
350          {  
351             /// \todo increment data pointer, don't multiply so much!
352             memcpy( (void *)(destCopy + frameCount*lgrSubFrame + lineCount*lgrSubLine), 
353                     (void *)(srcCopy  + frameNb*frameSize + lineNb*lineSize + lineOffset ), 
354                     lgrSubLine);
355          }        
356      }
357  
358     // Set the image size
359      str.str("");
360      str << subImDimX ;
361      fh->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
362
363      str.str("");
364      str << subImDimY;
365      fh->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
366      str.str("");
367      str << end-beg+1; 
368      fh->InsertEntryString(str.str(),0x0028,0x0008, "IS"); // Number of Frames 
369       
370      fh->SetImageData(subImage,lgrSubImage);
371             
372   }     
373
374
375 //----------------------------------- Write, now! ---------------------------------
376
377    switch (mode[0])
378    {
379       case 'A' :
380       case 'a' :
381       // Writting an ACR file
382       // from a full gdcm readable File
383          std::cout << "WriteACR" << std::endl;
384          fh->WriteAcr(outputFileName);
385          break;
386
387       case 'D' : // Not documented in the 'usage', because the method 
388       case 'd' : //                             is known to be bugged. 
389       // Writting a DICOM Implicit VR file
390       // from a full gdcm readable File
391          std::cout << "WriteDCM Implicit VR" << std::endl;
392          fh->WriteDcmImplVR(outputFileName);
393          break;
394
395       case 'X' :
396       case 'x' :
397       // writting a DICOM Explicit VR 
398       // from a full gdcm readable File
399          std::cout << "WriteDCM Explicit VR" << std::endl;
400          // fh->WriteDcmExplVR(outputFileName);
401          // Try this one :
402          fh->SetWriteTypeToDcmExplVR();
403          fh->Write(outputFileName);
404          break;
405
406       case 'R' :
407       case 'r' :
408       //  Writting a Raw File, 
409          std::cout << "WriteRaw" << std::endl;
410          fh->WriteRawData(outputFileName);
411          break;
412  
413  // Just for fun :
414  // Write a 'Video inverse' version of the file.
415  // *Not* described, on purpose,  in the USAGE  
416       case 'V' :
417       case 'v' :
418          if ( fh->GetFile()->GetBitsAllocated() == 8)
419          {
420             std::cout << "videoinv for 8 bits" << std::endl;
421             for (int i=0; i<dataSize; i++) 
422             {
423                ((uint8_t*)imageData)[i] = 255 - ((uint8_t*)imageData)[i];
424             }
425          }
426          else
427          {
428             std::cout << "videoinv for 16 bits" << std::endl;    
429             for (int i=0; i<dataSize/2; i++) 
430             {
431                ((uint16_t*)imageData)[i] =  65535 - ((uint16_t*)imageData)[i];
432             }
433          }
434          std::cout << "WriteDCM Explicit VR + VideoInv" << std::endl;
435          fh->WriteDcmExplVR(outputFileName);
436          break;
437    }
438
439    f->Delete();
440    fh->Delete();
441    return 0;
442 }
443