]> Creatis software - gdcm.git/blob - Testing/TestCopyRescaleDicom.cxx
New gdcm2 style syntax for Load()
[gdcm.git] / Testing / TestCopyRescaleDicom.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestCopyRescaleDicom.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/07/08 13:39:57 $
7   Version:   $Revision: 1.20 $
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 "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22
23 #include <time.h>
24 #include <sys/times.h>
25 #include <iomanip> // for std::ios::left, ...
26
27 //Generated file:
28 #include "gdcmDataImages.h"
29
30 #ifndef _WIN32
31 #include <unistd.h> //for access, unlink
32 #else
33 #include <io.h> //for _access on Win32
34 #endif
35
36 bool FileExists(const char *filename)
37 {
38 #ifdef _MSC_VER
39 # define access _access
40 #endif
41 #ifndef R_OK
42 # define R_OK 04
43 #endif
44   if ( access(filename, R_OK) != 0 )
45     {
46     return false;
47     }
48   else
49     {
50     return true;
51     }
52 }
53
54 bool RemoveFile(const char *source)
55 {
56 #ifdef _MSC_VER
57 #define _unlink unlink
58 #endif
59   return unlink(source) != 0 ? false : true;
60 }
61
62 int CopyRescaleDicom(std::string const &filename, 
63                      std::string const &output )
64 {
65    std::cout << "   Testing: " << filename << std::endl;
66    if( FileExists( output.c_str() ) )
67    {
68      // std::cerr << "Don't try to cheat, I am removing the file anyway" << std::endl;
69       if( !RemoveFile( output.c_str() ) )
70       {
71          std::cout << "Ouch, the file exist, but I cannot remove it" << std::endl;
72          return 1;
73       }
74    }
75  
76    //////////////// Step 1:
77    std::cout << "      1...";
78    gdcm::File originalF = gdcm::File( );
79    originalF.SetFileName( filename );
80    originalF.Load();
81    
82    gdcm::File copyF     = gdcm::File( );
83
84    //First of all copy the file, field by field
85
86    //////////////// Step 2:
87    std::cout << "2...";
88    // Copy of the file content
89    gdcm::DocEntry *d = originalF.GetFirstEntry();
90    while(d)
91    {
92       if ( gdcm::BinEntry *b = dynamic_cast<gdcm::BinEntry*>(d) )
93       {
94          copyF.InsertBinEntry( b->GetBinArea(),b->GetLength(),
95                                b->GetGroup(),b->GetElement(),
96                                b->GetVR() );
97       }
98       else if ( gdcm::ValEntry *v = dynamic_cast<gdcm::ValEntry*>(d) )
99       {   
100           copyF.InsertValEntry( v->GetValue(),
101                                 v->GetGroup(),v->GetElement(),
102                                 v->GetVR() ); 
103       }
104       else
105       {
106        // We skip pb of SQ recursive exploration
107       }
108
109       d = originalF.GetNextEntry();
110    }
111
112    gdcm::FileHelper original = gdcm::FileHelper( &originalF );
113    gdcm::FileHelper copy     = gdcm::FileHelper( &copyF );
114
115    size_t dataSize = original.GetImageDataSize();
116
117    size_t rescaleSize;
118    uint8_t *rescaleImage;
119
120    const std::string &bitsStored = originalF.GetEntryValue(0x0028,0x0101);
121    if( bitsStored == "16" )
122    {
123       std::cout << "Rescale...";
124       copyF.InsertValEntry( "8", 0x0028, 0x0100); // Bits Allocated
125       copyF.InsertValEntry( "8", 0x0028, 0x0101); // Bits Stored
126       copyF.InsertValEntry( "7", 0x0028, 0x0102); // High Bit
127       copyF.InsertValEntry( "0", 0x0028, 0x0103); // Pixel Representation
128
129       // We assume the value were from 0 to uint16_t max
130       rescaleSize = dataSize / 2;
131       rescaleImage = new uint8_t[dataSize];
132
133       uint16_t *imageData16 = (uint16_t*)original.GetImageData();
134       uint16_t *tmpImage = imageData16;
135       uint8_t *tmpRescale = rescaleImage;
136       for(unsigned int i=0; i<rescaleSize; i++)
137       {
138          *tmpRescale = (uint8_t)( (*tmpImage)>>8 );
139          tmpImage++;
140          tmpRescale++;
141       }
142    }
143    else
144    {
145       std::cout << "Same...";
146       rescaleSize = dataSize;
147       rescaleImage = new uint8_t[dataSize];
148       memcpy(rescaleImage,original.GetImageData(),dataSize);
149    }
150
151    copy.SetImageData(rescaleImage, rescaleSize);
152
153    //////////////// Step 3:
154    std::cout << "3...";
155    copy.SetWriteModeToRGB();
156    if( !copy.WriteDcmExplVR(output) )
157    {
158       std::cout << " Failed" << std::endl
159                 << "        " << output << " not written" << std::endl;
160
161       delete[] rescaleImage;
162
163       return 1;
164    }
165
166    //////////////// Step 4:
167    std::cout << "4...";
168    gdcm::FileHelper copy2 = gdcm::FileHelper( output );
169
170    //Is the file written still gdcm parsable ?
171    if ( !copy2.GetFile()->IsReadable() )
172    { 
173       std::cout << " Failed" << std::endl
174                 << "        " << output << " not readable" << std::endl;
175
176       delete[] rescaleImage;
177
178       return 1;
179    }
180
181    //////////////// Step 5:
182    std::cout << "5...";
183    size_t    dataSizeWritten = copy2.GetImageDataSize();
184    uint8_t *imageDataWritten = copy2.GetImageData();
185
186    if (originalF.GetXSize() != copy2.GetFile()->GetXSize() ||
187        originalF.GetYSize() != copy2.GetFile()->GetYSize() ||
188        originalF.GetZSize() != copy2.GetFile()->GetZSize())
189    {
190       std::cout << "Failed" << std::endl
191          << "        X Size differs: "
192          << "X: " << originalF.GetXSize() << " # " 
193                   << copy2.GetFile()->GetXSize() << " | "
194          << "Y: " << originalF.GetYSize() << " # " 
195                   << copy2.GetFile()->GetYSize() << " | "
196          << "Z: " << originalF.GetZSize() << " # " 
197                   << copy2.GetFile()->GetZSize() << std::endl;
198       delete[] rescaleImage;
199
200       return 1;
201    }
202
203    if (rescaleSize != dataSizeWritten)
204    {
205       std::cout << " Failed" << std::endl
206                 << "        Pixel areas lengths differ: "
207                 << dataSize << " # " << dataSizeWritten << std::endl;
208
209       delete[] rescaleImage;
210
211       return 1;
212    }
213
214    if (int res = memcmp(rescaleImage, imageDataWritten, rescaleSize) !=0)
215    {
216       (void)res;
217       std::cout << " Failed" << std::endl
218                 << "        Pixel differ (as expanded in memory)." << std::endl;
219
220       delete[] rescaleImage;
221
222       return 1;
223    }
224    std::cout << "OK." << std::endl ;
225
226    delete[] rescaleImage;
227
228    return 0;
229 }
230
231 // Here we load a gdcmFile and then try to create from scratch a copy of it,
232 // copying field by field the dicom image
233
234 int TestCopyRescaleDicom(int argc, char *argv[])
235 {
236    if ( argc == 3 )
237    {
238       // The test is specified a specific filename, use it instead of looping
239       // over all images
240       const std::string input     = argv[1];
241       const std::string reference = argv[2];
242       return CopyRescaleDicom( input, reference );
243    }
244    else if ( argc > 3 || argc == 2 )
245    {
246       std::cout << "   Usage: " << argv[0]
247                 << " (no arguments needed)." << std::endl;
248       std::cout << "or   Usage: " << argv[0]
249                 << " filename.dcm reference.dcm" << std::endl;
250       return 1;
251    }
252    // else other cases:
253
254    std::cout << "   Description (Test::TestCopyDicom): "
255              << std::endl;
256    std::cout << "   For all images in gdcmData (and not blacklisted in "
257                 "Test/CMakeLists.txt)"
258              << std::endl;
259    std::cout << "   apply the following to each filename.xxx: "
260              << std::endl;
261    std::cout << "   step 1: parse the image (as gdcmFile) and call"
262              << " IsReadable(). After that, call GetImageData() and "
263              << "GetImageDataSize() "
264              << std::endl;
265    std::cout << "   step 2: create a copy of the readed file and the new"
266              << " pixel data are set to the copy"
267              << std::endl;
268    std::cout << "   step 3: write the copy of the image"
269              << std::endl;
270    std::cout << "   step 4: read the copy and call IsReadable()"
271              << std::endl;
272    std::cout << "   step 5: compare (in memory with memcmp) that the two "
273              << "images " << std::endl
274              << "           match (as expanded by gdcm)." << std::endl;
275    std::cout << std::endl;
276
277
278    clock_t r1,r2, r3,r4;
279    struct tms tms1,tms2, tms3,tms4;
280
281    r3 = times(&tms3);
282    int i =0;
283    int retVal = 0;  //by default this is an error
284    while( gdcmDataImages[i] != 0 )
285    {
286       std::string filename = GDCM_DATA_ROOT;
287       filename += "/";  //doh!
288       filename += gdcmDataImages[i];
289
290       std::string output = "output.dcm";
291
292       r1 = times(&tms1);
293       if( CopyRescaleDicom( filename, output ) != 0 )
294       {
295          retVal++;
296       }
297       r2 = times(&tms2);
298
299       std::cout 
300         << std::setw(150-strlen(gdcmDataImages[i]))
301         << gdcmDataImages[i] << " user time: " 
302         << (long) ((tms2.tms_utime)  - (tms1.tms_utime)) 
303         << " system time: "
304         << (long) ((tms2.tms_stime)  - (tms1.tms_stime)) 
305         << "\t elapsed time: " << r2 - r1
306         << std::endl;
307
308       i++;
309    }
310    r4 = times(&tms4);
311
312    std::cout 
313         << std::setw(150-strlen("Gross Total")) << " --> "
314         << "Gross Total" << " user time: " 
315         << (long) ((tms4.tms_utime)  - (tms3.tms_utime))
316         << " system time: "
317         << (long) ((tms4.tms_stime)  - (tms3.tms_stime)) 
318         << "\t elapsed time: " << (long) (r4 - r3)
319         << std::endl;
320    return retVal;
321 }
322