comparison PalantirServer/FromDcmtkBridge.cpp @ 0:3959d33612cc

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 19 Jul 2012 14:32:22 +0200
parents
children 67a6978503b7
comparison
equal deleted inserted replaced
-1:000000000000 0:3959d33612cc
1 /**
2 * Palantir - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012 Medical Physics Department, CHU of Liege,
4 * Belgium
5 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 **/
19
20
21 #include "FromDcmtkBridge.h"
22
23 #include "ToDcmtkBridge.h"
24 #include "DicomIntegerPixelAccessor.h"
25 #include "../Core/PalantirException.h"
26 #include "../Core/PngWriter.h"
27 #include "../Core/DicomFormat/DicomString.h"
28 #include "../Core/DicomFormat/DicomNullValue.h"
29
30 #include <boost/locale.hpp>
31 #include <boost/lexical_cast.hpp>
32
33 #include <dcmtk/dcmdata/dcdicent.h>
34 #include <dcmtk/dcmdata/dcdict.h>
35 #include <dcmtk/dcmdata/dcelem.h>
36 #include <dcmtk/dcmdata/dcfilefo.h>
37 #include <dcmtk/dcmdata/dcistrmb.h>
38 #include <dcmtk/dcmdata/dcsequen.h>
39 #include <dcmtk/dcmdata/dcvrfd.h>
40 #include <dcmtk/dcmdata/dcvrfl.h>
41 #include <dcmtk/dcmdata/dcvrsl.h>
42 #include <dcmtk/dcmdata/dcvrss.h>
43 #include <dcmtk/dcmdata/dcvrul.h>
44 #include <dcmtk/dcmdata/dcvrus.h>
45
46
47 namespace Palantir
48 {
49 void FromDcmtkBridge::Convert(DicomMap& target, DcmDataset& dataset)
50 {
51 target.Clear();
52 for (unsigned long i = 0; i < dataset.card(); i++)
53 {
54 DcmElement* element = dataset.getElement(i);
55 if (element && element->isLeaf())
56 {
57 target.SetValue(element->getTag().getGTag(),
58 element->getTag().getETag(),
59 ConvertLeafElement(*element));
60 }
61 }
62 }
63
64
65 DicomTag FromDcmtkBridge::GetTag(const DcmElement& element)
66 {
67 return DicomTag(element.getGTag(), element.getETag());
68 }
69
70
71 DicomValue* FromDcmtkBridge::ConvertLeafElement(DcmElement& element)
72 {
73 if (!element.isLeaf())
74 {
75 throw PalantirException("Only applicable to leaf elements");
76 }
77
78 if (element.isaString())
79 {
80 char *c;
81 if (element.getString(c).good() &&
82 c != NULL)
83 {
84 std::string s(c);
85 std::string utf8;
86 try
87 {
88 utf8 = boost::locale::conv::to_utf<char>(s, "ISO-8859-1"); // TODO Parameter?
89 }
90 catch (std::runtime_error& e)
91 {
92 // Bad input string or bad encoding
93 utf8 = s;
94 }
95
96 return new DicomString(utf8);
97 }
98 else
99 {
100 return new DicomNullValue;
101 }
102 }
103
104 try
105 {
106 // http://support.dcmtk.org/docs/dcvr_8h-source.html
107 switch (element.getVR())
108 {
109
110 /**
111 * TODO.
112 **/
113
114 case EVR_DS: // decimal string
115 case EVR_IS: // integer string
116 case EVR_OB: // other byte
117 case EVR_OF: // other float
118 case EVR_OW: // other word
119 case EVR_AS: // age string
120 case EVR_AT: // attribute tag
121 case EVR_DA: // date string
122 case EVR_DT: // date time string
123 case EVR_TM: // time string
124 case EVR_UN: // unknown value representation
125 return new DicomNullValue();
126
127
128 /**
129 * String types, should never happen at this point because of
130 * "element.isaString()".
131 **/
132
133 case EVR_AE: // application entity title
134 case EVR_CS: // code string
135 case EVR_SH: // short string
136 case EVR_LO: // long string
137 case EVR_ST: // short text
138 case EVR_LT: // long text
139 case EVR_UT: // unlimited text
140 case EVR_PN: // person name
141 case EVR_UI: // unique identifier
142 return new DicomNullValue();
143
144
145 /**
146 * Numerical types
147 **/
148
149 case EVR_SL: // signed long
150 {
151 Sint32 f;
152 if (dynamic_cast<DcmSignedLong&>(element).getSint32(f).good())
153 {
154 return new DicomString(boost::lexical_cast<std::string>(f));
155 }
156 else
157 {
158 return new DicomNullValue();
159 }
160 }
161
162 case EVR_SS: // signed short
163 {
164 Sint16 f;
165 if (dynamic_cast<DcmSignedShort&>(element).getSint16(f).good())
166 {
167 return new DicomString(boost::lexical_cast<std::string>(f));
168 }
169 else
170 {
171 return new DicomNullValue();
172 }
173 }
174
175 case EVR_UL: // unsigned long
176 {
177 Uint32 f;
178 if (dynamic_cast<DcmUnsignedLong&>(element).getUint32(f).good())
179 {
180 return new DicomString(boost::lexical_cast<std::string>(f));
181 }
182 else
183 {
184 return new DicomNullValue();
185 }
186 }
187
188 case EVR_US: // unsigned short
189 {
190 Uint16 f;
191 if (dynamic_cast<DcmUnsignedShort&>(element).getUint16(f).good())
192 {
193 return new DicomString(boost::lexical_cast<std::string>(f));
194 }
195 else
196 {
197 return new DicomNullValue();
198 }
199 }
200
201 case EVR_FL: // float single-precision
202 {
203 Float32 f;
204 if (dynamic_cast<DcmFloatingPointSingle&>(element).getFloat32(f).good())
205 {
206 return new DicomString(boost::lexical_cast<std::string>(f));
207 }
208 else
209 {
210 return new DicomNullValue();
211 }
212 }
213
214 case EVR_FD: // float double-precision
215 {
216 Float64 f;
217 if (dynamic_cast<DcmFloatingPointDouble&>(element).getFloat64(f).good())
218 {
219 return new DicomString(boost::lexical_cast<std::string>(f));
220 }
221 else
222 {
223 return new DicomNullValue();
224 }
225 }
226
227
228 /**
229 * Sequence types, should never occur at this point because of
230 * "element.isLeaf()".
231 **/
232
233 case EVR_SQ: // sequence of items
234 return new DicomNullValue;
235
236
237 /**
238 * Internal to DCMTK.
239 **/
240
241 case EVR_ox: // OB or OW depending on context
242 case EVR_xs: // SS or US depending on context
243 case EVR_lt: // US, SS or OW depending on context, used for LUT Data (thus the name)
244 case EVR_na: // na="not applicable", for data which has no VR
245 case EVR_up: // up="unsigned pointer", used internally for DICOMDIR suppor
246 case EVR_item: // used internally for items
247 case EVR_metainfo: // used internally for meta info datasets
248 case EVR_dataset: // used internally for datasets
249 case EVR_fileFormat: // used internally for DICOM files
250 case EVR_dicomDir: // used internally for DICOMDIR objects
251 case EVR_dirRecord: // used internally for DICOMDIR records
252 case EVR_pixelSQ: // used internally for pixel sequences in a compressed image
253 case EVR_pixelItem: // used internally for pixel items in a compressed image
254 case EVR_UNKNOWN: // used internally for elements with unknown VR (encoded with 4-byte length field in explicit VR)
255 case EVR_PixelData: // used internally for uncompressed pixeld data
256 case EVR_OverlayData: // used internally for overlay data
257 case EVR_UNKNOWN2B: // used internally for elements with unknown VR with 2-byte length field in explicit VR
258 return new DicomNullValue;
259
260
261 /**
262 * Default case.
263 **/
264
265 default:
266 return new DicomNullValue;
267 }
268 }
269 catch (boost::bad_lexical_cast)
270 {
271 return new DicomNullValue;
272 }
273 }
274
275
276 static void StoreElement(Json::Value& target,
277 DcmElement& element,
278 unsigned int maxStringLength);
279
280 static void StoreItem(Json::Value& target,
281 DcmItem& item,
282 unsigned int maxStringLength)
283 {
284 target = Json::Value(Json::objectValue);
285
286 for (unsigned long i = 0; i < item.card(); i++)
287 {
288 DcmElement* element = item.getElement(i);
289 StoreElement(target, *element, maxStringLength);
290 }
291 }
292
293
294 static void StoreElement(Json::Value& target,
295 DcmElement& element,
296 unsigned int maxStringLength)
297 {
298 assert(target.type() == Json::objectValue);
299
300 const std::string tagName = FromDcmtkBridge::GetName(FromDcmtkBridge::GetTag(element));
301
302 if (element.isLeaf())
303 {
304 std::auto_ptr<DicomValue> v(FromDcmtkBridge::ConvertLeafElement(element));
305 if (v->IsNull())
306 {
307 target[tagName] = Json::nullValue;
308 }
309 else
310 {
311 std::string s = v->AsString();
312 if (maxStringLength == 0 ||
313 s.size() <= maxStringLength)
314 {
315 target[tagName] = s;
316 }
317 else
318 {
319 // An integer value of 0 in JSON indicates too long field
320 target[tagName] = 0;
321 }
322 }
323 }
324 else
325 {
326 target[tagName] = Json::Value(Json::arrayValue);
327
328 // "All subclasses of DcmElement except for DcmSequenceOfItems
329 // are leaf nodes, while DcmSequenceOfItems, DcmItem, DcmDataset
330 // etc. are not." The following cast is thus OK.
331 DcmSequenceOfItems& sequence = dynamic_cast<DcmSequenceOfItems&>(element);
332
333 for (unsigned long i = 0; i < sequence.card(); i++)
334 {
335 DcmItem* child = sequence.getItem(i);
336 Json::Value& v = target[tagName].append(Json::objectValue);
337 StoreItem(v, *child, maxStringLength);
338 }
339 }
340 }
341
342
343 void FromDcmtkBridge::ToJson(Json::Value& root,
344 DcmDataset& dataset,
345 unsigned int maxStringLength)
346 {
347 StoreItem(root, dataset, maxStringLength);
348 }
349
350
351
352 void FromDcmtkBridge::ToJson(Json::Value& target,
353 const std::string& path,
354 unsigned int maxStringLength)
355 {
356 DcmFileFormat dicom;
357 if (!dicom.loadFile(path.c_str()).good())
358 {
359 throw PalantirException(ErrorCode_BadFileFormat);
360 }
361 else
362 {
363 FromDcmtkBridge::ToJson(target, *dicom.getDataset(), maxStringLength);
364 }
365 }
366
367
368 void FromDcmtkBridge::ExtractNormalizedImage(std::string& result,
369 DcmDataset& dataset)
370 {
371 // See also: http://support.dcmtk.org/wiki/dcmtk/howto/accessing-compressed-data
372
373 PngWriter w;
374 std::auto_ptr<DicomIntegerPixelAccessor> accessor;
375
376 DicomMap m;
377 FromDcmtkBridge::Convert(m, dataset);
378
379 DcmElement* e;
380 if (dataset.findAndGetElement(ToDcmtkBridge::Convert(DicomTag::PIXEL_DATA), e).good() &&
381 e != NULL)
382 {
383 Uint8* pixData = NULL;
384 if (e->getUint8Array(pixData) == EC_Normal)
385 {
386 accessor.reset(new DicomIntegerPixelAccessor(m, pixData, e->getLength()));
387 }
388 }
389
390 if (accessor.get() == NULL ||
391 accessor->GetWidth() == 0 ||
392 accessor->GetHeight() == 0)
393 {
394 w.WriteToMemory(result, 0, 0, 0, PixelFormat_Grayscale8, NULL);
395 }
396 else
397 {
398 int32_t min, max;
399 accessor->GetExtremeValues(min, max);
400
401 std::vector<uint8_t> image(accessor->GetWidth() * accessor->GetHeight(), 0);
402 if (min != max)
403 {
404 uint8_t* result = &image[0];
405 for (unsigned int y = 0; y < accessor->GetHeight(); y++)
406 {
407 for (unsigned int x = 0; x < accessor->GetWidth(); x++, result++)
408 {
409 int32_t v = accessor->GetValue(x, y);
410 *result = lround(static_cast<float>(v - min) / static_cast<float>(max - min) * 255.0f);
411 }
412 }
413 }
414
415 w.WriteToMemory(result, accessor->GetWidth(), accessor->GetHeight(),
416 accessor->GetWidth(), PixelFormat_Grayscale8, &image[0]);
417 }
418 }
419
420
421 void FromDcmtkBridge::ExtractNormalizedImage(std::string& result,
422 const std::string& dicomContent)
423 {
424 DcmInputBufferStream is;
425 if (dicomContent.size() > 0)
426 {
427 is.setBuffer(&dicomContent[0], dicomContent.size());
428 }
429 is.setEos();
430
431 DcmFileFormat dicom;
432 if (dicom.read(is).good())
433 {
434 ExtractNormalizedImage(result, *dicom.getDataset());
435 }
436 else
437 {
438 throw PalantirException(ErrorCode_BadFileFormat);
439 }
440 }
441
442
443
444 std::string FromDcmtkBridge::GetName(const DicomTag& t)
445 {
446 DcmTagKey tag(t.GetGroup(), t.GetElement());
447 const DcmDataDictionary& dict = dcmDataDict.rdlock();
448 const DcmDictEntry* entry = dict.findEntry(tag, NULL);
449
450 std::string s("Unknown");
451 if (entry != NULL)
452 {
453 s = std::string(entry->getTagName());
454 }
455
456 dcmDataDict.unlock();
457 return s;
458 }
459
460
461 DicomTag FromDcmtkBridge::FindTag(const char* name)
462 {
463 const DcmDataDictionary& dict = dcmDataDict.rdlock();
464 const DcmDictEntry* entry = dict.findEntry(name);
465
466 if (entry == NULL)
467 {
468 dcmDataDict.unlock();
469 throw PalantirException("Unknown DICOM tag");
470 }
471 else
472 {
473 DcmTagKey key = entry->getKey();
474 DicomTag tag(key.getGroup(), key.getElement());
475 dcmDataDict.unlock();
476 return tag;
477 }
478 }
479
480
481 void FromDcmtkBridge::Print(FILE* fp, const DicomMap& m)
482 {
483 for (DicomMap::Map::const_iterator
484 it = m.map_.begin(); it != m.map_.end(); it++)
485 {
486 DicomTag t = it->first;
487 std::string s = it->second->AsString();
488 printf("0x%04x 0x%04x (%s) [%s]\n", t.GetGroup(), t.GetElement(), GetName(t).c_str(), s.c_str());
489 }
490 }
491
492
493 void FromDcmtkBridge::ToJson(Json::Value& result,
494 const DicomMap& values)
495 {
496 if (result.type() != Json::objectValue)
497 {
498 throw PalantirException(ErrorCode_BadParameterType);
499 }
500
501 result.clear();
502
503 for (DicomMap::Map::const_iterator
504 it = values.map_.begin(); it != values.map_.end(); it++)
505 {
506 result[GetName(it->first)] = it->second->AsString();
507 }
508 }
509 }