]> Creatis software - gdcm.git/blob - Testing/TestAllReadCompareDicom.cxx
Fix the test suite, when there is no mistake in the library ;-)
[gdcm.git] / Testing / TestAllReadCompareDicom.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestAllReadCompareDicom.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/11/15 11:43:22 $
7   Version:   $Revision: 1.55 $
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 if, you'll get *allways* "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    return swap;
201 }
202
203 void TestFile::NewData()
204 {
205    DeleteData();
206    if( GetDataSize() == 0 )
207       return;
208    Data = new uint8_t[GetDataSize()];
209 }
210
211 void TestFile::DeleteData()
212 {
213    if( Data )
214       delete[] Data;
215    Data = NULL;
216 }
217
218 void TestFile::ReadFile()
219 {
220    readable=true;
221    std::ifstream fp(fileName.c_str(),std::ios::in | std::ios::binary);
222
223    if(!fp)
224    {
225       readable=false;
226       return;
227    }
228
229    try
230    {
231       readable=ReadFileHeader(&fp);
232       if(!readable)
233       {
234          std::cout << "Problems when reading Header part" << std::endl;
235          fp.close();
236          return;
237       }
238
239       readable=ReadFileData(&fp);
240       if(!readable)
241       {
242          std::cout << "Problems when reading data" << std::endl;
243          fp.close();
244          return;
245       }
246    }
247    catch(...)
248    {
249       readable=false;
250       fp.close();
251       return;
252    }
253
254    fp.close();
255 }
256
257 bool TestFile::ReadFileHeader(std::ifstream *fp)
258 {
259    uint32_t tag = ReadInt32(fp);
260    SwapCode = ComputeSwapCode(tag);
261    if( SwapCode == 0 )
262    {
263       std::cout << "TestFile: Bad tag - Must be 'gdcm'" << std::endl;
264       return(false);
265    }
266
267    SizeX = ReadInt32(fp); // Size X
268    SizeY = ReadInt32(fp); // Size Y
269    SizeZ = ReadInt32(fp); // Size Z
270    ScalarSize = ReadInt16(fp)/8; // bytes per scalar
271    Components = ReadInt16(fp);   // Number of components
272
273    return(true);
274 }
275
276 bool TestFile::ReadFileData(std::ifstream *fp)
277 {
278    DeleteData();
279
280    // Allocate data
281    NewData();
282    if( !Data )
283       return(false);
284
285    // Read data
286    fp->read((char *)Data,GetDataSize());
287
288    // Track BigEndian troubles
289    std::cout << " ScalarSize : " << GetScalarSize() 
290           << " SwapCode:" << GetSwapCode()
291           << std::endl;
292         
293    //if (GetScalarSize() == 1 || GetSwapCode() == 1234)
294    if (GetScalarSize() == 1 || !gdcm::Util::IsCurrentProcessorBigEndian() )    
295    {
296       return true;
297    }
298    // We *know* the .tst files are written in 'Little Endian' format.
299    // We *know* DataSize may be 1 or 2 !  
300    uint16_t g;
301    
302    std::cout << " Let's swap Pixels" <<std::endl; 
303      
304    for (unsigned int i=0; i<GetDataSize()/2; i++)
305    {
306       g = ((uint16_t *)Data)[i];
307       g = ( g << 8 |  g >> 8  );
308       ((uint16_t *)Data)[i] = g;   
309    }
310    return(true);
311 }
312
313 void TestFile::WriteFile()
314 {
315    std::ofstream fp(fileName.c_str(),std::ios::out | std::ios::binary);
316
317    if(!fp)
318    {
319       readable=false;
320       return;
321    }
322
323    WriteFileHeader(&fp);
324    WriteFileData(&fp);
325
326    fp.close();
327 }
328
329 bool TestFile::WriteFileHeader(std::ofstream *fp)
330 {
331    WriteInt8(fp,'g'); // Bitmap tag - must be 'g'
332    WriteInt8(fp,'d'); // Bitmap tag - must be 'd'
333    WriteInt8(fp,'c'); // Bitmap tag - must be 'c'
334    WriteInt8(fp,'m'); // Bitmap tag - must be 'm'
335    
336    // FIXME : Think of writting an int32, better !
337    // (('g' << 8 + 'd') << 8 + 'c') + 'm'
338    // if you want to use it to check the endianess.
339    // (and upload again *all* the .tst files ...)
340    WriteInt32(fp,SizeX); // Size X
341    WriteInt32(fp,SizeY); // Size Y
342    WriteInt32(fp,SizeZ); // Size Z
343    WriteInt16(fp,ScalarSize*8); // bits per scalar
344    WriteInt16(fp,Components);   // number of components
345
346    return(true);
347 }
348
349 bool TestFile::WriteFileData(std::ofstream *fp)
350 {
351    fp->write((char *)Data,GetDataSize());
352
353    return(true);
354 }
355
356 uint8_t  TestFile::ReadInt8 (std::ifstream *fp)
357 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
358    throw( std::ios::failure )
359 #endif
360 {
361    uint8_t g;
362    fp->read ((char*)&g, (size_t)1);
363 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
364    if ( fp->fail() )
365       throw std::ios::failure( "TestFile::ReadInt8() - file error." );
366    if( fp->eof() )
367       throw std::ios::failure( "TestFile::ReadInt8() - EOF." );
368 #endif
369    return g;
370 }
371
372 uint16_t TestFile::ReadInt16(std::ifstream *fp)
373 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
374    throw( std::ios::failure )
375 #endif
376 {
377    uint16_t g;
378    fp->read ((char*)&g, (size_t)2);
379 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
380    if ( fp->fail() )
381       throw std::ios::failure( "TestFile::ReadInt16() - file error." );
382    if( fp->eof() )
383       throw std::ios::failure( "TestFile::ReadInt16() - EOF." );
384 #endif
385
386 #if defined(GDCM_WORDS_BIGENDIAN)
387    g = ( g << 8 |  g >> 8  );
388 #endif
389    return g;
390 }
391
392 uint32_t TestFile::ReadInt32(std::ifstream *fp)
393 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
394    throw( std::ios::failure )
395 #endif
396 {
397    uint32_t g;
398    fp->read ((char*)&g, (size_t)4);
399 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
400    if ( fp->fail() )
401       throw std::ios::failure( "TestFile::ReadInt32() - file error." );
402    if( fp->eof() )
403       throw std::ios::failure( "TestFile::ReadInt32() - EOF." );
404 #endif
405
406 #if defined(GDCM_WORDS_BIGENDIAN)
407    g = (  (g<<24)               | ((g<<8)  & 0x00ff0000) | 
408        (  (g>>8)  & 0x0000ff00) |  (g>>24)               );
409 #endif
410    return g;
411 }
412
413 void TestFile::WriteInt8 (std::ofstream *fp,uint8_t value)
414 {
415    fp->write((char*)&value, (size_t)1);
416 }
417
418 void TestFile::WriteInt16(std::ofstream *fp,uint16_t value)
419 {
420 #if defined(GDCM_WORDS_BIGENDIAN)
421    value = ( value << 8 |  value >> 8  );
422 #endif
423    fp->write((char*)&value, (size_t)2);
424 }
425
426 void TestFile::WriteInt32(std::ofstream *fp,uint32_t value)
427 {
428 #if defined(GDCM_WORDS_BIGENDIAN)
429    value = (  (value<<24)               | ((value<<8)  & 0x00ff0000) | 
430            (  (value>>8)  & 0x0000ff00) |  (value>>24)               );
431 #endif
432    fp->write((char*)&value, (size_t)4);
433 }
434
435 int InternalTest(std::string const &filename, 
436                  std::string const &referenceFileName )
437 {
438       std::cout << "   Testing: " << filename << std::endl;
439       std::cout << "      ";
440
441       ////// Step 1:
442       std::cout << "1...";
443
444        // new style 
445       gdcm::File *f = gdcm::File::New();
446       f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
447       f->SetFileName( filename );
448       f->Load();
449  
450       if( !f->IsReadable() )
451       {
452         std::cout << " Failed" << std::endl
453                    << "      Image not gdcm compatible:"
454                   << filename << std::endl;
455         f->Delete();
456         return 1;
457       }
458       gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
459      
460       ////// Step 2:
461       ////// Check for existence of reference baseline dicom file:
462       std::cout << "2...";
463
464       TestFile *reference = new TestFile();
465       std::ifstream refFile(referenceFileName.c_str(),
466                             std::ios::binary|std::ios::in);
467       if(!refFile)
468       {
469          std::cout << " Failed" << std::endl
470                    << "      Image not found:"
471                    << referenceFileName << std::endl;
472          reference->SetXSize(tested->GetFile()->GetXSize());
473          reference->SetYSize(tested->GetFile()->GetYSize());
474          reference->SetZSize(tested->GetFile()->GetZSize());
475          reference->SetScalarSize(tested->GetFile()->GetPixelSize());
476          reference->SetNumberOfComponents(tested->GetFile()->GetNumberOfScalarComponents());
477          reference->SetData(tested->GetImageData());
478          reference->Write(referenceFileName);
479       }
480       else
481          refFile.close();
482
483       reference->Load(referenceFileName);
484       if(!reference->IsReadable())
485       {
486         std::cout << " Failed" << std::endl
487                    << "      Image not Testing compatible:"
488                   << filename << std::endl;
489          delete reference;
490          tested->Delete();
491          f->Delete();
492          return 1;
493       }
494
495       ////// Step 3:
496       std::string PixelType = tested->GetFile()->GetPixelType();
497       std::cout << "3...";
498       int testedDataSize    = tested->GetImageDataSize();
499       uint8_t *testedImageData = tested->GetImageData();
500     
501       int    referenceDataSize = reference->GetDataSize();
502       uint8_t *referenceImageData = reference->GetData();
503
504       // Test the image size
505       if (tested->GetFile()->GetXSize() != reference->GetXSize() ||
506           tested->GetFile()->GetYSize() != reference->GetYSize() ||
507           tested->GetFile()->GetZSize() != reference->GetZSize())
508       {
509          std::cout << "Failed" << std::endl
510                    << "        Size differs: "
511                    << "X: " << tested->GetFile()->GetXSize() << " # " 
512                    << reference->GetXSize() << " | "
513                    << "Y: " << tested->GetFile()->GetYSize() << " # " 
514                    << reference->GetYSize() << " | "
515                    << "Z: " << tested->GetFile()->GetZSize() << " # " 
516                    << reference->GetZSize() << std::endl;
517          delete reference;
518          tested->Delete();
519          f->Delete();
520          return 1;
521       }
522
523       // Test the pixel size
524       if (tested->GetFile()->GetPixelSize() != reference->GetScalarSize() ||
525           tested->GetFile()->GetNumberOfScalarComponents() != reference->GetNumberOfComponents())
526       {
527          std::cout << "Failed" << std::endl
528                    << "        Pixel size differs: " << std::endl
529                    << "        Scalar size: " << tested->GetFile()->GetPixelSize() << " # " 
530                    << reference->GetScalarSize() << std::endl
531                    << "        Number of scalar: " << tested->GetFile()->GetNumberOfScalarComponents() << " # " 
532                    << reference->GetNumberOfComponents() << std::endl
533                    << "        Pixel type: " << tested->GetFile()->GetPixelType() << std::endl;
534          delete reference;
535          tested->Delete();
536          f->Delete();
537          return 1;
538       }
539
540       // Test the data size
541       if (testedDataSize != referenceDataSize)
542       {
543          std::cout << " Failed" << std::endl
544                    << "        pixel ("
545                    << PixelType
546                    <<") areas lengths differ: "
547                    << testedDataSize << " # " << referenceDataSize
548                    << std::endl
549                    << "        Image size: ("
550                    << tested->GetFile()->GetXSize() << ","
551                    << tested->GetFile()->GetYSize() << ","
552                    << tested->GetFile()->GetZSize() << ")"
553                    << std::endl;
554          tested->Delete();
555          delete reference;
556          f->Delete();
557          return 1;
558       }
559
560       // Test the data content
561       if ( memcmp(testedImageData, referenceImageData,
562                            testedDataSize) != 0 )
563       {
564          std::string ts  = tested->GetFile()->GetTransferSyntax();
565
566          std::cout << " Failed" << std::endl
567                    << "        pixel (" 
568                    << PixelType
569                    << ") differ (as expanded in memory)."
570                    << std::endl
571                    << "        compression : " 
572                    << gdcm::Global::GetTS()->GetValue(ts) << std::endl;
573
574          std::cout << "        list of the first " << MAX_NUMBER_OF_DIFFERENCE
575                    << " pixels differing (pos : test - ref) :" 
576                    << std::endl;
577          int i;
578          unsigned int j;
579          for(i=0, j=0;i<testedDataSize && j<MAX_NUMBER_OF_DIFFERENCE;i++)
580          {
581             if(testedImageData[i]!=referenceImageData[i])
582               {
583                std::cout << std::hex << "(" << i << " : " 
584                          << std::hex << (int)(testedImageData[i]) << " - "
585                          << std::hex << (int)(referenceImageData[i]) << ") "
586                          << std::dec;
587                ++j;
588               }
589          }
590          std::cout << std::endl;
591
592          tested->Delete();
593          delete reference;
594          f->Delete();
595          return 1;
596       }
597
598       //////////////// Clean up:
599       tested->Delete();
600       delete reference;
601       f->Delete();
602
603       std::cout << "OK." << std::endl;
604       
605       return 0;
606 }
607
608 int TestAllReadCompareDicom(int argc, char *argv[]) 
609 {
610 // Temporarily added, to track BigEndian troubles
611 gdcm::Debug::WarningOn();
612
613    if (argc == 4)
614       gdcm::Debug::DebugOn();
615
616    if ( argc >= 3 )
617    {
618       // The test is specified a specific filename, use it instead of looping
619       // over all images
620       const std::string input = argv[1];
621       const std::string reference = argv[2];
622       return InternalTest( input, reference );
623    }
624    else if ( argc > 4 || argc == 2 )
625    {
626       std::cerr << "   Usage: " << argv[0]
627                 << " (no arguments needed)." << std::endl;
628       std::cerr << "or   Usage: " << argv[0]
629                 << " filename.dcm reference.dcm" << std::endl;
630       return 1;
631    }
632    // else other cases:
633    
634    std::cout << "   Description (Test::TestAllReadCompareDicom): "
635              << std::endl;
636    std::cout << "   For all images in gdcmData (and not blacklisted in "
637                 "Test/CMakeLists.txt)"
638              << std::endl;
639    std::cout << "   apply the following to each filename.xxx: "
640              << std::endl;
641    std::cout << "   step 1: parse the image (as gdcmFile) and call"
642              << " IsReadable(). "
643              << std::endl;
644    std::cout << "   step 2: find in GDCM_DATA_ROOT/BaselineDicom/filename.tst"
645              << std::endl
646              << "           special internal file format containing the"
647              << std::endl
648              << "           caracteristic of the image and the pixel data "
649              << "(uncompressed). This file is written if it's not found."
650              << std::endl;
651    std::cout << "   step 3: compare the DICOM image with the reference image"
652              << std::endl
653              << "           (.tst file). The test is made on the caracteristics"
654              << std::endl
655              << "           of the image and the pixel data"
656              << std::endl << std::endl;
657
658    int i = 0;
659    int result = 0;
660    while( gdcmDataImages[i] != 0 )
661    {
662       ////// Check for existence of reference baseline directory
663
664       std::string baseLineDir = GDCM_DATA_ROOT;
665       baseLineDir += "/BaselineDicom";
666
667       if( !gdcm::DirList::IsDirectory(baseLineDir) )
668       {
669          std::cerr << "   The reference baseline directory " << std::endl
670                    << "      "
671                    << baseLineDir << std::endl
672                    << "   couldn't be opened."
673                    << std::endl;
674          return 1;
675       }
676
677       ////// Step 1 (see above description):
678       std::string filename = GDCM_DATA_ROOT;
679       filename += "/";
680       filename += gdcmDataImages[i];
681       
682       baseLineDir += '/';
683       std::string referenceFileName = baseLineDir + gdcmDataImages[i++];
684       std::string::size_type slash_pos = referenceFileName.rfind( "." );
685       if( slash_pos != std::string::npos )
686       {
687          referenceFileName.replace( slash_pos + 1, 3, "tst" );
688       }
689
690       if( InternalTest( filename, referenceFileName ) != 0 )
691       {
692          result++;
693       }
694    }
695
696    return result;
697 }