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