File: dicomdump.cxx

package info (click to toggle)
vtk-dicom 0.8.17-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,176 kB
  • sloc: cpp: 113,811; python: 2,041; makefile: 43; tcl: 10
file content (625 lines) | stat: -rw-r--r-- 17,282 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/*=========================================================================

  Program: DICOM for VTK

  Copyright (c) 2012-2024 David Gobbi
  All rights reserved.
  See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDICOMConfig.h"
#include "vtkDICOMParser.h"
#include "vtkDICOMDictionary.h"
#include "vtkDICOMDirectory.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMItem.h"
#include "vtkDICOMUtilities.h"

// from dicomcli
#include "vtkConsoleOutputWindow.h"
#include "mainmacro.h"
#include "readquery.h"

#include "vtkSortFileNames.h"
#include "vtkStringArray.h"
#include "vtkSmartPointer.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_INDENT 24
#define INDENT_SIZE 2
#define MAX_LENGTH 120

// print the version
void printVersion(FILE *file, const char *cp)
{
  fprintf(file, "%s %s\n", cp, DICOM_VERSION);
  fprintf(file, "\n"
    "Copyright (c) 2012-2024, David Gobbi.\n\n"
    "This software is distributed under an open-source license.  See the\n"
    "Copyright.txt file that comes with the vtk-dicom source distribution.\n");
}

// print the usage
void printUsage(FILE *file, const char *cp)
{
  fprintf(file, "usage:\n"
    "  %s file1.dcm [file2.dcm ...]\n\n", cp);
  fprintf(file, "options:\n"
    "  -k tag          Provide a tag or key to be printed.\n"
    "  -q <query.txt>  Provide a file that lists which elements to print.\n"
    "  --charset <cs>  Charset to use if SpecificCharacterSet is missing.\n"
    "  --help          Print a brief help message.\n"
    "  --version       Print the software version.\n");
}

// print the help
void printHelp(FILE *file, const char *cp)
{
  printUsage(file, cp);
  fprintf(file, "\n"
    "Dump the metadata from a set of DICOM files as text.\n"
    "\n"
    "By default, all the attributes are dumped.  However, If only a few\n"
    "attributes are to be dumped, then their tags can be given with \"-k\"\n"
    "(the \"-k\" option can be repeated as many times as needed).  Tags can\n"
    "be given in hexadecimal GGGG,EEEE format, or in text format as specified\n"
    "in the DICOM dictionary key.  Alternatively, the tags can be listed in\n"
    "a query file given with the \"-q\" option (one tag per line).\n"
    "Attributes nested within sequences can be specified by giving a tag\n"
    "path e.g. \"-k Tag1/Tag2/Tag3\".  Either a forward slash or a backslash\n"
    "can be used to separate the components of the path.\n"
    "\n"
    "For text attribute values, any unprintable bytes will be replaced with\n"
    "the four characters \"\\nnn\", where \"nnn\" is the three digit octal code\n"
    "for the byte.  Unprintable bytes are control characters or bytes that\n"
    "cannot be decoded with the SpecificCharacterSet of the DICOM file.  A\n"
    "backslash itself will be replaced by its byte value \"\\134\" if the VR is\n"
    "ST, LT or UT (that is, any VR where backslash isn't used as a separator\n"
    "for multi-valued attributes).\n\n");
}

// remove path portion of filename
const char *fileBasename(const char *filename)
{
  const char *cp = filename + strlen(filename);
  while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; }
  return cp;
}

// Print out one data element
void printElement(
  vtkDICOMMetaData *meta, const vtkDICOMItem *item,
  const vtkDICOMDataElementIterator &iter, int depth,
  unsigned int pixelDataVL)
{
  vtkDICOMTag tag = iter->GetTag();
  int g = tag.GetGroup();
  int e = tag.GetElement();
  vtkDICOMVR vr = iter->GetVR();
  const char *name = "";
  vtkDICOMDictEntry d;
  if (item)
  {
    d = item->FindDictEntry(tag);
  }
  else if (meta)
  {
    d = meta->FindDictEntry(tag);
  }
  if (d.IsValid())
  {
    name = d.GetName();
    if (d.GetVR() != vr &&
        !(d.GetVR() == vtkDICOMVR::XS &&
          (vr == vtkDICOMVR::SS || vr == vtkDICOMVR::US)) &&
        !(d.GetVR() == vtkDICOMVR::OX &&
          (vr == vtkDICOMVR::OB || vr == vtkDICOMVR::OW)))
    {
      printf("VR mismatch! %s != %s %s\n",
             vr.GetText(), d.GetVR().GetText(), name);
    }
  }
  else if ((tag.GetGroup() & 0xFFFE) != 0 && tag.GetElement() == 0)
  {
    // group is even, element is zero
    name = "GroupLength";
  }
  else if ((tag.GetGroup() & 0x0001) != 0 &&
           (tag.GetElement() & 0xFF00) == 0)
  {
    // group is odd, element is a creator element
    name = "PrivateCreator";
  }
  // allow multiple values (i.e. for each image in series)
  vtkDICOMValue v = iter->GetValue();
  size_t vn = v.GetNumberOfValues();
  const vtkDICOMValue *vp = v.GetMultiplexData();
  if (vp == nullptr)
  {
    vp = &v;
    vn = 1;
  }

  // make an indentation string
  if (INDENT_SIZE*depth > MAX_INDENT)
  {
    depth = MAX_INDENT/INDENT_SIZE;
  }
  static const char spaces[MAX_INDENT+1] = "                        ";
  const char *indent = spaces + (MAX_INDENT - INDENT_SIZE*depth);

  for (size_t vi = 0; vi < vn; vi++)
  {
    v = vp[vi];
    unsigned int vl = v.GetVL();
    if (tag == DC::PixelData ||
        tag == DC::FloatPixelData ||
        tag == DC::DoubleFloatPixelData)
    {
      vl = (depth == 0 && vl == 0 ? pixelDataVL : v.GetVL());
    }
    std::string s;
    if (vr == vtkDICOMVR::UN ||
        vr == vtkDICOMVR::SQ)
    {
      // sequences are printed later
      s = (vl > 0 ? "..." : "");
    }
    else if (vr == vtkDICOMVR::LT ||
             vr == vtkDICOMVR::ST ||
             vr == vtkDICOMVR::UT)
    {
      vtkDICOMCharacterSet cs = v.GetCharacterSet();
      const char *cp = v.GetCharData();
      size_t l = vl;
      bool truncated = false;
      while (l > 0 && cp[l-1] == ' ')
      {
        l--;
      }
      if (l > MAX_LENGTH)
      {
        l = MAX_LENGTH;
        truncated = true;
      }
      std::string utf8 = cs.ToSafeUTF8(cp, l);
      cp = utf8.data();
      l = utf8.length();
      if (l > MAX_LENGTH)
      {
        l = MAX_LENGTH-3;
        truncated = true;
        // remove possibly incomplete final character
        while (l > 1 && (cp[l-1] & 0xC0) == 0x80)
        {
          l--;
        }
        l--;
      }
      s.append(cp, l);
      if (truncated)
      {
        s.append("...");
      }
    }
    else if (vr.HasTextValue())
    {
      vtkDICOMCharacterSet cs = v.GetCharacterSet();
      const char *cp = v.GetCharData();
      const char *ep = cp + vl;
      size_t pos = 0;
      while (cp != ep && *cp != '\0')
      {
        size_t n = cs.NextBackslash(cp, ep);
        while (n > 0 && *cp == ' ') { cp++; n--; }
        size_t m = n;
        while (m > 0 && cp[m-1] == ' ') { m--; }
        s.append(cs.ToSafeUTF8(cp, m));
        cp += n;
        if (cp != ep && *cp == '\\')
        {
          s.append(cp, 1);
          cp++;
        }
        if (s.size() > MAX_LENGTH-4)
        {
          s.resize(pos);
          s.append("...");
          break;
        }
        pos = s.size();
      }
    }
    else
    {
      // print any other VR via conversion to string
      size_t n = v.GetNumberOfValues();
      size_t pos = 0;
      for (size_t i = 0; i < n; i++)
      {
        v.AppendValueToString(s, i);
        if (i < n - 1)
        {
          s.append("\\");
        }
        if (s.size() > MAX_LENGTH-4)
        {
          s.resize(pos);
          s.append("...");
          break;
        }
        pos = s.size();
      }
    }

    if (meta && vi == 0)
    {
      printf("%s(%04X,%04X) %s \"%s\" :", indent, g, e, vr.GetText(), name);
    }
    if (meta && vn > 1)
    {
      printf("%s%s  %4.4u",
        (vi == 0 ? " (multiple values)\n" : ""), indent,
        static_cast<unsigned int>(vi + 1));
    }
    if (vr == vtkDICOMVR::SQ)
    {
      size_t m = v.GetNumberOfValues();
      const vtkDICOMItem *items = v.GetSequenceData();
      printf(" (%u %s%s)\n",
        static_cast<unsigned int>(m), (m == 1 ? "item" : "items"),
        (vl == 0xffffffffu ? ", delimited" : ""));
      for (size_t j = 0; j < m; j++)
      {
        printf("%s%s---- SQ Item %04u at offset %u ----\n",
          indent, spaces+(MAX_INDENT - INDENT_SIZE),
          static_cast<unsigned int>(j+1),
          items[j].GetByteOffset());
        vtkDICOMDataElementIterator siter = items[j].Begin();
        vtkDICOMDataElementIterator siterEnd = items[j].End();

        for (; siter != siterEnd; ++siter)
        {
          printElement(meta, &items[j], siter, depth+1, pixelDataVL);
        }
      }
    }
    else if (vl == 0xffffffffu)
    {
      if (tag == DC::PixelData ||
          tag == DC::FloatPixelData ||
          tag == DC::DoubleFloatPixelData)
      {
        printf(" [...] (compressed)\n");
      }
      else
      {
        printf(" [...] (delimited)\n");
      }
    }
    else
    {
      const char *uidName = "";
      if (vr == vtkDICOMVR::UI)
      {
        uidName = vtkDICOMUtilities::GetUIDName(s.c_str());
      }
      if (uidName[0] != '\0')
      {
        printf(" [%s] {%s} (%u bytes)\n", s.c_str(), uidName, vl);
      }
      else if (vr == vtkDICOMVR::OB ||
               vr == vtkDICOMVR::OW ||
               vr == vtkDICOMVR::OF ||
               vr == vtkDICOMVR::OD)
      {
        printf(" [%s] (%u bytes)\n", (vl == 0 ? "" : "..."), vl);
      }
      else
      {
        printf(" [%s] (%u bytes)\n", s.c_str(), vl);
      }
    }
  }
}

void printElementFromTagPathRecurse(
  const vtkDICOMItem *item, const vtkDICOMTagPath& tagPath,
  const vtkDICOMTagPath& fullPath, int *count)
{
  vtkDICOMTag tag = tagPath.GetHead();

  vtkDICOMDataElementIterator iter = item->Begin();
  while (iter != item->End() && iter->GetTag() != tag)
  {
    ++iter;
  }

  if (iter != item->End())
  {
    if (tagPath.HasTail())
    {
      const vtkDICOMItem *items = iter->GetValue().GetSequenceData();
      if (items)
      {
        size_t n = iter->GetValue().GetNumberOfValues();
        for (size_t i = 0; i < n; i++)
        {
          printElementFromTagPathRecurse(
            &items[i], tagPath.GetTail(), fullPath, count);
        }
      }
    }
    else
    {
      ++(*count);
      fprintf(stdout, "  %04d", *count);
      printElement(nullptr, item, iter, 0, 0);
    }
  }
}

void printElementFromTagPath(
  vtkDICOMMetaData *data, const vtkDICOMTagPath& tagPath,
  unsigned int pixelDataVL)
{
  int count = 0;
  vtkDICOMTag tag = tagPath.GetHead();
  vtkDICOMDataElementIterator iter = data->Find(tag);
  if (iter != data->End())
  {
    if (tagPath.HasTail())
    {
      for (vtkDICOMTagPath p = tagPath; ; p = p.GetTail())
      {
        int g = p.GetHead().GetGroup();
        int e = p.GetHead().GetElement();
        if (p.HasTail())
        {
          printf("(%04X,%04X)\\", g, e);
        }
        else
        {
          vtkDICOMDictEntry entry =
            vtkDICOMDictionary::FindDictEntry(p.GetHead());
          vtkDICOMVR vr = entry.GetVR();
          const char *name = entry.GetName();
          name = ((name && name[0]) ? name : "Unknown");
          printf("(%04X,%04X) %s \"%s\" : (nested)\n",
            g, e, vr.GetText(), name);
          break;
        }
      }
      if (iter->IsPerInstance())
      {
        for (int j = 0; j < iter->GetNumberOfInstances(); j++)
        {
          const vtkDICOMItem *items = iter->GetValue(j).GetSequenceData();
          if (items)
          {
            size_t n = iter->GetValue(j).GetNumberOfValues();
            for (size_t i = 0; i < n; i++)
            {
              printElementFromTagPathRecurse(
                &items[i], tagPath.GetTail(), tagPath, &count);
            }
          }
        }
      }
      else
      {
        const vtkDICOMItem *items = iter->GetValue().GetSequenceData();
        if (items)
        {
          size_t n = iter->GetValue().GetNumberOfValues();
          for (size_t i = 0; i < n; i++)
          {
            printElementFromTagPathRecurse(
              &items[i], tagPath.GetTail(), tagPath, &count);
          }
        }
      }
    }
    else
    {
      printElement(data, nullptr, iter, 0, pixelDataVL);
    }
  }
}

// This program will dump all the metadata in the given file
int MAINMACRO(int argc, char *argv[])
{
  // redirect all VTK errors to stderr
  vtkConsoleOutputWindow::Install();

  int rval = 0;

  // for the optional query file
  QueryTagList qtlist;
  vtkDICOMItem query;

  // for the default character set
  vtkDICOMCharacterSet charset;

  if (argc < 2)
  {
    printUsage(stdout, fileBasename(argv[0]));
    return rval;
  }
  else if (argc == 2 && strcmp(argv[1], "--help") == 0)
  {
    printHelp(stdout, fileBasename(argv[0]));
    return rval;
  }
  else if (argc == 2 && strcmp(argv[1], "--version") == 0)
  {
    printVersion(stdout, fileBasename(argv[0]));
    return rval;
  }

  vtkSmartPointer<vtkStringArray> files =
    vtkSmartPointer<vtkStringArray>::New();

  for (int argi = 1; argi < argc; argi++)
  {
    const char *arg = argv[argi];
    if (strcmp(arg, "-q") == 0 || strcmp(arg, "-o") == 0)
    {
      if (argi + 1 == argc || argv[argi+1][0] == '-')
      {
        fprintf(stderr, "%s must be followed by a file.\n\n", arg);
        printUsage(stderr, fileBasename(argv[0]));
        return 1;
      }

      if (arg[1] == 'q')
      {
        const char *qfile = argv[++argi];
        if (!dicomcli_readquery(qfile, &query, &qtlist))
        {
          fprintf(stderr, "Can't read query file %s\n\n", qfile);
          return 1;
        }
      }
      else if (arg[1] == 'o')
      {
        fprintf(stderr, "unrecognized option %s.\n\n", arg);
        return 1;
      }
    }
    else if (strcmp(arg, "-k") == 0)
    {
      ++argi;
      if (argi == argc || argv[argi][0] == '-')
      {
        fprintf(stderr, "%s must be followed by gggg,eeee=value "
                        "where gggg,eeee is a DICOM tag.\n\n", arg);
        return 1;
      }
      if (!dicomcli_readkey(argv[argi], &query, &qtlist))
      {
        return 1;
      }
    }
    else if (strcmp(arg, "--charset") == 0)
    {
      ++argi;
      if (argi == argc || argv[argi][0] == '-')
      {
        fprintf(stderr, "%s must be followed by a valid character set\n\n",
                arg);
        return 1;
      }
      charset = vtkDICOMCharacterSet(argv[argi]);
      if (charset.GetKey() == vtkDICOMCharacterSet::Unknown)
      {
        fprintf(stderr, "%s %s is not a known character set\n\n",
                arg, argv[argi]);
        return 1;
      }
    }
    else if (arg[0] == '-')
    {
      fprintf(stderr, "unrecognized option %s.\n\n", arg);
      printUsage(stderr, fileBasename(argv[0]));
      return 1;
    }
    else
    {
      files->InsertNextValue(arg);
    }
  }

  // sort the files by study and series
  vtkSmartPointer<vtkDICOMDirectory> sorter =
    vtkSmartPointer<vtkDICOMDirectory>::New();
  sorter->RequirePixelDataOff();
  sorter->SetScanDepth(0);
  sorter->IgnoreDicomdirOn();
  sorter->SetFindQuery(query);
  sorter->SetInputFileNames(files);
  sorter->Update();

  vtkSmartPointer<vtkDICOMParser> parser =
    vtkSmartPointer<vtkDICOMParser>::New();
  parser->SetDefaultCharacterSet(charset);
  parser->SetQueryItem(query);

  vtkSmartPointer<vtkDICOMMetaData> data =
    vtkSmartPointer<vtkDICOMMetaData>::New();
  parser->SetMetaData(data);

  int m = sorter->GetNumberOfStudies();
  for (int j = 0; j < m; j++)
  {
    int k = sorter->GetFirstSeriesForStudy(j);
    int kl = sorter->GetLastSeriesForStudy(j);
    for (; k <= kl; k++)
    {
      vtkStringArray *a = sorter->GetFileNamesForSeries(k);
      vtkIdType l = a->GetNumberOfValues();
      std::string fname = a->GetValue(0);
      if (l == 1)
      {
        printf("==== %s ====\n", fname.c_str());
      }
      else
      {
        // print the first and last filenames (sorted)
        vtkSmartPointer<vtkSortFileNames> fsort =
          vtkSmartPointer<vtkSortFileNames>::New();
        fsort->NumericSortOn();
        fsort->IgnoreCaseOn();
        fsort->GroupingOff();
        fsort->SetInputFileNames(a);
        fsort->Update();
        printf("==== %s .. %s (%d files) ====\n",
          fsort->GetFileNames()->GetValue(0).c_str(),
          fileBasename(fsort->GetFileNames()->GetValue(l-1).c_str()),
          static_cast<int>(l));
      }

      data->Clear();
      data->SetNumberOfInstances(static_cast<int>(l));

      unsigned int pixelDataVL = 0;
      for (vtkIdType i = 0; i < l; i++)
      {
        fname = a->GetValue(i);
        parser->SetIndex(i);
        parser->SetFileName(fname.c_str());
        parser->Update();
        pixelDataVL = parser->GetPixelDataVL();
      }

      if (query.GetNumberOfDataElements() > 0)
      {
        for (size_t i = 0; i < qtlist.size(); i++)
        {
          printElementFromTagPath(data, qtlist[i], pixelDataVL);
        }
      }
      else
      {
        vtkDICOMDataElementIterator iter = data->Begin();
        vtkDICOMDataElementIterator iterEnd = data->End();

        for (; iter != iterEnd; ++iter)
        {
          printElement(data, nullptr, iter, 0, pixelDataVL);
        }
      }
    }
  }

  return rval;
}