ctkDICOMDataset.cpp 32 KB

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