]> Creatis software - gdcm.git/blob - Testing/TestAllReadCompareDicom.cxx
* Testing/TestAllReadCompareDicom.cxx : amelioration
[gdcm.git] / Testing / TestAllReadCompareDicom.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestAllReadCompareDicom.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/03/31 08:06:21 $
7   Version:   $Revision: 1.33 $
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 "gdcmDirList.h"
19 #include "gdcmFile.h"
20 #include "gdcmFileHelper.h"
21
22 #include <iostream>
23 #include <fstream>
24
25 //Generated file:
26 #include "gdcmDataImages.h"
27
28 /**
29  * /brief   File Read/Writer specific for the TestAllReadCompareDicom test
30  * /remarks The Test file format is (only in little endian) :
31  *  - 4 bytes : 'gdcm'
32  *  - 4 bytes : size X
33  *  - 4 bytes : size Y
34  *  - 4 bytes : size Z
35  *  - 2 bytes : scalar size (8,16,32)
36  *  - 2 bytes : number of components per pixel (1,2,3)
37  *  - n bytes : datas
38  */
39 class TestFile
40 {
41 public:
42    TestFile(void);
43    ~TestFile(void);
44
45    bool IsReadable(void) {return readable;}
46    int GetXSize(void) {return sizeX;};
47    void SetXSize(int size) {sizeX = size;};
48    int GetYSize(void) {return sizeY;};
49    void SetYSize(int size) {sizeY = size;};
50    int GetZSize(void) {return sizeZ;};
51    void SetZSize(int size) {sizeZ = size;};
52    int GetScalarSize(void) {return scalarSize;};
53    void SetScalarSize(int size) {scalarSize = size;};
54    int GetNumberOfComponents(void) {return components;};
55    void SetNumberOfComponents(int size) {components = size;};
56
57    unsigned long GetDataSize(void) {return GetLineSize()*sizeY*sizeZ;}
58    uint8_t *GetData(void) {return data;}
59    void SetData(const uint8_t *newData);
60
61    void Load(const std::string &filename);
62    void Write(const std::string &filename);
63
64 private:
65    unsigned long GetLineSize(void) {return sizeX*scalarSize*components;}
66    int GetSwapCode(uint32_t tag);
67
68    void NewData(void);
69    void DeleteData(void);
70
71    void ReadFile(void);
72    bool ReadFileHeader(std::ifstream *fp);
73    bool ReadFileData(std::ifstream *fp);
74    void WriteFile(void);
75    bool WriteFileHeader(std::ofstream *fp);
76    bool WriteFileData(std::ofstream *fp);
77
78    uint8_t  ReadInt8 (std::ifstream *fp) throw( std::ios::failure );
79    uint16_t ReadInt16(std::ifstream *fp) throw( std::ios::failure );
80    uint32_t ReadInt32(std::ifstream *fp) throw( std::ios::failure );
81    void WriteInt8 (std::ofstream *fp,uint8_t  value);
82    void WriteInt16(std::ofstream *fp,uint16_t value);
83    void WriteInt32(std::ofstream *fp,uint32_t value);
84
85    std::string fileName;
86    bool readable;
87
88    int sizeX;
89    int sizeY;
90    int sizeZ;
91    int scalarSize;
92    int components;
93    uint8_t *data;
94    int swapCode;
95
96    static const unsigned int HEADER_SIZE;
97 };
98
99 const unsigned int TestFile::HEADER_SIZE = 20;
100
101 TestFile::TestFile(void)
102 {
103    fileName = "";
104    readable=false;
105
106    sizeX = 0;
107    sizeY = 0;
108    sizeZ = 0;
109    scalarSize = 0;
110    components = 0;
111    data = NULL;
112
113    swapCode = 1234;
114 }
115
116 TestFile::~TestFile(void)
117 {
118    DeleteData();
119 }
120
121 void TestFile::SetData(const uint8_t *newData)
122 {
123    DeleteData();
124    NewData();
125    if( data )
126       memcpy(data,newData,GetDataSize());
127 }
128
129 void TestFile::Load(const std::string &filename)
130 {
131    fileName = filename;
132    ReadFile();
133 }
134
135 void TestFile::Write(const std::string &filename)
136 {
137    fileName = filename;
138    WriteFile();
139 }
140
141 int TestFile::GetSwapCode(uint32_t tag)
142 {
143    int swap = 0;
144    for(int i=0;i<4;i++)
145    {
146       switch(tag&0x000000FF)
147       {
148          case 'g':
149             swap += (i+1)*1000;
150             break;
151          case 'd':
152             swap += (i+1)*100;
153             break;
154          case 'c':
155             swap += (i+1)*10;
156             break;
157          case 'm':
158             swap += (i+1);
159             break;
160          default:
161             return 0;
162       }
163       tag >>= 8;
164    }
165    return swap;
166 }
167
168 void TestFile::NewData(void)
169 {
170    DeleteData();
171    if( GetDataSize() == 0 )
172       return;
173    data = new uint8_t[GetDataSize()];
174 }
175
176 void TestFile::DeleteData(void)
177 {
178    if( data )
179       delete[] data;
180    data = NULL;
181 }
182
183 void TestFile::ReadFile(void)
184 {
185    readable=true;
186    std::ifstream fp(fileName.c_str(),std::ios::in | std::ios::binary);
187
188    if(!fp)
189    {
190       readable=false;
191       return;
192    }
193
194    try
195    {
196       readable=ReadFileHeader(&fp);
197       if(!readable)
198       {
199          std::cout << "Problems when reading Header part" << std::endl;
200          fp.close();
201          return;
202       }
203
204       readable=ReadFileData(&fp);
205       if(!readable)
206       {
207          std::cout << "Problems when reading datas" << std::endl;
208          fp.close();
209          return;
210       }
211    }
212    catch(...)
213    {
214       readable=false;
215       fp.close();
216       return;
217    }
218
219    fp.close();
220 }
221
222 bool TestFile::ReadFileHeader(std::ifstream *fp)
223 {
224    uint32_t tag = ReadInt32(fp);
225    swapCode = GetSwapCode(tag);
226    if( swapCode == 0 )
227    {
228       std::cout << "TestFile: Bad tag - Must be 'gdcm'" << std::endl;
229       return(false);
230    }
231
232    sizeX = ReadInt32(fp); // Size X
233    sizeY = ReadInt32(fp); // Size Y
234    sizeZ = ReadInt32(fp); // Size Z
235    scalarSize = ReadInt16(fp)/8; // bits per scalar
236    components = ReadInt16(fp); // Number of components
237
238    return(true);
239 }
240
241 bool TestFile::ReadFileData(std::ifstream *fp)
242 {
243    DeleteData();
244
245    // Allocate datas
246    NewData();
247    if( !data )
248       return(false);
249
250    // Read datas
251    fp->read((char *)data,GetDataSize());
252
253    return(true);
254 }
255
256 void TestFile::WriteFile(void)
257 {
258    std::ofstream fp(fileName.c_str(),std::ios::out | std::ios::binary);
259
260    if(!fp)
261    {
262       readable=false;
263       return;
264    }
265
266    WriteFileHeader(&fp);
267    WriteFileData(&fp);
268
269    fp.close();
270 }
271
272 bool TestFile::WriteFileHeader(std::ofstream *fp)
273 {
274    WriteInt8(fp,'g'); // Bitmap tag - must be 'g'
275    WriteInt8(fp,'d'); // Bitmap tag - must be 'd'
276    WriteInt8(fp,'c'); // Bitmap tag - must be 'c'
277    WriteInt8(fp,'m'); // Bitmap tag - must be 'm'
278    WriteInt32(fp,sizeX); // Size X
279    WriteInt32(fp,sizeY); // Size Y
280    WriteInt32(fp,sizeZ); // Size Z
281    WriteInt16(fp,scalarSize*8); // bits per scalar
282    WriteInt16(fp,components); // number of components
283
284    return(true);
285 }
286
287 bool TestFile::WriteFileData(std::ofstream *fp)
288 {
289    fp->write((char *)data,GetDataSize());
290
291    return(true);
292 }
293
294 uint8_t  TestFile::ReadInt8 (std::ifstream *fp)
295    throw( std::ios::failure )
296 {
297    uint8_t g;
298    fp->read ((char*)&g, (size_t)1);
299    if ( fp->fail() )
300       throw std::ios::failure( "TestFile::ReadInt8() - file error." );
301    if( fp->eof() )
302       throw std::ios::failure( "TestFile::ReadInt8() - EOF." );
303    return g;
304 }
305
306 uint16_t TestFile::ReadInt16(std::ifstream *fp)
307    throw( std::ios::failure )
308 {
309    uint16_t g;
310    fp->read ((char*)&g, (size_t)2);
311    if ( fp->fail() )
312       throw std::ios::failure( "TestFile::ReadInt16() - file error." );
313    if( fp->eof() )
314       throw std::ios::failure( "TestFile::ReadInt16() - EOF." );
315
316 #if defined(GDCM_WORDS_BIGENDIAN)
317    g = ( g << 8 |  g >> 8  );
318 #endif
319    return g;
320 }
321
322 uint32_t TestFile::ReadInt32(std::ifstream *fp)
323    throw( std::ios::failure )
324 {
325    uint32_t g;
326    fp->read ((char*)&g, (size_t)4);
327    if ( fp->fail() )
328       throw std::ios::failure( "TestFile::ReadInt32() - file error." );
329    if( fp->eof() )
330       throw std::ios::failure( "TestFile::ReadInt32() - EOF." );
331
332 #if defined(GDCM_WORDS_BIGENDIAN)
333    g = (  (g<<24)               | ((g<<8)  & 0x00ff0000) | 
334        (  (g>>8)  & 0x0000ff00) |  (g>>24)               );
335 #endif
336    return g;
337 }
338
339 void TestFile::WriteInt8 (std::ofstream *fp,uint8_t value)
340 {
341    fp->write((char*)&value, (size_t)1);
342 }
343
344 void TestFile::WriteInt16(std::ofstream *fp,uint16_t value)
345 {
346 #if defined(GDCM_WORDS_BIGENDIAN)
347    value = ( value << 8 |  value >> 8  );
348 #endif
349    fp->write((char*)&value, (size_t)2);
350 }
351
352 void TestFile::WriteInt32(std::ofstream *fp,uint32_t value)
353 {
354 #if defined(GDCM_WORDS_BIGENDIAN)
355    value = (  (value<<24)               | ((value<<8)  & 0x00ff0000) | 
356            (  (value>>8)  & 0x0000ff00) |  (value>>24)               );
357 #endif
358    fp->write((char*)&value, (size_t)4);
359 }
360
361 int InternalTest(std::string const &filename, 
362                  std::string const &referenceFileName )
363 {
364       std::cout << "   Testing: " << filename << std::endl;
365       std::cout << "      ";
366
367       ////// Step 1:
368       std::cout << "1...";
369       gdcm::FileHelper *tested = new gdcm::FileHelper( filename );
370       if( !tested->GetFile()->IsReadable() )
371       {
372         std::cout << " Failed" << std::endl
373                    << "      Image not gdcm compatible:"
374                   << filename << std::endl;
375         delete tested;
376         return 1;
377       }
378
379       ////// Step 2:
380       ////// Check for existence of reference baseline dicom file:
381       std::cout << "2...";
382
383       TestFile *reference = new TestFile();
384       std::ifstream refFile(referenceFileName.c_str(),
385                             std::ios::binary|std::ios::in);
386       if(!refFile)
387       {
388          std::cout << " Failed" << std::endl
389                    << "      Image not found:"
390                    << referenceFileName << std::endl;
391          reference->SetXSize(tested->GetFile()->GetXSize());
392          reference->SetYSize(tested->GetFile()->GetYSize());
393          reference->SetZSize(tested->GetFile()->GetZSize());
394          reference->SetScalarSize(tested->GetFile()->GetPixelSize());
395          reference->SetNumberOfComponents(tested->GetFile()->GetNumberOfScalarComponents());
396          reference->SetData(tested->GetImageData());
397          reference->Write(referenceFileName);
398       }
399       else
400          refFile.close();
401
402       reference->Load(referenceFileName);
403       if(!reference->IsReadable())
404       {
405         std::cout << " Failed" << std::endl
406                    << "      Image not Testing compatible:"
407                   << filename << std::endl;
408          delete reference;
409          delete tested;
410          return 1;
411       }
412
413       ////// Step 3:
414       std::string PixelType = tested->GetFile()->GetPixelType();
415       std::cout << "3...";
416       int testedDataSize    = tested->GetImageDataSize();
417       uint8_t *testedImageData = tested->GetImageData();
418     
419       int    referenceDataSize = reference->GetDataSize();
420       uint8_t *referenceImageData = reference->GetData();
421
422       // Test the image size
423       if (tested->GetFile()->GetXSize() != reference->GetXSize() ||
424           tested->GetFile()->GetYSize() != reference->GetYSize() ||
425           tested->GetFile()->GetZSize() != reference->GetZSize())
426       {
427          std::cout << "Failed" << std::endl
428                    << "        Size differs: "
429                    << "X: " << tested->GetFile()->GetXSize() << " # " 
430                    << reference->GetXSize() << " | "
431                    << "Y: " << tested->GetFile()->GetYSize() << " # " 
432                    << reference->GetYSize() << " | "
433                    << "Z: " << tested->GetFile()->GetZSize() << " # " 
434                    << reference->GetZSize() << std::endl;
435          delete reference;
436          delete tested;
437          return 1;
438       }
439
440       // Test the pixel size
441       if (tested->GetFile()->GetPixelSize() != reference->GetScalarSize() ||
442           tested->GetFile()->GetNumberOfScalarComponents() != reference->GetNumberOfComponents())
443       {
444          std::cout << "Failed" << std::endl
445                    << "        Pixel size differs: " << std::endl
446                    << "        Scalar size: " << tested->GetFile()->GetPixelSize() << " # " 
447                    << reference->GetScalarSize() << std::endl
448                    << "        Number of scalar: " << tested->GetFile()->GetNumberOfScalarComponents() << " # " 
449                    << reference->GetNumberOfComponents() << std::endl;
450          delete reference;
451          delete tested;
452          return 1;
453       }
454
455       // Test the data size
456       if (testedDataSize != referenceDataSize)
457       {
458          std::cout << " Failed" << std::endl
459                    << "        pixel ("
460                    << PixelType
461                    <<") areas lengths differ: "
462                    << testedDataSize << " # " << referenceDataSize
463                    << std::endl
464                    << "        Image size: ("
465                    << tested->GetFile()->GetXSize() << ","
466                    << tested->GetFile()->GetYSize() << ","
467                    << tested->GetFile()->GetZSize() << ")"
468                    << std::endl;
469          delete tested;
470          delete reference;
471          return 1;
472       }
473
474       // Test the data content
475       if (int res = memcmp(testedImageData, referenceImageData,
476                            testedDataSize) != 0 )
477       {
478          (void)res;
479          std::cout << " Failed" << std::endl
480                    << "        pixel (" 
481                    << PixelType
482                    << ") differ (as expanded in memory)."
483                    << std::endl;
484          delete tested;
485          delete reference;
486          return 1;
487       }
488
489       //////////////// Clean up:
490       delete tested;
491       delete reference;
492
493       std::cout << "OK." << std::endl;
494       
495       return 0;
496 }
497
498 int TestAllReadCompareDicom(int argc, char *argv[]) 
499 {
500    if ( argc == 3 )
501    {
502       // The test is specified a specific filename, use it instead of looping
503       // over all images
504       const std::string input = argv[1];
505       const std::string reference = argv[2];
506       return InternalTest( input, reference );
507    }
508    else if ( argc > 3 || argc == 2 )
509    {
510       std::cerr << "   Usage: " << argv[0]
511                 << " (no arguments needed)." << std::endl;
512       std::cerr << "or   Usage: " << argv[0]
513                 << " filename.dcm reference.dcm" << std::endl;
514       return 1;
515    }
516    // else other cases:
517    
518    std::cout << "   Description (Test::TestAllReadCompareDicom): "
519              << std::endl;
520    std::cout << "   For all images in gdcmData (and not blacklisted in "
521                 "Test/CMakeLists.txt)"
522              << std::endl;
523    std::cout << "   apply the following to each filename.xxx: "
524              << std::endl;
525    std::cout << "   step 1: parse the image (as gdcmFile) and call"
526              << " IsReadable(). "
527              << std::endl;
528    std::cout << "   step 2: find in GDCM_DATA_ROOT/BaselineDicom/filename.dcm"
529              << std::endl
530              << "           (with format DICOM V3, explicit Value"
531              << "Representation)"
532              << std::endl;
533    std::cout << "   step 3a: when image NOT found on step 2, write "
534              << std::endl
535              << "            GDCM_DATA_ROOT/BaselineDicom/filename.dcm"
536              << std::endl
537              << "           (with format DICOM V3, explicit Value"
538              << "Representation)"
539              << std::endl;
540    std::cout << "   step 3b: when image found on step 2, and when IsReadable()"
541              << std::endl
542              << "            compare it (in memory with memcmp) with the"
543              << std::endl
544              << "            image we are testing (the one of step 1). "
545              << std::endl << std::endl;
546
547    int i = 0;
548    int result = 0;
549    while( gdcmDataImages[i] != 0 )
550    {
551       ////// Check for existence of reference baseline directory
552
553       std::string baseLineDir = GDCM_DATA_ROOT;
554       baseLineDir += "/BaselineDicom/";
555
556       if( !gdcm::DirList::IsDirectory(baseLineDir) )
557       {
558          std::cerr << "   The reference baseline directory " << std::endl
559                    << "      "
560                    << baseLineDir << std::endl
561                    << "   couldn't be opened."
562                    << std::endl;
563          return 1;
564       }
565
566       ////// Step 1 (see above description):
567       std::string filename = GDCM_DATA_ROOT;
568       filename += "/";
569       filename += gdcmDataImages[i];
570       
571       std::string referenceFileName = baseLineDir + gdcmDataImages[i++];
572       std::string::size_type slash_pos = referenceFileName.rfind( "." );
573       if( slash_pos != std::string::npos )
574       {
575          referenceFileName.replace( slash_pos + 1, 3, "tst" );
576       }
577
578       if( InternalTest( filename, referenceFileName ) != 0 )
579       {
580          result++;
581       }
582    }
583
584    return result;
585 }