]> Creatis software - gdcm.git/blob - Example/exReadPapyrus.cxx
* Minor coding-style clean up
[gdcm.git] / Example / exReadPapyrus.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: exReadPapyrus.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/18 08:35:44 $
7   Version:   $Revision: 1.4 $
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 "gdcmDocument.h"
21 #include "gdcmDataEntry.h"
22 #include "gdcmSeqEntry.h"
23 #include "gdcmSQItem.h"
24 #include "gdcmDebug.h"
25 #include "gdcmUtil.h"
26
27 #include "gdcmArgMgr.h"
28 #include <iostream>
29
30 //#include <fstream>
31
32 #ifndef _WIN32
33 #include <unistd.h> //for access, unlink
34 #else
35 #include <io.h> //for _access
36 #endif
37
38 // return true if the file exists
39 bool FileExists(const char *filename)
40 {
41 #ifdef _MSC_VER
42 # define access _access
43 #endif
44 #ifndef R_OK
45 # define R_OK 04
46 #endif
47   if ( access(filename, R_OK) != 0 )
48     {
49     return false;
50     }
51   else
52     {
53     return true;
54     }
55 }
56
57 bool RemoveFile(const char *source)
58 {
59 #ifdef _MSC_VER
60 #define _unlink unlink
61 #endif
62   return unlink(source) != 0 ? false : true;
63 }
64
65 // ----------------------------------------------------------------------
66 // Here we load a supposed to be Papyrus File (gdcm::File compliant)
67 // and then try to get the pixels, using low-level SeqEntry accessors.
68 // Since it's not a general purpose Papyrus related program
69 // (just a light example) we suppose *everything* is clean
70 // and we don't perform any integrity check
71 // ----------------------------------------------------------------------
72
73 int main(int argc, char *argv[])
74 {
75
76    START_USAGE(usage)
77    " \n exReadPapyrus :\n",
78    " Reads a Papyrus V3 File, Writes a Multiframe Dicoim V3 File ",
79    "     (just to show gdcm can do it ...)               ",
80    "",
81    " usage: exReadPapyrus filein=inputPapyrusFileName fileout=outputDicomFileName", 
82    "                      [debug]  ", 
83    "        debug    : user wants to run the program in 'debug mode'        ",
84    FINISH_USAGE
85
86
87    // ----- Initialize Arguments Manager ------
88    
89    gdcm::ArgMgr *am = new gdcm::ArgMgr(argc, argv);
90   
91    if (am->ArgMgrDefined("usage")) 
92    {
93       am->ArgMgrUsage(usage); // Display 'usage'
94       delete am;
95       return 0;
96    }
97    char *fileName = am->ArgMgrWantString("filein",usage);
98    if ( fileName == NULL )
99    {
100       delete am;
101       return 0;
102    }
103
104    char *outputFileName = am->ArgMgrWantString("fileout",usage);
105    if ( outputFileName == NULL )
106    {
107       delete am;
108       return 0;
109    }
110
111    if (am->ArgMgrDefined("debug"))
112       gdcm::Debug::DebugOn();
113  
114    // if unused Params we give up
115    if ( am->ArgMgrPrintUnusedLabels() )
116    { 
117       am->ArgMgrUsage(usage);
118       delete am;
119       return 0;
120    }
121
122    delete am;  // we don't need Argument Manager any longer
123
124    // ----------- End Arguments Manager ---------
125
126    if( FileExists( outputFileName ) )
127    {
128       if( !RemoveFile( outputFileName ) )
129       {
130          std::cerr << "Ouch, the file exist, but I cannot remove it" << std::endl;
131          return 1;
132       }
133    }
134
135    int loadMode = 0x0; // load everything
136    gdcm::File *f = new gdcm::File();
137    f->SetLoadMode( loadMode );
138    f->SetFileName( fileName );
139    bool res = f->Load();  
140
141    if ( !res )
142    {
143       delete f;
144       return 0;
145    }
146
147    // Look for private Papyrus Sequence
148    gdcm::SeqEntry *seqPapyrus= f->GetSeqEntry(0x0041, 0x1050);
149    if (!seqPapyrus)
150    {
151       std::cout << "NOT a Papyrus File : " << fileName <<std::endl;
152       delete f;
153       return 1;
154    }
155
156 //   gdcm::FileHelper *original = new gdcm::FileHelper( fileName );
157 //   gdcm::File *h = original->GetFile();
158
159    //gdcm::FileHelper *f1 = new gdcm::FileHelper(f);
160    gdcm::SQItem *sqi = seqPapyrus->GetFirstSQItem();
161    if (sqi == 0)
162    {
163       std::cout << "NO SQItem found within private Papyrus Sequence"
164           << std::endl;
165       delete f;
166       return 1;
167    }
168       
169    std::string TransferSyntax;
170    std::string StudyDate;
171    std::string StudyTime;
172    std::string Modality;
173    std::string PatientName;
174    std::string MediaStSOPinstUID;
175
176 // Get informations on the file : 
177 //  Modality, Transfer Syntax, Study Date, Study Time
178 // Patient Name, Media Storage SOP Instance UID, etc
179
180    MediaStSOPinstUID   =  f->GetEntryString(0x0002,0x0002);
181    TransferSyntax      =  f->GetEntryString(0x0002,0x0010);
182    StudyDate           = sqi->GetEntryString(0x0008,0x0020);
183    StudyTime           = sqi->GetEntryString(0x0008,0x0030);
184    Modality            = sqi->GetEntryString(0x0008,0x0060);
185    PatientName         = sqi->GetEntryString(0x0010,0x0010);
186
187    std::cout << "TransferSyntax " << TransferSyntax << std::endl;
188
189    std::string Rows;
190    std::string Columns;
191    std::string SamplesPerPixel;
192    std::string BitsAllocated;
193    std::string BitsStored;
194    std::string HighBit;
195    std::string PixelRepresentation;
196    
197
198    // we brutally suppose all the images within a Papyrus file
199    // have the same caracteristics.
200    // if you're aware they have not, just move the GetEntryString
201    // inside the loop
202
203    // Get caracteristics of the first image
204    SamplesPerPixel     = sqi->GetEntryString(0x0028,0x0002);
205    Rows                = sqi->GetEntryString(0x0028,0x0010);
206    Columns             = sqi->GetEntryString(0x0028,0x0011);
207    BitsAllocated       = sqi->GetEntryString(0x0028,0x0100);
208    BitsStored          = sqi->GetEntryString(0x0028,0x0101);
209    HighBit             = sqi->GetEntryString(0x0028,0x0102);
210    PixelRepresentation = sqi->GetEntryString(0x0028,0x0103);
211
212    // just convert those needed to compute PixelArea length
213    int iRows            = (uint32_t) atoi( Rows.c_str() );
214    int iColumns         = (uint32_t) atoi( Columns.c_str() );
215    int iSamplesPerPixel = (uint32_t) atoi( SamplesPerPixel.c_str() );
216    int iBitsAllocated   = (uint32_t) atoi( BitsAllocated.c_str() );
217
218    int lgrImage = iRows*iColumns * iSamplesPerPixel * (iBitsAllocated/8);
219
220    // compute number of images
221    int nbImages = seqPapyrus->GetNumberOfSQItems();
222    std::cout <<"Number of frames :" << nbImages << std::endl;  
223
224    //  allocate enough room to get the pixels of all images.
225    uint8_t *PixelArea = new uint8_t[lgrImage*nbImages];
226    uint8_t *currentPosition = PixelArea;
227    gdcm::DataEntry *pixels;
228
229    // declare and open the file
230    std::ifstream *Fp;
231    Fp = new std::ifstream(fileName, std::ios::in | std::ios::binary);
232    if( ! *Fp )
233    {
234       std::cout <<  "Cannot open file: " << fileName << std::endl;
235       //gdcmDebugMacro( "Cannot open file: " << fileName.c_str() );
236       delete Fp;
237       Fp = 0;
238       return 0;
239    }
240    // to be sure to be at the beginning
241    Fp->seekg(0, std::ios::end);
242
243    uint32_t offset;
244    std::string previousRows = Rows;
245    sqi = seqPapyrus->GetFirstSQItem();
246    while (sqi)
247    {
248       std::cout << "One more image read. Keep waiting" << std::endl;
249       Rows = sqi->GetEntryString(0x0028,0x0010);
250       // minimum integrity check
251       if (Rows != previousRows)
252       {
253          std::cout << "Consistency check failed " << std::endl;
254          return 1;
255       }
256       // get the images pixels
257       pixels = sqi->GetDataEntry(0x7fe0,0x0010);
258       offset = pixels->GetOffset();
259       // perform a fseek, on offset length on the 'right' length
260       Fp->seekg(offset, std::ios::beg);
261       // perform a fread into the right place
262       Fp->read((char *)currentPosition, (size_t)lgrImage);
263       currentPosition +=lgrImage;
264
265       std::string previousRowNb = Rows;
266
267       sqi =  seqPapyrus->GetNextSQItem();
268    }
269
270    // build up a new File, with file info + images info + global pixel area.
271
272    std::string NumberOfFrames = gdcm::Util::Format("%d", nbImages); 
273
274    gdcm::File *n = new gdcm::File();
275
276    n->InsertEntryString(MediaStSOPinstUID,  0x0002,0x0002);
277   // Whe keep default gdcm Transfer Syntax (Explicit VR Little Endian)
278   // since using Papyrus one (Implicit VR Little Endian) is a mess
279    //n->InsertEntryString(TransferSyntax,     0x0002,0x0010);
280    n->InsertEntryString(StudyDate,          0x0008,0x0020);
281    n->InsertEntryString(StudyTime,          0x0008,0x0030);
282    n->InsertEntryString(Modality,           0x0008,0x0060);
283    n->InsertEntryString(PatientName,        0x0010,0x0010);
284
285    n->InsertEntryString(SamplesPerPixel,    0x0028,0x0002);
286    n->InsertEntryString(NumberOfFrames,     0x0028,0x0008);
287    n->InsertEntryString(Rows,               0x0028,0x0010);
288    n->InsertEntryString(Columns,            0x0028,0x0011);
289    n->InsertEntryString(BitsAllocated,      0x0028,0x0100);
290    n->InsertEntryString(BitsStored,         0x0028,0x0101);
291    n->InsertEntryString(HighBit,            0x0028,0x0102);
292    n->InsertEntryString(PixelRepresentation,0x0028,0x0103);
293
294    // create the file
295    gdcm::FileHelper *file = new gdcm::FileHelper(n);
296
297    file->SetImageData(PixelArea,lgrImage*nbImages);
298    file->SetWriteTypeToDcmExplVR();
299
300    //file->SetPrintLevel(2);
301    n->Print();
302
303    // Write the file
304    file->Write(outputFileName); 
305    if (!file)
306    {
307       std::cout <<"Fail to open (write) file:[" << outputFileName << "]" << std::endl;;
308       return 1;  
309    }
310    return 0;
311 }