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