]> Creatis software - gdcm.git/blob - Testing/TestAllReadCompareDicom.cxx
Fix mistypings
[gdcm.git] / Testing / TestAllReadCompareDicom.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestAllReadCompareDicom.cxx,v $
5   Language:  C++
6   Date:      $Date: 2008/09/15 15:49:21 $
7   Version:   $Revision: 1.62 $
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_NAME_SPACE::Util::IsCurrentProcessorBigEndian()
295           << std::endl;
296         
297    //if (GetScalarSize() == 1 || GetSwapCode() == 1234)  
298    if (GetScalarSize() == 1 || !GDCM_NAME_SPACE::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_NAME_SPACE::File *f = GDCM_NAME_SPACE::File::New();
450       f->SetLoadMode ( GDCM_NAME_SPACE::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_NAME_SPACE::FileHelper *tested = GDCM_NAME_SPACE::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       // *actual* image length may differ to 1 with Pixel Data Element length!
546       if ((testedDataSize+testedDataSize%2) !=
547                                       (referenceDataSize+referenceDataSize%2) )
548       {
549          std::cout << " Failed" << std::endl
550                    << "        pixel ("
551                    << PixelType
552                    <<") areas lengths differ: "
553                    << testedDataSize << " # " << referenceDataSize
554                    << std::endl
555                    << "        Image size: ("
556                    << tested->GetFile()->GetXSize() << ","
557                    << tested->GetFile()->GetYSize() << ","
558                    << tested->GetFile()->GetZSize() << ") nb of scalar components "
559                    << tested->GetFile()->GetNumberOfScalarComponents()
560                    << std::endl;
561          tested->Delete();
562          delete reference;
563          f->Delete();
564          return 1;
565       }
566
567       // Test the data content
568       int length = tested->GetFile()->GetXSize()*tested->GetFile()->GetYSize()*tested->GetFile()->GetZSize()
569                   *reference->GetScalarSize()*tested->GetFile()->GetNumberOfScalarComponents();
570
571       // *actual* image length may differ to 1 with Pixel Data Element length!
572       if (length != testedDataSize)
573          std::cout <<"--------------------length " << length << " != testedDataSize " << testedDataSize << std::endl;
574       if ( memcmp(testedImageData, referenceImageData,
575                            length/*testedDataSize*/) != 0 )
576       {
577          std::string ts  = tested->GetFile()->GetTransferSyntax();
578
579          std::cout << " Failed" << std::endl
580                    << "        pixel (" 
581                    << PixelType
582                    << ") differ (as expanded in memory)."
583                    << std::endl
584                    << "        compression : " 
585                    << GDCM_NAME_SPACE::Global::GetTS()->GetValue(ts) << std::endl;
586
587          std::cout << "        list of the first " << MAX_NUMBER_OF_DIFFERENCE
588                    << " pixels differing (pos : test - ref) :" 
589                    << std::endl;
590          int i;
591          unsigned int j;
592          for(i=0, j=0;i<testedDataSize && j<MAX_NUMBER_OF_DIFFERENCE;i++)
593          {
594             if(testedImageData[i]!=referenceImageData[i])
595               {
596                std::cout << std::hex << "(" << i << " : " 
597                          << std::hex << (int)(testedImageData[i]) << " - "
598                          << std::hex << (int)(referenceImageData[i]) << ") "
599                          << std::dec;
600                ++j;
601               }
602          }
603          std::cout << std::endl;
604
605          tested->Delete();
606          delete reference;
607          f->Delete();
608          return 1;
609       }
610
611       //////////////// Clean up:
612       tested->Delete();
613       delete reference;
614       f->Delete();
615
616       std::cout << "OK." << std::endl;
617       
618       return 0;
619 }
620
621 int TestAllReadCompareDicom(int argc, char *argv[]) 
622 {
623 // Temporarily added, to track BigEndian troubles
624 GDCM_NAME_SPACE::Debug::WarningOn();
625
626    if (argc == 4)
627       GDCM_NAME_SPACE::Debug::DebugOn();
628
629    if ( argc >= 3 )
630    {
631       // The test is specified a specific filename, use it instead of looping
632       // over all images
633       const std::string input = argv[1];
634       const std::string reference = argv[2];
635       return InternalTest( input, reference );
636    }
637    else if ( argc > 4 || argc == 2 )
638    {
639       std::cerr << "   Usage: " << argv[0]
640                 << " (no arguments needed)." << std::endl;
641       std::cerr << "or   Usage: " << argv[0]
642                 << " filename.dcm reference.dcm" << std::endl;
643       return 1;
644    }
645    // else other cases:
646    
647    std::cout << "   Description (Test::TestAllReadCompareDicom): "
648              << std::endl;
649    std::cout << "   For all images in gdcmData (and not blacklisted in "
650                 "Test/CMakeLists.txt)"
651              << std::endl;
652    std::cout << "   apply the following to each filename.xxx: "
653              << std::endl;
654    std::cout << "   step 1: parse the image (as gdcmFile) and call"
655              << " IsReadable(). "
656              << std::endl;
657    std::cout << "   step 2: find in GDCM_DATA_ROOT/BaselineDicom/filename.tst"
658              << std::endl
659              << "           special internal file format containing the"
660              << std::endl
661              << "           caracteristic of the image and the pixel data "
662              << "(uncompressed). This file is written if it's not found."
663              << std::endl;
664    std::cout << "   step 3: compare the DICOM image with the reference image"
665              << std::endl
666              << "           (.tst file). The test is made on the caracteristics"
667              << std::endl
668              << "           of the image and the pixel data"
669              << std::endl << std::endl;
670
671    int i = 0;
672    int result = 0;
673    while( gdcmDataImages[i] != 0 )
674    {
675       ////// Check for existence of reference baseline directory
676
677       std::string baseLineDir = GDCM_DATA_ROOT;
678       baseLineDir += "/BaselineDicom";
679
680       if( !GDCM_NAME_SPACE::DirList::IsDirectory(baseLineDir) )
681       {
682          std::cerr << "   The reference baseline directory " << std::endl
683                    << "      "
684                    << baseLineDir << std::endl
685                    << "   couldn't be opened."
686                    << std::endl;
687          return 1;
688       }
689
690 //if (gdcmDataImages[i] == "D_CLUNIE_CT2_RLE.dcm")
691 //   GDCM_NAME_SPACE::Debug::DebugOn(); // track pb on BigEndian Proc
692 //else 
693    GDCM_NAME_SPACE::Debug::DebugOff();
694    
695       ////// Step 1 (see above description):
696       std::string filename = GDCM_DATA_ROOT;
697       filename += "/";
698       filename += gdcmDataImages[i];
699       
700       baseLineDir += '/';
701       std::string referenceFileName = baseLineDir + gdcmDataImages[i++];
702       std::string::size_type slash_pos = referenceFileName.rfind( "." );
703       if( slash_pos != std::string::npos )
704       {
705          referenceFileName.replace( slash_pos + 1, 3, "tst" );
706       }
707
708       if( InternalTest( filename, referenceFileName ) != 0 )
709       {
710          result++;
711       }
712    }
713
714    return result;
715 }