ctkDICOMDataset.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkDICOMDataset.h"
  16. #include <dctk.h>
  17. #include <dcostrmb.h>
  18. #include <dcistrmb.h>
  19. #include <stdexcept>
  20. class ctkDICOMDatasetPrivate
  21. {
  22. public:
  23. ctkDICOMDatasetPrivate() {}
  24. QString m_SpecificCharacterSet;
  25. bool m_DICOMDataSetInitialized;
  26. static const QScopedPointer<const DcmDataDictionary> s_Dictionary;
  27. DcmDataset* m_DcmDataset;
  28. };
  29. const QScopedPointer<const DcmDataDictionary> ctkDICOMDatasetPrivate::s_Dictionary(new DcmDataDictionary(OFTrue, OFTrue));
  30. // = QScopedPointer<const DcmDataDictionary>(new DcmDataDictionary(OFTrue, OFTrue));
  31. ctkDICOMDataset::ctkDICOMDataset()
  32. :d_ptr(new ctkDICOMDatasetPrivate)
  33. {
  34. Q_D(ctkDICOMDataset);
  35. d->m_DICOMDataSetInitialized = false;
  36. d->m_DcmDataset = this;
  37. }
  38. ctkDICOMDataset::~ctkDICOMDataset()
  39. {
  40. Q_D(ctkDICOMDataset);
  41. if(d->m_DcmDataset != this)
  42. {
  43. delete d->m_DcmDataset;
  44. }
  45. }
  46. void ctkDICOMDataset::InitializeFromDataset(DcmDataset* dataset)
  47. {
  48. Q_D(ctkDICOMDataset);
  49. if(d->m_DcmDataset != this)
  50. {
  51. delete d->m_DcmDataset;
  52. d->m_DcmDataset = NULL;
  53. }
  54. if (dataset)
  55. {
  56. d->m_DcmDataset=dataset;
  57. if (!d->m_DICOMDataSetInitialized)
  58. {
  59. d->m_DICOMDataSetInitialized = true;
  60. // remember "specific character set" tag for conversion of strings to the right encoding
  61. //std::cerr << "** " << (void*)this << " ctkDICOMDataset: Initialized DcmDataset" << std::endl;
  62. if ( CopyElement( dataset, DCM_SpecificCharacterSet, 3 ) )
  63. {
  64. OFString encoding;
  65. if ( CheckCondition( findAndGetOFString(DCM_SpecificCharacterSet, encoding) ) )
  66. {
  67. d->m_SpecificCharacterSet = encoding.c_str();
  68. }
  69. else
  70. {
  71. std::cerr << "Some implementation error in DCMTK. We put something into a box and now the box is empty. This is not ok." << std::endl;
  72. //throw std::logic_error("Some implementation error in DCMTK. We put something into a box and now the box is empty. This is not ok.");
  73. }
  74. }
  75. if (d->m_SpecificCharacterSet.isEmpty())
  76. {
  77. /**
  78. see Bug # 6458:
  79. There are cases, where different studies of the same person get encoded both with and without the SpecificCharacterSet attribute set.
  80. DICOM says: default is ASCII / ISO_IR 6 / ISO 646
  81. Since we experienced such mixed data, we supplement missing characterset information with the ISO_IR 100 / Latin1 character set.
  82. Since Latin1 is a superset of ASCII, this will not cause problems. PLUS in most cases (Europe) we will guess right and suppress
  83. "double patients" in applications.
  84. */
  85. SetElementAsString( DCM_SpecificCharacterSet, "ISO_IR 100" );
  86. }
  87. }
  88. }
  89. }
  90. void ctkDICOMDataset::InitializeFromFile(const QString& filename,
  91. const E_TransferSyntax readXfer,
  92. const E_GrpLenEncoding groupLength,
  93. const Uint32 maxReadLength,
  94. const E_FileReadMode readMode)
  95. {
  96. Q_UNUSED(maxReadLength);
  97. DcmDataset *dataset;
  98. DcmFileFormat fileformat;
  99. OFCondition status = fileformat.loadFile(filename.toAscii().data(), readXfer, groupLength, readMode);
  100. dataset = fileformat.getAndRemoveDataset();
  101. if (!status.good())
  102. {
  103. qDebug() << "Could not load " << filename << "\nDCMTK says: " << status.text();
  104. delete dataset;
  105. return;
  106. }
  107. InitializeFromDataset(dataset);
  108. }
  109. void ctkDICOMDataset::Serialize()
  110. {
  111. // store content of current DcmDataset (our parent) as QByteArray into m_ctkDICOMDataset
  112. Uint32 buffersize = 1024*1024; // reserve 1MB
  113. char* writebuffer = new char[buffersize];
  114. // write into buffer
  115. DcmOutputBufferStream dcmbuffer(writebuffer, buffersize);
  116. DcmDataset::transferInit();
  117. OFCondition condition = DcmDataset::write(dcmbuffer, EXS_LittleEndianImplicit, EET_UndefinedLength, NULL );
  118. DcmDataset::transferEnd();
  119. if ( condition.bad() )
  120. {
  121. std::cerr << "Could not DcmDataset::write(..): " << condition.text() << std::endl;
  122. }
  123. // get written contents of buffer
  124. offile_off_t datasetsize = 0;
  125. void* readbuffer = NULL;
  126. dcmbuffer.flushBuffer(readbuffer, datasetsize);
  127. //std::cerr << "** " << (void*)this << " ctkDICOMDataset: Serializing Dataset into " << datasetsize << " bytes" << std::endl;
  128. // construct Qt type from that contents
  129. QByteArray qtArray = QByteArray::fromRawData( static_cast<const char*>(readbuffer), datasetsize );
  130. //std::cerr << "** Buffer size: " << qtArray.size() << std::endl;
  131. QString stringbuffer = QString::fromAscii(qtArray.toBase64());
  132. //std::cerr << "** String of size " << stringbuffer.size() << " looks like this:\n" << stringbuffer.toStdString() << std::endl << std::endl;
  133. this->SetStoredSerialization( stringbuffer );
  134. delete[] writebuffer;
  135. }
  136. void ctkDICOMDataset::MarkForInitialization()
  137. {
  138. Q_D(ctkDICOMDataset);
  139. d->m_DICOMDataSetInitialized = false;
  140. }
  141. void ctkDICOMDataset::EnsureDcmDataSetIsInitialized() const
  142. {
  143. const_cast<ctkDICOMDataset*>(this)->Deserialize();
  144. }
  145. void ctkDICOMDataset::Deserialize()
  146. {
  147. Q_D(ctkDICOMDataset);
  148. // read attribute m_ctkDICOMDataset
  149. // construct a DcmDataset from it
  150. // calls InitializeData(DcmDataset*)
  151. // this method can be called both from sub-classes when they get the InitializeData signal from the persistence framework
  152. // and from EnsureDcmDataSetIsInitialized() when a GetElement.. or SetElement.. method is called.
  153. if (d->m_DICOMDataSetInitialized) return; // only need to do this once
  154. QString stringbuffer = this->GetStoredSerialization();
  155. if ( stringbuffer.isEmpty() )
  156. {
  157. d->m_DICOMDataSetInitialized = true;
  158. return; // TODO nicer: hold three states: newly created / loaded but not initialized / restored from DB
  159. }
  160. //std::cerr << "** " << (void*)this << " ctkDICOMDataset: Deserialize Dataset from string of size " << stringbuffer.size() << "\n" << stringbuffer.toStdString() << std::endl;
  161. QByteArray qtArray = QByteArray::fromBase64( stringbuffer.toAscii() );
  162. //std::cerr << "** " << (void*)this << " ctkDICOMDataset: Deserialize Dataset from byte array of size " << qtArray.size() << std::endl;
  163. DcmInputBufferStream dcmbuffer;
  164. dcmbuffer.setBuffer( qtArray.data(), qtArray.size() );
  165. //std::cerr << "** Buffer state: " << dcmbuffer.status().code() << " " << dcmbuffer.good() << " " << dcmbuffer.eos() << " tell " << dcmbuffer.tell() << " avail " << dcmbuffer.avail() << std::endl;
  166. DcmDataset dataset;
  167. dataset.transferInit();
  168. //std::cerr << "** Dataset state: " << dataset.transferState() << std::endl << std::endl;
  169. OFCondition condition = dataset.read( dcmbuffer, EXS_LittleEndianImplicit );
  170. dataset.transferEnd();
  171. // do this in all cases, even when reading reported an error
  172. this->InitializeFromDataset(&dataset);
  173. if ( condition.bad() )
  174. {
  175. std::cerr << "** Condition code of Dataset::read() is "
  176. << condition.code() << std::endl;
  177. std::cerr << "** Buffer state: " << dcmbuffer.status().code()
  178. << " " << dcmbuffer.good()
  179. << " " << dcmbuffer.eos()
  180. << " tell " << dcmbuffer.tell()
  181. << " avail " << dcmbuffer.avail() << std::endl;
  182. std::cerr << "** Dataset state: "
  183. << static_cast<int>(dataset.transferState()) << std::endl;
  184. std::cerr << "Could not DcmDataset::read(..): "
  185. << condition.text() << std::endl;
  186. //throw std::invalid_argument( std::string("Could not DcmDataset::read(..): ") + condition.text() );
  187. }
  188. }
  189. DcmDataset& ctkDICOMDataset::GetDcmDataset() const
  190. {
  191. const Q_D(ctkDICOMDataset);
  192. return *d->m_DcmDataset;
  193. }
  194. OFCondition ctkDICOMDataset::findAndGetElement(const DcmTag& tag, DcmElement*& element, const OFBool searchIntoSub) const
  195. {
  196. // this one const_cast allows us to declare quite a lot of methods nicely with const
  197. return GetDcmDataset().findAndGetElement(tag, element, searchIntoSub);
  198. }
  199. OFCondition ctkDICOMDataset::findAndGetOFString(const DcmTag& tag, OFString& value, const unsigned long pos, const OFBool searchIntoSub) const
  200. {
  201. // this second const_cast allows us to declare quite a lot of methods nicely with const
  202. return GetDcmDataset().findAndGetOFString(tag, value, pos, searchIntoSub);
  203. }
  204. bool ctkDICOMDataset::CheckCondition(const OFCondition& condition)
  205. {
  206. if ( condition.bad() )
  207. {
  208. //std::cerr << "Bad return code (" << condition.code() << "): " << condition.text() << std::endl;
  209. }
  210. return condition.good();
  211. }
  212. bool ctkDICOMDataset::CopyElement( DcmDataset* dataset, const DcmTagKey& tag, int type )
  213. {
  214. switch (type)
  215. {
  216. case 0x1:
  217. case 0x1C:
  218. case 0x2:
  219. case 0x2C:
  220. case 0x3:
  221. // these are ok
  222. break;
  223. default:
  224. // nothing else is ok
  225. std::cerr << "Unknown attribute type. Cannot process call to ExtractElement " << TagKey(tag).toStdString() << std::endl;
  226. return false;
  227. }
  228. bool missing(false);
  229. bool copied(true);
  230. if (!dataset) return false;
  231. // type 1 or 1C must exist AND have a value
  232. if (!dataset->tagExistsWithValue( tag ))
  233. {
  234. if (type == 0x1 || type == 0x1C) missing = true;
  235. }
  236. // type 2 or 2C must exist but may have an empty value
  237. if (!dataset->tagExists( tag ))
  238. {
  239. if (type == 0x1 || type == 0x1C) missing = true;
  240. if (type == 0x2 || type == 0x2C) missing = true;
  241. }
  242. else
  243. {
  244. // we found this tag
  245. DcmElement* element(NULL);
  246. dataset->findAndGetElement( tag, element, OFFalse, OFTrue ); // OFTrue is important (copies element), DcmDataset takes ownership and deletes elements on its own destruction
  247. if (element)
  248. {
  249. copied = CheckCondition( DcmDataset::insert(element) );
  250. }
  251. }
  252. if (missing)
  253. {
  254. std::cerr << "Tag " << TagKey(tag).toStdString() << " [" << TagDescription(tag).toStdString() << "] of type " << QString("%1").arg(type,0,16).toStdString() << " missing or empty." << std::endl;
  255. }
  256. if (!copied)
  257. {
  258. std::cerr << "Tag " << TagKey(tag).toStdString() << " [" << TagDescription(tag).toStdString() << "] not copied successfully" << std::endl;
  259. }
  260. return !missing && copied;
  261. }
  262. QString ctkDICOMDataset::Decode( const DcmTag& tag, const OFString& raw ) const
  263. {
  264. Q_D(const ctkDICOMDataset);
  265. // decode for types LO, LT, PN, SH, ST, UT
  266. QString vr = TagVR(tag);
  267. if ( !d->m_SpecificCharacterSet.isEmpty()
  268. && (vr == "LO" ||
  269. vr == "LT" ||
  270. vr == "PN" ||
  271. vr == "SH" ||
  272. vr == "ST" ||
  273. vr == "UT" ) )
  274. {
  275. //std::cout << "Decode from encoding " << d->m_SpecificCharacterSet.toStdString() << std::endl;
  276. static QMap<QString, QTextDecoder*> decoders;
  277. static QMap<QString, QString> qtEncodingNamesForDICOMEncodingNames;
  278. if (qtEncodingNamesForDICOMEncodingNames.isEmpty())
  279. {
  280. // runs only once and fills up a map of encoding names that might be named in DICOM files.
  281. // for each encoding we store the name that Qt uses for the same encoding.
  282. // This is because there is not yet a standard naming scheme but lots of aliases
  283. // out in the real world: e.g. http://www.openi18n.org/subgroups/sa/locnameguide/final/CodesetAliasTable.html
  284. // DICOM Qt
  285. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 192", "UTF-8");
  286. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 100", "ISO-8859-1");
  287. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 101", "ISO-8859-2");
  288. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 109", "ISO-8859-3");
  289. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 110", "ISO-8859-4");
  290. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 144", "ISO-8859-5");
  291. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 127", "ISO-8859-6");
  292. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 126", "ISO-8859-7");
  293. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 138", "ISO-8859-8");
  294. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 148", "ISO-8859-9");
  295. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 179", "ISO-8859-13");
  296. qtEncodingNamesForDICOMEncodingNames.insert("ISO 2022 IR 13", "jisx0201*-0");
  297. // use all names that Qt knows by itself
  298. foreach( QByteArray c, QTextCodec::availableCodecs() )
  299. {
  300. qtEncodingNamesForDICOMEncodingNames.insert( c.constData(), c.constData() );
  301. }
  302. }
  303. if ( qtEncodingNamesForDICOMEncodingNames.contains(d->m_SpecificCharacterSet) )
  304. {
  305. QString encodingName( qtEncodingNamesForDICOMEncodingNames[d->m_SpecificCharacterSet] );
  306. if ( !decoders.contains( encodingName ) )
  307. {
  308. QTextCodec* codec = QTextCodec::codecForName( encodingName.toAscii() );
  309. if (!codec)
  310. {
  311. std::cerr << "Could not create QTextCodec object for '" << encodingName.toStdString() << "'. Using default encoding instead." << std::endl;
  312. decoders.insert( encodingName, QTextCodec::codecForCStrings()->makeDecoder() ); // uses Latin1
  313. }
  314. else
  315. {
  316. // initialize a QTextDecoder for given encoding
  317. decoders.insert( encodingName, codec->makeDecoder() );
  318. // We are responsible for deleting the QTextDecoder objects
  319. // created by makeDecoder(). BUT as these objects are stored
  320. // in a static map that lives until application end AND
  321. // nothing application relevant happens during their
  322. // destruction, we just let them be destructed by C++ on
  323. // application exit.
  324. // Any potential leaks that are found by this behavior can
  325. // be suppressed.
  326. }
  327. }
  328. //std::cout << "Decode '" << raw.c_str() << "' to '" << decoders[encodingName]->toUnicode( raw.c_str() ).toLocal8Bit().constData() << "'" << std::endl;
  329. return decoders[encodingName]->toUnicode( raw.c_str() );
  330. }
  331. else
  332. {
  333. std::cerr << "DICOM dataset contains some encoding that we never thought we would see(" << d->m_SpecificCharacterSet.toStdString() << "). Using default encoding." << std::endl;
  334. }
  335. }
  336. return QString::fromLatin1(raw.c_str()); // Latin1 is ISO 8859, which is the default character set of DICOM (PS 3.5-2008, Page 18)
  337. }
  338. OFString ctkDICOMDataset::Encode( const DcmTag& tag, const QString& qstring ) const
  339. {
  340. // TODO: respect given character-set when encoding; see Decode()
  341. Q_UNUSED(tag);
  342. return OFString( qstring.toLatin1().data() ); // Latin1 is ISO 8859, which is the default character set of DICOM (PS 3.5-2008, Page 18)
  343. }
  344. QString ctkDICOMDataset::GetAllElementValuesAsString( const DcmTag& tag ) const
  345. {
  346. this->EnsureDcmDataSetIsInitialized();
  347. QStringList qsl;
  348. DcmElement* element(NULL);
  349. findAndGetElement(tag, element);
  350. if (!element) return QString::null;
  351. const unsigned long count = element->getVM(); // value multiplicity
  352. for (unsigned long i = 0; i < count; ++i)
  353. {
  354. OFString s;
  355. if ( CheckCondition( const_cast<ctkDICOMDataset*>(this)->findAndGetOFString(tag, s, i) ) )
  356. {
  357. qsl << Decode( tag, s );
  358. }
  359. }
  360. return qsl.join("|");
  361. }
  362. QString ctkDICOMDataset::GetElementAsString( const DcmTag& tag, unsigned long pos ) const
  363. {
  364. this->EnsureDcmDataSetIsInitialized();
  365. OFString s;
  366. if ( CheckCondition( findAndGetOFString(tag, s, pos) ) )
  367. {
  368. return Decode( tag, s );
  369. }
  370. else
  371. {
  372. return QString::null;
  373. }
  374. }
  375. QStringList ctkDICOMDataset::GetElementAsStringList( const DcmTag& tag ) const
  376. {
  377. this->EnsureDcmDataSetIsInitialized();
  378. QStringList qsl;
  379. DcmElement* element(NULL);
  380. findAndGetElement(tag, element);
  381. if (!element) return qsl;
  382. const unsigned long count = element->getVM(); // value multiplicity
  383. for (unsigned long i = 0; i < count; ++i)
  384. {
  385. qsl << GetElementAsString(tag, i);
  386. }
  387. return qsl;
  388. }
  389. ctkDICOMPersonName ctkDICOMDataset::GetElementAsPersonName( const DcmTag& tag, unsigned long pos ) const
  390. {
  391. this->EnsureDcmDataSetIsInitialized();
  392. DcmElement* element(NULL);
  393. findAndGetElement(tag, element);
  394. DcmPersonName* name = dynamic_cast<DcmPersonName*>(element);
  395. if (!name) return ctkDICOMPersonName(); // invalid
  396. OFString lastName;
  397. OFString firstName;
  398. OFString middleName;
  399. OFString namePrefix;
  400. OFString nameSuffix;
  401. if (CheckCondition( name->getNameComponents(lastName, firstName, middleName, namePrefix, nameSuffix, pos) ) )
  402. {
  403. return ctkDICOMPersonName(
  404. Decode(tag, lastName),
  405. Decode(tag, firstName),
  406. Decode(tag, middleName),
  407. Decode(tag, namePrefix),
  408. Decode(tag, nameSuffix) );
  409. }
  410. else
  411. {
  412. return ctkDICOMPersonName();
  413. }
  414. }
  415. ctkDICOMPersonNameList ctkDICOMDataset::GetElementAsPersonNameList( const DcmTag& tag ) const
  416. {
  417. this->EnsureDcmDataSetIsInitialized();
  418. ctkDICOMPersonNameList qpnl;
  419. DcmElement* element(NULL);
  420. findAndGetElement(tag, element);
  421. if (!element) return qpnl;
  422. const unsigned long count = element->getVM(); // value multiplicity
  423. for (unsigned long i = 0; i < count; ++i)
  424. {
  425. qpnl << GetElementAsPersonName(tag, i);
  426. }
  427. return qpnl;
  428. }
  429. QDate ctkDICOMDataset::GetElementAsDate( const DcmTag& tag, unsigned long pos ) const
  430. {
  431. this->EnsureDcmDataSetIsInitialized();
  432. DcmElement* element(NULL);
  433. findAndGetElement(tag, element);
  434. DcmDate* date = dynamic_cast<DcmDate*>(element);
  435. if (!date) return QDate(); // invalid
  436. OFString ofs;
  437. if (CheckCondition( date->getISOFormattedDate(ofs, pos) ) )
  438. {
  439. QString qs(ofs.c_str());
  440. return QDate::fromString(qs, "yyyy-MM-dd");
  441. }
  442. else
  443. {
  444. return QDate();
  445. }
  446. }
  447. QTime ctkDICOMDataset::GetElementAsTime( const DcmTag& tag, unsigned long pos ) const
  448. {
  449. this->EnsureDcmDataSetIsInitialized();
  450. DcmElement* element(NULL);
  451. findAndGetElement(tag, element);
  452. DcmTime* time = dynamic_cast<DcmTime*>(element);
  453. if (!time) return QTime(); // invalid
  454. OFString ofs;
  455. if (CheckCondition( time->getISOFormattedTime(ofs, pos, OFTrue, OFFalse) ) ) // true (seconds), false (fraction of a second)
  456. {
  457. QString qs(ofs.c_str());
  458. return QTime::fromString(qs, "hh:mm:ss");
  459. }
  460. else
  461. {
  462. return QTime();
  463. }
  464. }
  465. QDateTime ctkDICOMDataset::GetElementAsDateTime( const DcmTag& tag, unsigned long pos ) const
  466. {
  467. this->EnsureDcmDataSetIsInitialized();
  468. DcmElement* element(NULL);
  469. findAndGetElement(tag, element);
  470. DcmDateTime* datetime = dynamic_cast<DcmDateTime*>(element);
  471. if (!datetime) return QDateTime(); // invalid
  472. OFString ofs;
  473. if (CheckCondition( datetime->getISOFormattedDateTime(ofs, pos, OFTrue, OFFalse, OFTrue) ) ) // true (seconds), false (fraction of a second), true (time zone)
  474. {
  475. QString qs(ofs.c_str());
  476. return QDateTime::fromString(qs, "dd-MM-yyy hh:mm:ss");
  477. }
  478. else
  479. {
  480. return QDateTime();
  481. }
  482. }
  483. double ctkDICOMDataset::GetElementAsDouble( const DcmTag& tag, unsigned long pos ) const
  484. {
  485. this->EnsureDcmDataSetIsInitialized();
  486. DcmElement* element(NULL);
  487. findAndGetElement(tag, element);
  488. DcmDecimalString* ds = dynamic_cast<DcmDecimalString*>(element);
  489. if (!ds) throw std::logic_error("Element not found or not a decimal number");
  490. Float64 d;
  491. ds->getFloat64(d, pos);
  492. return d;
  493. }
  494. long ctkDICOMDataset::GetElementAsInteger( const DcmTag& tag, unsigned long pos ) const
  495. {
  496. this->EnsureDcmDataSetIsInitialized();
  497. DcmElement* element(NULL);
  498. findAndGetElement(tag, element);
  499. DcmIntegerString* is = dynamic_cast<DcmIntegerString*>(element);
  500. if (!is) throw std::logic_error("Element not found or not an integer");
  501. Sint32 i;
  502. is->getSint32(i, pos);
  503. return i;
  504. }
  505. int ctkDICOMDataset::GetElementAsSignedShort( const DcmTag& tag, unsigned long pos ) const // type SS
  506. {
  507. this->EnsureDcmDataSetIsInitialized();
  508. DcmElement* element(NULL);
  509. findAndGetElement(tag, element);
  510. DcmSignedShort* ss = dynamic_cast<DcmSignedShort*>(element);
  511. if (!ss) throw std::logic_error("Element not found or not a signed short integer");
  512. Sint16 i;
  513. ss->getSint16(i, pos);
  514. return i;
  515. }
  516. int ctkDICOMDataset::GetElementAsUnsignedShort( const DcmTag& tag, unsigned long pos ) const // type US
  517. {
  518. this->EnsureDcmDataSetIsInitialized();
  519. DcmElement* element(NULL);
  520. findAndGetElement(tag, element);
  521. DcmUnsignedShort* us = dynamic_cast<DcmUnsignedShort*>(element);
  522. if (!us) throw std::logic_error("Element not found or not a unsigned short integer");
  523. Uint16 i;
  524. us->getUint16(i, pos);
  525. return i;
  526. }
  527. bool ctkDICOMDataset::SetElementAsString( const DcmTag& tag, QString string )
  528. {
  529. this->EnsureDcmDataSetIsInitialized();
  530. // TODO: Evaluate DICOM tag for proper encoding (see GetElementAsString())
  531. return CheckCondition( putAndInsertString( tag, string.toLatin1().data() ) );
  532. }
  533. bool ctkDICOMDataset::SetElementAsStringList( const DcmTag& /*tag*/, QStringList /*stringList*/ )
  534. {
  535. this->EnsureDcmDataSetIsInitialized();
  536. // TODO: Find out how this can be implemented with DcmDataset methods; there is no method for
  537. // setting a string at a given position
  538. return false;
  539. }
  540. bool ctkDICOMDataset::SetElementAsPersonName( const DcmTag& tag, ctkDICOMPersonName personName )
  541. {
  542. this->EnsureDcmDataSetIsInitialized();
  543. DcmPersonName* dcmPersonName = new DcmPersonName( tag ); // TODO leak?
  544. if ( CheckCondition( dcmPersonName->putNameComponents(
  545. Encode( tag, personName.lastName() ),
  546. Encode( tag, personName.firstName() ),
  547. Encode( tag, personName.middleName() ),
  548. Encode( tag, personName.namePrefix() ),
  549. Encode( tag, personName.nameSuffix() ) ) ) )
  550. {
  551. return CheckCondition( insert( dcmPersonName ) );
  552. }
  553. return false;
  554. }
  555. bool ctkDICOMDataset::SetElementAsPersonNameList( const DcmTag& tag, ctkDICOMPersonNameList personNameList )
  556. {
  557. Q_UNUSED(tag);
  558. Q_UNUSED(personNameList);
  559. this->EnsureDcmDataSetIsInitialized();
  560. // TODO: Find out how this can be implemented with DcmDataset methods; there is no method for
  561. // setting an element at a given position
  562. return false;
  563. }
  564. bool ctkDICOMDataset::SetElementAsDate( const DcmTag& tag, QDate date )
  565. {
  566. this->EnsureDcmDataSetIsInitialized();
  567. OFDate ofDate( date.year(), date.month(), date.day() );
  568. DcmDate* dcmDate = new DcmDate( tag ); // TODO leak?
  569. if ( CheckCondition( dcmDate->setOFDate( ofDate ) ) )
  570. {
  571. return CheckCondition( insert( dcmDate ) );
  572. }
  573. return false;
  574. }
  575. bool ctkDICOMDataset::SetElementAsTime( const DcmTag& tag, QTime time )
  576. {
  577. this->EnsureDcmDataSetIsInitialized();
  578. OFTime ofTime( time.hour(), time.minute(), time.second() );
  579. DcmTime* dcmTime = new DcmTime( tag ); // TODO leak?
  580. if ( CheckCondition( dcmTime->setOFTime( ofTime ) ) )
  581. {
  582. return CheckCondition( insert( dcmTime ) );
  583. }
  584. return false;
  585. }
  586. bool ctkDICOMDataset::SetElementAsDateTime( const DcmTag& tag, QDateTime dateTime )
  587. {
  588. this->EnsureDcmDataSetIsInitialized();
  589. QDate date = dateTime.date();
  590. QTime time = dateTime.time();
  591. OFDateTime ofDateTime;
  592. ofDateTime.setDateTime( date.year(), date.month(), date.day(), time.hour(), time.minute(), time.second() );
  593. DcmDateTime* dcmDateTime = new DcmDateTime( tag ); // TODO leak?
  594. if ( CheckCondition( dcmDateTime->setOFDateTime( ofDateTime ) ) )
  595. {
  596. return CheckCondition( insert( dcmDateTime ) );
  597. }
  598. return false;
  599. }
  600. bool ctkDICOMDataset::SetElementAsInteger( const DcmTag& tag, long value, unsigned long pos )
  601. {
  602. this->EnsureDcmDataSetIsInitialized();
  603. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  604. return CheckCondition( putAndInsertSint32( tag, value, pos ) );
  605. }
  606. bool ctkDICOMDataset::SetElementAsSignedShort( const DcmTag& tag, int value, unsigned long pos )
  607. {
  608. this->EnsureDcmDataSetIsInitialized();
  609. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  610. return CheckCondition( putAndInsertSint16( tag, value, pos ) );
  611. }
  612. bool ctkDICOMDataset::SetElementAsUnsignedShort( const DcmTag& tag, int value, unsigned long pos )
  613. {
  614. this->EnsureDcmDataSetIsInitialized();
  615. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  616. return CheckCondition( putAndInsertUint16( tag, value, pos ) );
  617. }
  618. QString ctkDICOMDataset::TranslateDefinedTermPatientPosition( const QString& dt )
  619. {
  620. static bool initialized = false;
  621. static QMap<QString, QString> descriptionOfTerms;
  622. if (!initialized)
  623. {
  624. descriptionOfTerms.insert("HFP", "Head First - Prone");
  625. descriptionOfTerms.insert("HFDR", "Head First - Decubitus Right");
  626. descriptionOfTerms.insert("FFDR", "Feet First - Decubitus Right");
  627. descriptionOfTerms.insert("FFP", "Feet First - Prone");
  628. descriptionOfTerms.insert("HFS", "Head First - Supine");
  629. descriptionOfTerms.insert("HFDL", "Head First - Decubitus Left");
  630. descriptionOfTerms.insert("FFDL", "Feet First - Decubitus Left");
  631. descriptionOfTerms.insert("FFS", "Feet First - Supine");
  632. initialized = true;
  633. }
  634. if ( descriptionOfTerms.contains( dt.toUpper() ) )
  635. {
  636. return descriptionOfTerms.value(dt.toUpper());
  637. }
  638. else
  639. {
  640. std::cerr << "Invalid enum for patient position" << std::endl;
  641. return QString::null;
  642. }
  643. }
  644. QString ctkDICOMDataset::TranslateDefinedTermModality( const QString& dt )
  645. {
  646. static bool initialized = false;
  647. static QMap<QString, QString> descriptionOfTerms;
  648. if (!initialized)
  649. {
  650. descriptionOfTerms.insert("CR", "Computed Radiography");
  651. descriptionOfTerms.insert("CT", "Computed Tomography");
  652. descriptionOfTerms.insert("MR", "Magnetic Resonance");
  653. descriptionOfTerms.insert("NM", "Nuclear Medicine");
  654. descriptionOfTerms.insert("US", "Ultrasound");
  655. descriptionOfTerms.insert("OT", "Other");
  656. descriptionOfTerms.insert("BI", "Biomagnetic imaging");
  657. descriptionOfTerms.insert("CD", "Color flow Doppler");
  658. descriptionOfTerms.insert("DD", "Duplex Doppler");
  659. descriptionOfTerms.insert("ES", "Endoscopy");
  660. descriptionOfTerms.insert("LS", "Laser surface scan");
  661. descriptionOfTerms.insert("PT", "Positron emission tomography (PET)");
  662. descriptionOfTerms.insert("RG", "Radiographic imaging (conventional film/screen)");
  663. descriptionOfTerms.insert("ST", "Single-photon emission computed tomograpy (SPECT)");
  664. descriptionOfTerms.insert("TG", "Thermography");
  665. descriptionOfTerms.insert("XA", "X-Ray Aniography");
  666. descriptionOfTerms.insert("RF", "Radio Fluoroscopy");
  667. descriptionOfTerms.insert("RTIMAGE", "Radiotherapy Image");
  668. descriptionOfTerms.insert("RTDOSE", "Radiotherapy Dose");
  669. descriptionOfTerms.insert("RTSTRUCT", "Radiotherapy Structure Set");
  670. descriptionOfTerms.insert("RTPLAN", "Radiotherapy Plan");
  671. descriptionOfTerms.insert("RTRECORD", "RT Treatment Record");
  672. descriptionOfTerms.insert("HC", "Hard Copy");
  673. descriptionOfTerms.insert("DX", "Digital Radiography");
  674. descriptionOfTerms.insert("MG", "Mammography");
  675. descriptionOfTerms.insert("IO", "Intra-oral Radiography");
  676. descriptionOfTerms.insert("PX", "Panoramic X-Ray");
  677. descriptionOfTerms.insert("GM", "General Microscopy");
  678. descriptionOfTerms.insert("SM", "Slide Microscopy");
  679. descriptionOfTerms.insert("XC", "External-camera Photography");
  680. descriptionOfTerms.insert("PR", "Presentation state");
  681. descriptionOfTerms.insert("AU", "Audio");
  682. descriptionOfTerms.insert("ECG", "Electrocardiography");
  683. descriptionOfTerms.insert("EPS", "Cardiac Electrophysiology");
  684. descriptionOfTerms.insert("HD", "Hemodynamic Waveform");
  685. descriptionOfTerms.insert("SR", "SR Document");
  686. descriptionOfTerms.insert("IVUS", "Intravascular Ultrasound");
  687. descriptionOfTerms.insert("OP", "Ophthalmic Photography");
  688. descriptionOfTerms.insert("SMR", "Stereometric Relationship");
  689. descriptionOfTerms.insert("OCT", "Optical Coherence Tomography (non-Ophthalmic)");
  690. descriptionOfTerms.insert("OPR", "Ophthalmic Refraction");
  691. descriptionOfTerms.insert("OPV", "Ophthalmic Visual Field");
  692. descriptionOfTerms.insert("OPM", "Ophthalmic Mapping");
  693. descriptionOfTerms.insert("KO", "Key Object Selection");
  694. descriptionOfTerms.insert("SEG", "Segmentation");
  695. descriptionOfTerms.insert("REG", "Registration");
  696. descriptionOfTerms.insert("OPT", "Ophthalmic Tomography");
  697. descriptionOfTerms.insert("BDUS", "Bone Densitometry (ultrasound)");
  698. descriptionOfTerms.insert("BMD", "Bone Densitometry (X-Ray)");
  699. descriptionOfTerms.insert("DOC", "Document");
  700. // retired terms (but probably still in use)
  701. descriptionOfTerms.insert("DS", "Digital Subtraction Angiography");
  702. descriptionOfTerms.insert("CF", "Cinefluorography");
  703. descriptionOfTerms.insert("DF", "Digital fluoroscopy");
  704. descriptionOfTerms.insert("VF", "Videofluorography");
  705. descriptionOfTerms.insert("AS", "Angioscopy");
  706. descriptionOfTerms.insert("CS", "Cystoscopy");
  707. descriptionOfTerms.insert("EC", "Echocardiography");
  708. descriptionOfTerms.insert("LP", "Laparoscopy");
  709. descriptionOfTerms.insert("FA", "Fluorescein angiography ");
  710. descriptionOfTerms.insert("CP", "Culposcopy");
  711. descriptionOfTerms.insert("DM", "Digital microscopy");
  712. descriptionOfTerms.insert("FS", "Fundoscopy");
  713. descriptionOfTerms.insert("MA", "Magnetic resonance angiography");
  714. descriptionOfTerms.insert("MS", "Magnetic resonance spectroscopy");
  715. initialized = true;
  716. }
  717. if ( descriptionOfTerms.contains( dt.toUpper() ) )
  718. {
  719. return descriptionOfTerms.value(dt.toUpper());
  720. }
  721. else
  722. {
  723. std::cerr << "Invalid enum for patient position" << std::endl;
  724. return QString::null;
  725. }
  726. }
  727. QString ctkDICOMDataset::TagKey( const DcmTag& tag )
  728. {
  729. return QString("(%1,%2)").arg( tag.getGroup(), 4, 16, QLatin1Char('0')).arg( tag.getElement(), 4, 16, QLatin1Char('0') );
  730. }
  731. QString ctkDICOMDataset::TagDescription( const DcmTag& tag )
  732. {
  733. if (!ctkDICOMDatasetPrivate::s_Dictionary->isDictionaryLoaded()) return QString("<no DICOM dictionary loaded. application broken>");
  734. const DcmDictEntry* entry = ctkDICOMDatasetPrivate::s_Dictionary->findEntry(tag, NULL);
  735. if (entry)
  736. {
  737. return QString(entry->getTagName());
  738. }
  739. else
  740. {
  741. return QString("<unknown>");
  742. }
  743. }
  744. QString ctkDICOMDataset::TagVR( const DcmTag& tag )
  745. {
  746. if (!ctkDICOMDatasetPrivate::s_Dictionary->isDictionaryLoaded()) return QString("<no DICOM dictionary loaded. application broken>");
  747. const DcmDictEntry* entry = ctkDICOMDatasetPrivate::s_Dictionary->findEntry(tag, NULL);
  748. if (entry)
  749. {
  750. return QString(entry->getVR().getVRName());
  751. }
  752. else
  753. {
  754. return QString("UN"); // unknown
  755. }
  756. }
  757. QString ctkDICOMDataset::GetStoredSerialization()
  758. {
  759. throw std::runtime_error("No serialization implemented for this object!");
  760. }
  761. void ctkDICOMDataset::SetStoredSerialization(QString serializedDataset)
  762. {
  763. Q_UNUSED(serializedDataset);
  764. throw std::runtime_error("No serialization implemented for this object!");
  765. }