ctkDICOMItem.cpp 32 KB

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