ctkDICOMDataset.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. bool m_TakeOwnership;
  28. DcmDataset* m_DcmDataset;
  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. // type 1 or 1C must exist AND have a value
  241. if (!dataset->tagExistsWithValue( tag ))
  242. {
  243. if (type == 0x1 || type == 0x1C) missing = true;
  244. }
  245. // type 2 or 2C must exist but may have an empty value
  246. if (!dataset->tagExists( tag ))
  247. {
  248. if (type == 0x1 || type == 0x1C) missing = true;
  249. if (type == 0x2 || type == 0x2C) missing = true;
  250. }
  251. else
  252. {
  253. // we found this tag
  254. DcmElement* element(NULL);
  255. dataset->findAndGetElement( tag, element, OFFalse, OFTrue ); // OFTrue is important (copies element), DcmDataset takes ownership and deletes elements on its own destruction
  256. if (element)
  257. {
  258. copied = CheckCondition( d->m_DcmDataset->insert(element) );
  259. }
  260. }
  261. if (missing)
  262. {
  263. std::cerr << "Tag " << TagKey(tag).toStdString() << " [" << TagDescription(tag).toStdString() << "] of type " << QString("%1").arg(type,0,16).toStdString() << " missing or empty." << std::endl;
  264. }
  265. if (!copied)
  266. {
  267. std::cerr << "Tag " << TagKey(tag).toStdString() << " [" << TagDescription(tag).toStdString() << "] not copied successfully" << std::endl;
  268. }
  269. return !missing && copied;
  270. }
  271. QString ctkDICOMDataset::Decode( const DcmTag& tag, const OFString& raw ) const
  272. {
  273. Q_D(const ctkDICOMDataset);
  274. // decode for types LO, LT, PN, SH, ST, UT
  275. QString vr = TagVR(tag);
  276. if ( !d->m_SpecificCharacterSet.isEmpty()
  277. && (vr == "LO" ||
  278. vr == "LT" ||
  279. vr == "PN" ||
  280. vr == "SH" ||
  281. vr == "ST" ||
  282. vr == "UT" ) )
  283. {
  284. //std::cout << "Decode from encoding " << d->m_SpecificCharacterSet.toStdString() << std::endl;
  285. static QMap<QString, QTextDecoder*> decoders;
  286. static QMap<QString, QString> qtEncodingNamesForDICOMEncodingNames;
  287. if (qtEncodingNamesForDICOMEncodingNames.isEmpty())
  288. {
  289. // runs only once and fills up a map of encoding names that might be named in DICOM files.
  290. // for each encoding we store the name that Qt uses for the same encoding.
  291. // This is because there is not yet a standard naming scheme but lots of aliases
  292. // out in the real world: e.g. http://www.openi18n.org/subgroups/sa/locnameguide/final/CodesetAliasTable.html
  293. // DICOM Qt
  294. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 192", "UTF-8");
  295. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 100", "ISO-8859-1");
  296. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 101", "ISO-8859-2");
  297. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 109", "ISO-8859-3");
  298. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 110", "ISO-8859-4");
  299. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 144", "ISO-8859-5");
  300. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 127", "ISO-8859-6");
  301. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 126", "ISO-8859-7");
  302. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 138", "ISO-8859-8");
  303. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 148", "ISO-8859-9");
  304. qtEncodingNamesForDICOMEncodingNames.insert("ISO_IR 179", "ISO-8859-13");
  305. qtEncodingNamesForDICOMEncodingNames.insert("ISO 2022 IR 13", "jisx0201*-0");
  306. // use all names that Qt knows by itself
  307. foreach( QByteArray c, QTextCodec::availableCodecs() )
  308. {
  309. qtEncodingNamesForDICOMEncodingNames.insert( c.constData(), c.constData() );
  310. }
  311. }
  312. if ( qtEncodingNamesForDICOMEncodingNames.contains(d->m_SpecificCharacterSet) )
  313. {
  314. QString encodingName( qtEncodingNamesForDICOMEncodingNames[d->m_SpecificCharacterSet] );
  315. if ( !decoders.contains( encodingName ) )
  316. {
  317. QTextCodec* codec = QTextCodec::codecForName( encodingName.toAscii() );
  318. if (!codec)
  319. {
  320. std::cerr << "Could not create QTextCodec object for '" << encodingName.toStdString() << "'. Using default encoding instead." << std::endl;
  321. decoders.insert( encodingName, QTextCodec::codecForCStrings()->makeDecoder() ); // uses Latin1
  322. }
  323. else
  324. {
  325. // initialize a QTextDecoder for given encoding
  326. decoders.insert( encodingName, codec->makeDecoder() );
  327. // We are responsible for deleting the QTextDecoder objects
  328. // created by makeDecoder(). BUT as these objects are stored
  329. // in a static map that lives until application end AND
  330. // nothing application relevant happens during their
  331. // destruction, we just let them be destructed by C++ on
  332. // application exit.
  333. // Any potential leaks that are found by this behavior can
  334. // be suppressed.
  335. }
  336. }
  337. //std::cout << "Decode '" << raw.c_str() << "' to '" << decoders[encodingName]->toUnicode( raw.c_str() ).toLocal8Bit().constData() << "'" << std::endl;
  338. return decoders[encodingName]->toUnicode( raw.c_str() );
  339. }
  340. else
  341. {
  342. std::cerr << "DICOM dataset contains some encoding that we never thought we would see(" << d->m_SpecificCharacterSet.toStdString() << "). Using default encoding." << std::endl;
  343. }
  344. }
  345. return QString::fromLatin1(raw.c_str()); // Latin1 is ISO 8859, which is the default character set of DICOM (PS 3.5-2008, Page 18)
  346. }
  347. OFString ctkDICOMDataset::Encode( const DcmTag& tag, const QString& qstring ) const
  348. {
  349. // TODO: respect given character-set when encoding; see Decode()
  350. Q_UNUSED(tag);
  351. return OFString( qstring.toLatin1().data() ); // Latin1 is ISO 8859, which is the default character set of DICOM (PS 3.5-2008, Page 18)
  352. }
  353. QString ctkDICOMDataset::GetAllElementValuesAsString( const DcmTag& tag ) const
  354. {
  355. this->EnsureDcmDataSetIsInitialized();
  356. QStringList qsl;
  357. DcmElement* element(NULL);
  358. findAndGetElement(tag, element);
  359. if (!element) return QString::null;
  360. const unsigned long count = element->getVM(); // value multiplicity
  361. for (unsigned long i = 0; i < count; ++i)
  362. {
  363. OFString s;
  364. if ( CheckCondition( const_cast<ctkDICOMDataset*>(this)->findAndGetOFString(tag, s, i) ) )
  365. {
  366. qsl << Decode( tag, s );
  367. }
  368. }
  369. return qsl.join("|");
  370. }
  371. QString ctkDICOMDataset::GetElementAsString( const DcmTag& tag, unsigned long pos ) const
  372. {
  373. this->EnsureDcmDataSetIsInitialized();
  374. OFString s;
  375. if ( CheckCondition( findAndGetOFString(tag, s, pos) ) )
  376. {
  377. return Decode( tag, s );
  378. }
  379. else
  380. {
  381. return QString::null;
  382. }
  383. }
  384. QStringList ctkDICOMDataset::GetElementAsStringList( const DcmTag& tag ) const
  385. {
  386. this->EnsureDcmDataSetIsInitialized();
  387. QStringList qsl;
  388. DcmElement* element(NULL);
  389. findAndGetElement(tag, element);
  390. if (!element) return qsl;
  391. const unsigned long count = element->getVM(); // value multiplicity
  392. for (unsigned long i = 0; i < count; ++i)
  393. {
  394. qsl << GetElementAsString(tag, i);
  395. }
  396. return qsl;
  397. }
  398. ctkDICOMPersonName ctkDICOMDataset::GetElementAsPersonName( const DcmTag& tag, unsigned long pos ) const
  399. {
  400. this->EnsureDcmDataSetIsInitialized();
  401. DcmElement* element(NULL);
  402. findAndGetElement(tag, element);
  403. DcmPersonName* name = dynamic_cast<DcmPersonName*>(element);
  404. if (!name) return ctkDICOMPersonName(); // invalid
  405. OFString lastName;
  406. OFString firstName;
  407. OFString middleName;
  408. OFString namePrefix;
  409. OFString nameSuffix;
  410. if (CheckCondition( name->getNameComponents(lastName, firstName, middleName, namePrefix, nameSuffix, pos) ) )
  411. {
  412. return ctkDICOMPersonName(
  413. Decode(tag, lastName),
  414. Decode(tag, firstName),
  415. Decode(tag, middleName),
  416. Decode(tag, namePrefix),
  417. Decode(tag, nameSuffix) );
  418. }
  419. else
  420. {
  421. return ctkDICOMPersonName();
  422. }
  423. }
  424. ctkDICOMPersonNameList ctkDICOMDataset::GetElementAsPersonNameList( const DcmTag& tag ) const
  425. {
  426. this->EnsureDcmDataSetIsInitialized();
  427. ctkDICOMPersonNameList qpnl;
  428. DcmElement* element(NULL);
  429. findAndGetElement(tag, element);
  430. if (!element) return qpnl;
  431. const unsigned long count = element->getVM(); // value multiplicity
  432. for (unsigned long i = 0; i < count; ++i)
  433. {
  434. qpnl << GetElementAsPersonName(tag, i);
  435. }
  436. return qpnl;
  437. }
  438. QDate ctkDICOMDataset::GetElementAsDate( const DcmTag& tag, unsigned long pos ) const
  439. {
  440. this->EnsureDcmDataSetIsInitialized();
  441. DcmElement* element(NULL);
  442. findAndGetElement(tag, element);
  443. DcmDate* date = dynamic_cast<DcmDate*>(element);
  444. if (!date) return QDate(); // invalid
  445. OFString ofs;
  446. if (CheckCondition( date->getISOFormattedDate(ofs, pos) ) )
  447. {
  448. QString qs(ofs.c_str());
  449. return QDate::fromString(qs, "yyyy-MM-dd");
  450. }
  451. else
  452. {
  453. return QDate();
  454. }
  455. }
  456. QTime ctkDICOMDataset::GetElementAsTime( const DcmTag& tag, unsigned long pos ) const
  457. {
  458. this->EnsureDcmDataSetIsInitialized();
  459. DcmElement* element(NULL);
  460. findAndGetElement(tag, element);
  461. DcmTime* time = dynamic_cast<DcmTime*>(element);
  462. if (!time) return QTime(); // invalid
  463. OFString ofs;
  464. if (CheckCondition( time->getISOFormattedTime(ofs, pos, OFTrue, OFFalse) ) ) // true (seconds), false (fraction of a second)
  465. {
  466. QString qs(ofs.c_str());
  467. return QTime::fromString(qs, "hh:mm:ss");
  468. }
  469. else
  470. {
  471. return QTime();
  472. }
  473. }
  474. QDateTime ctkDICOMDataset::GetElementAsDateTime( const DcmTag& tag, unsigned long pos ) const
  475. {
  476. this->EnsureDcmDataSetIsInitialized();
  477. DcmElement* element(NULL);
  478. findAndGetElement(tag, element);
  479. DcmDateTime* datetime = dynamic_cast<DcmDateTime*>(element);
  480. if (!datetime) return QDateTime(); // invalid
  481. OFString ofs;
  482. if (CheckCondition( datetime->getISOFormattedDateTime(ofs, pos, OFTrue, OFFalse, OFTrue) ) ) // true (seconds), false (fraction of a second), true (time zone)
  483. {
  484. QString qs(ofs.c_str());
  485. return QDateTime::fromString(qs, "dd-MM-yyy hh:mm:ss");
  486. }
  487. else
  488. {
  489. return QDateTime();
  490. }
  491. }
  492. double ctkDICOMDataset::GetElementAsDouble( const DcmTag& tag, unsigned long pos ) const
  493. {
  494. Q_D(const ctkDICOMDataset);
  495. this->EnsureDcmDataSetIsInitialized();
  496. DcmElement* element(NULL);
  497. findAndGetElement(tag, element);
  498. DcmDecimalString* ds = dynamic_cast<DcmDecimalString*>(element);
  499. if (!ds)
  500. {
  501. if (d->m_StrictErrorHandling)
  502. {
  503. throw std::logic_error("Element not found or not a decimal number");
  504. }
  505. else
  506. {
  507. return 0.0;
  508. }
  509. }
  510. Float64 dvalue;
  511. ds->getFloat64(dvalue, pos);
  512. return dvalue;
  513. }
  514. long ctkDICOMDataset::GetElementAsInteger( const DcmTag& tag, unsigned long pos ) const
  515. {
  516. Q_D(const ctkDICOMDataset);
  517. this->EnsureDcmDataSetIsInitialized();
  518. DcmElement* element(NULL);
  519. findAndGetElement(tag, element);
  520. DcmIntegerString* is = dynamic_cast<DcmIntegerString*>(element);
  521. if (!is)
  522. {
  523. if (d->m_StrictErrorHandling)
  524. {
  525. throw std::logic_error("Element not found or not an integer");
  526. }
  527. else
  528. {
  529. return 0;
  530. }
  531. }
  532. Sint32 i = 0;
  533. is->getSint32(i, pos);
  534. return i;
  535. }
  536. int ctkDICOMDataset::GetElementAsSignedShort( const DcmTag& tag, unsigned long pos ) const // type SS
  537. {
  538. this->EnsureDcmDataSetIsInitialized();
  539. DcmElement* element(NULL);
  540. findAndGetElement(tag, element);
  541. DcmSignedShort* ss = dynamic_cast<DcmSignedShort*>(element);
  542. if (!ss) throw std::logic_error("Element not found or not a signed short integer");
  543. Sint16 i;
  544. ss->getSint16(i, pos);
  545. return i;
  546. }
  547. int ctkDICOMDataset::GetElementAsUnsignedShort( const DcmTag& tag, unsigned long pos ) const // type US
  548. {
  549. this->EnsureDcmDataSetIsInitialized();
  550. DcmElement* element(NULL);
  551. findAndGetElement(tag, element);
  552. DcmUnsignedShort* us = dynamic_cast<DcmUnsignedShort*>(element);
  553. if (!us) throw std::logic_error("Element not found or not a unsigned short integer");
  554. Uint16 i;
  555. us->getUint16(i, pos);
  556. return i;
  557. }
  558. bool ctkDICOMDataset::SetElementAsString( const DcmTag& tag, QString string )
  559. {
  560. Q_D(ctkDICOMDataset);
  561. this->EnsureDcmDataSetIsInitialized();
  562. // TODO: Evaluate DICOM tag for proper encoding (see GetElementAsString())
  563. return CheckCondition( d->m_DcmDataset->putAndInsertString( tag, string.toLatin1().data() ) );
  564. }
  565. bool ctkDICOMDataset::SetElementAsStringList( const DcmTag& /*tag*/, QStringList /*stringList*/ )
  566. {
  567. this->EnsureDcmDataSetIsInitialized();
  568. // TODO: Find out how this can be implemented with DcmDataset methods; there is no method for
  569. // setting a string at a given position
  570. return false;
  571. }
  572. bool ctkDICOMDataset::SetElementAsPersonName( const DcmTag& tag, ctkDICOMPersonName personName )
  573. {
  574. Q_D(ctkDICOMDataset);
  575. this->EnsureDcmDataSetIsInitialized();
  576. DcmPersonName* dcmPersonName = new DcmPersonName( tag ); // TODO leak?
  577. if ( CheckCondition( dcmPersonName->putNameComponents(
  578. Encode( tag, personName.lastName() ),
  579. Encode( tag, personName.firstName() ),
  580. Encode( tag, personName.middleName() ),
  581. Encode( tag, personName.namePrefix() ),
  582. Encode( tag, personName.nameSuffix() ) ) ) )
  583. {
  584. return CheckCondition( d->m_DcmDataset->insert( dcmPersonName ) );
  585. }
  586. return false;
  587. }
  588. bool ctkDICOMDataset::SetElementAsPersonNameList( const DcmTag& tag, ctkDICOMPersonNameList personNameList )
  589. {
  590. Q_UNUSED(tag);
  591. Q_UNUSED(personNameList);
  592. this->EnsureDcmDataSetIsInitialized();
  593. // TODO: Find out how this can be implemented with DcmDataset methods; there is no method for
  594. // setting an element at a given position
  595. return false;
  596. }
  597. bool ctkDICOMDataset::SetElementAsDate( const DcmTag& tag, QDate date )
  598. {
  599. Q_D(ctkDICOMDataset);
  600. this->EnsureDcmDataSetIsInitialized();
  601. OFDate ofDate( date.year(), date.month(), date.day() );
  602. DcmDate* dcmDate = new DcmDate( tag ); // TODO leak?
  603. if ( CheckCondition( dcmDate->setOFDate( ofDate ) ) )
  604. {
  605. return CheckCondition( d->m_DcmDataset->insert( dcmDate ) );
  606. }
  607. return false;
  608. }
  609. bool ctkDICOMDataset::SetElementAsTime( const DcmTag& tag, QTime time )
  610. {
  611. Q_D(ctkDICOMDataset);
  612. this->EnsureDcmDataSetIsInitialized();
  613. OFTime ofTime( time.hour(), time.minute(), time.second() );
  614. DcmTime* dcmTime = new DcmTime( tag ); // TODO leak?
  615. if ( CheckCondition( dcmTime->setOFTime( ofTime ) ) )
  616. {
  617. return CheckCondition( d->m_DcmDataset->insert( dcmTime ) );
  618. }
  619. return false;
  620. }
  621. bool ctkDICOMDataset::SetElementAsDateTime( const DcmTag& tag, QDateTime dateTime )
  622. {
  623. Q_D(ctkDICOMDataset);
  624. this->EnsureDcmDataSetIsInitialized();
  625. QDate date = dateTime.date();
  626. QTime time = dateTime.time();
  627. OFDateTime ofDateTime;
  628. ofDateTime.setDateTime( date.year(), date.month(), date.day(), time.hour(), time.minute(), time.second() );
  629. DcmDateTime* dcmDateTime = new DcmDateTime( tag ); // TODO leak?
  630. if ( CheckCondition( dcmDateTime->setOFDateTime( ofDateTime ) ) )
  631. {
  632. return CheckCondition( d->m_DcmDataset->insert( dcmDateTime ) );
  633. }
  634. return false;
  635. }
  636. bool ctkDICOMDataset::SetElementAsInteger( const DcmTag& tag, long value, unsigned long pos )
  637. {
  638. Q_D(ctkDICOMDataset);
  639. this->EnsureDcmDataSetIsInitialized();
  640. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  641. return CheckCondition( d->m_DcmDataset->putAndInsertSint32( tag, value, pos ) );
  642. }
  643. bool ctkDICOMDataset::SetElementAsSignedShort( const DcmTag& tag, int value, unsigned long pos )
  644. {
  645. Q_D(ctkDICOMDataset);
  646. this->EnsureDcmDataSetIsInitialized();
  647. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  648. return CheckCondition( d->m_DcmDataset->putAndInsertSint16( tag, value, pos ) );
  649. }
  650. bool ctkDICOMDataset::SetElementAsUnsignedShort( const DcmTag& tag, int value, unsigned long pos )
  651. {
  652. Q_D(ctkDICOMDataset);
  653. this->EnsureDcmDataSetIsInitialized();
  654. //std::cerr << "TagVR: " << TagVR( tag ).toStdString() << std::endl;
  655. return CheckCondition( d->m_DcmDataset->putAndInsertUint16( tag, value, pos ) );
  656. }
  657. QString ctkDICOMDataset::GetStudyInstanceUID() const
  658. {
  659. return this->GetElementAsString(DCM_StudyInstanceUID);
  660. }
  661. QString ctkDICOMDataset::GetSeriesInstanceUID() const
  662. {
  663. return this->GetElementAsString(DCM_SeriesInstanceUID);
  664. }
  665. QString ctkDICOMDataset::GetSOPInstanceUID() const
  666. {
  667. return this->GetElementAsString(DCM_SOPInstanceUID);
  668. }
  669. QString ctkDICOMDataset::TranslateDefinedTermPatientPosition( const QString& dt )
  670. {
  671. static bool initialized = false;
  672. static QMap<QString, QString> descriptionOfTerms;
  673. if (!initialized)
  674. {
  675. descriptionOfTerms.insert("HFP", "Head First - Prone");
  676. descriptionOfTerms.insert("HFDR", "Head First - Decubitus Right");
  677. descriptionOfTerms.insert("FFDR", "Feet First - Decubitus Right");
  678. descriptionOfTerms.insert("FFP", "Feet First - Prone");
  679. descriptionOfTerms.insert("HFS", "Head First - Supine");
  680. descriptionOfTerms.insert("HFDL", "Head First - Decubitus Left");
  681. descriptionOfTerms.insert("FFDL", "Feet First - Decubitus Left");
  682. descriptionOfTerms.insert("FFS", "Feet First - Supine");
  683. initialized = true;
  684. }
  685. if ( descriptionOfTerms.contains( dt.toUpper() ) )
  686. {
  687. return descriptionOfTerms.value(dt.toUpper());
  688. }
  689. else
  690. {
  691. std::cerr << "Invalid enum for patient position" << std::endl;
  692. return QString::null;
  693. }
  694. }
  695. QString ctkDICOMDataset::TranslateDefinedTermModality( const QString& dt )
  696. {
  697. static bool initialized = false;
  698. static QMap<QString, QString> descriptionOfTerms;
  699. if (!initialized)
  700. {
  701. descriptionOfTerms.insert("CR", "Computed Radiography");
  702. descriptionOfTerms.insert("CT", "Computed Tomography");
  703. descriptionOfTerms.insert("MR", "Magnetic Resonance");
  704. descriptionOfTerms.insert("NM", "Nuclear Medicine");
  705. descriptionOfTerms.insert("US", "Ultrasound");
  706. descriptionOfTerms.insert("OT", "Other");
  707. descriptionOfTerms.insert("BI", "Biomagnetic imaging");
  708. descriptionOfTerms.insert("CD", "Color flow Doppler");
  709. descriptionOfTerms.insert("DD", "Duplex Doppler");
  710. descriptionOfTerms.insert("ES", "Endoscopy");
  711. descriptionOfTerms.insert("LS", "Laser surface scan");
  712. descriptionOfTerms.insert("PT", "Positron emission tomography (PET)");
  713. descriptionOfTerms.insert("RG", "Radiographic imaging (conventional film/screen)");
  714. descriptionOfTerms.insert("ST", "Single-photon emission computed tomograpy (SPECT)");
  715. descriptionOfTerms.insert("TG", "Thermography");
  716. descriptionOfTerms.insert("XA", "X-Ray Aniography");
  717. descriptionOfTerms.insert("RF", "Radio Fluoroscopy");
  718. descriptionOfTerms.insert("RTIMAGE", "Radiotherapy Image");
  719. descriptionOfTerms.insert("RTDOSE", "Radiotherapy Dose");
  720. descriptionOfTerms.insert("RTSTRUCT", "Radiotherapy Structure Set");
  721. descriptionOfTerms.insert("RTPLAN", "Radiotherapy Plan");
  722. descriptionOfTerms.insert("RTRECORD", "RT Treatment Record");
  723. descriptionOfTerms.insert("HC", "Hard Copy");
  724. descriptionOfTerms.insert("DX", "Digital Radiography");
  725. descriptionOfTerms.insert("MG", "Mammography");
  726. descriptionOfTerms.insert("IO", "Intra-oral Radiography");
  727. descriptionOfTerms.insert("PX", "Panoramic X-Ray");
  728. descriptionOfTerms.insert("GM", "General Microscopy");
  729. descriptionOfTerms.insert("SM", "Slide Microscopy");
  730. descriptionOfTerms.insert("XC", "External-camera Photography");
  731. descriptionOfTerms.insert("PR", "Presentation state");
  732. descriptionOfTerms.insert("AU", "Audio");
  733. descriptionOfTerms.insert("ECG", "Electrocardiography");
  734. descriptionOfTerms.insert("EPS", "Cardiac Electrophysiology");
  735. descriptionOfTerms.insert("HD", "Hemodynamic Waveform");
  736. descriptionOfTerms.insert("SR", "SR Document");
  737. descriptionOfTerms.insert("IVUS", "Intravascular Ultrasound");
  738. descriptionOfTerms.insert("OP", "Ophthalmic Photography");
  739. descriptionOfTerms.insert("SMR", "Stereometric Relationship");
  740. descriptionOfTerms.insert("OCT", "Optical Coherence Tomography (non-Ophthalmic)");
  741. descriptionOfTerms.insert("OPR", "Ophthalmic Refraction");
  742. descriptionOfTerms.insert("OPV", "Ophthalmic Visual Field");
  743. descriptionOfTerms.insert("OPM", "Ophthalmic Mapping");
  744. descriptionOfTerms.insert("KO", "Key Object Selection");
  745. descriptionOfTerms.insert("SEG", "Segmentation");
  746. descriptionOfTerms.insert("REG", "Registration");
  747. descriptionOfTerms.insert("OPT", "Ophthalmic Tomography");
  748. descriptionOfTerms.insert("BDUS", "Bone Densitometry (ultrasound)");
  749. descriptionOfTerms.insert("BMD", "Bone Densitometry (X-Ray)");
  750. descriptionOfTerms.insert("DOC", "Document");
  751. // retired terms (but probably still in use)
  752. descriptionOfTerms.insert("DS", "Digital Subtraction Angiography");
  753. descriptionOfTerms.insert("CF", "Cinefluorography");
  754. descriptionOfTerms.insert("DF", "Digital fluoroscopy");
  755. descriptionOfTerms.insert("VF", "Videofluorography");
  756. descriptionOfTerms.insert("AS", "Angioscopy");
  757. descriptionOfTerms.insert("CS", "Cystoscopy");
  758. descriptionOfTerms.insert("EC", "Echocardiography");
  759. descriptionOfTerms.insert("LP", "Laparoscopy");
  760. descriptionOfTerms.insert("FA", "Fluorescein angiography ");
  761. descriptionOfTerms.insert("CP", "Culposcopy");
  762. descriptionOfTerms.insert("DM", "Digital microscopy");
  763. descriptionOfTerms.insert("FS", "Fundoscopy");
  764. descriptionOfTerms.insert("MA", "Magnetic resonance angiography");
  765. descriptionOfTerms.insert("MS", "Magnetic resonance spectroscopy");
  766. initialized = true;
  767. }
  768. if ( descriptionOfTerms.contains( dt.toUpper() ) )
  769. {
  770. return descriptionOfTerms.value(dt.toUpper());
  771. }
  772. else
  773. {
  774. std::cerr << "Invalid enum for patient position" << std::endl;
  775. return QString::null;
  776. }
  777. }
  778. QString ctkDICOMDataset::TagKey( const DcmTag& tag )
  779. {
  780. return QString("(%1,%2)").arg( tag.getGroup(), 4, 16, QLatin1Char('0')).arg( tag.getElement(), 4, 16, QLatin1Char('0') );
  781. }
  782. QString ctkDICOMDataset::TagDescription( const DcmTag& tag )
  783. {
  784. if (!dcmDataDict.isDictionaryLoaded())
  785. return QString("<no DICOM dictionary loaded. application broken>");
  786. const DcmDataDictionary& globalDict = dcmDataDict.rdlock();
  787. const DcmDictEntry* entry = globalDict.findEntry(tag, NULL);
  788. QString returnName("Unknown");
  789. if (entry)
  790. {
  791. returnName = entry->getTagName();
  792. }
  793. dcmDataDict.unlock();
  794. return returnName;
  795. }
  796. QString ctkDICOMDataset::TagVR( const DcmTag& tag )
  797. {
  798. if (!dcmDataDict.isDictionaryLoaded()) return QString("<no DICOM dictionary loaded. application broken>");
  799. const DcmDataDictionary& globalDataDict = dcmDataDict.rdlock();
  800. const DcmDictEntry* entry = globalDataDict.findEntry(tag, NULL);
  801. QString returnVR("UN");
  802. if (entry)
  803. {
  804. returnVR = entry->getVR().getVRName();
  805. }
  806. dcmDataDict.unlock();
  807. return returnVR;
  808. }
  809. QString ctkDICOMDataset::GetStoredSerialization()
  810. {
  811. throw std::runtime_error("No serialization implemented for this object!");
  812. }
  813. void ctkDICOMDataset::SetStoredSerialization(QString serializedDataset)
  814. {
  815. Q_UNUSED(serializedDataset);
  816. throw std::runtime_error("No serialization implemented for this object!");
  817. }
  818. bool ctkDICOMDataset::SaveToFile(const QString& filePath) const
  819. {
  820. Q_D(const ctkDICOMDataset);
  821. DcmFileFormat* fileformat = new DcmFileFormat ( d->m_DcmDataset );
  822. OFCondition status = fileformat->saveFile ( QDir::toNativeSeparators( filePath).toAscii() );
  823. delete fileformat;
  824. return status.good();
  825. }