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