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