ctkDICOMIndexer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QSqlQuery>
  16. #include <QSqlRecord>
  17. #include <QVariant>
  18. #include <QDate>
  19. #include <QStringList>
  20. #include <QSet>
  21. #include <QFile>
  22. #include <QDirIterator>
  23. #include <QFileInfo>
  24. #include <QDebug>
  25. #include <QPixmap>
  26. // ctkDICOM includes
  27. #include "ctkDICOMIndexer.h"
  28. #include "ctkDICOMAbstractThumbnailGenerator.h"
  29. // DCMTK includes
  30. #ifndef WIN32
  31. #define HAVE_CONFIG_H
  32. #endif
  33. #include <dcmtk/dcmdata/dcfilefo.h>
  34. #include <dcmtk/dcmdata/dcfilefo.h>
  35. #include <dcmtk/dcmdata/dcdeftag.h>
  36. #include <dcmtk/dcmdata/dcdatset.h>
  37. #include <dcmtk/ofstd/ofcond.h>
  38. #include <dcmtk/ofstd/ofstring.h>
  39. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  40. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  41. #include <dcmtk/dcmimgle/dcmimage.h> /* for class DicomImage */
  42. #include <dcmtk/dcmimage/diregist.h> /* include support for color images */
  43. #define MITK_ERROR std::cout
  44. #define MITK_INFO std::cout
  45. //------------------------------------------------------------------------------
  46. class ctkDICOMIndexerPrivate
  47. {
  48. public:
  49. ctkDICOMIndexerPrivate();
  50. ~ctkDICOMIndexerPrivate();
  51. ctkDICOMAbstractThumbnailGenerator* thumbnailGenerator;
  52. };
  53. //------------------------------------------------------------------------------
  54. // ctkDICOMIndexerPrivate methods
  55. //------------------------------------------------------------------------------
  56. ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate()
  57. {
  58. this->thumbnailGenerator = NULL;
  59. }
  60. //------------------------------------------------------------------------------
  61. ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate()
  62. {
  63. }
  64. //------------------------------------------------------------------------------
  65. //------------------------------------------------------------------------------
  66. // ctkDICOMIndexer methods
  67. //------------------------------------------------------------------------------
  68. ctkDICOMIndexer::ctkDICOMIndexer():d_ptr(new ctkDICOMIndexerPrivate)
  69. {
  70. }
  71. //------------------------------------------------------------------------------
  72. ctkDICOMIndexer::~ctkDICOMIndexer()
  73. {
  74. }
  75. //------------------------------------------------------------------------------
  76. void ctkDICOMIndexer::addDirectory(ctkDICOMDatabase& database,
  77. const QString& directoryName,
  78. const QString& destinationDirectoryName,
  79. bool createHierarchy,
  80. bool createThumbnails)
  81. {
  82. Q_D(ctkDICOMIndexer);
  83. QSqlDatabase db = database.database();
  84. const std::string src_directory(directoryName.toStdString());
  85. OFList<OFString> originalDcmtkFileNames;
  86. OFList<OFString> dcmtkFileNames;
  87. OFStandard::searchDirectoryRecursively( QDir::toNativeSeparators(src_directory.c_str()).toAscii().data(), originalDcmtkFileNames, "", "");
  88. // hack to reverse list of filenames (not neccessary when image loading works correctly)
  89. for ( OFListIterator(OFString) iter = originalDcmtkFileNames.begin(); iter != originalDcmtkFileNames.end(); ++iter )
  90. {
  91. dcmtkFileNames.push_front( *iter );
  92. }
  93. DcmFileFormat fileformat;
  94. DcmDataset *dataset;
  95. OFListIterator(OFString) iter = dcmtkFileNames.begin();
  96. OFListIterator(OFString) last = dcmtkFileNames.end();
  97. if(iter == last) return;
  98. QSqlQuery query(database.database());
  99. /// these are for optimizing the import of image sequences
  100. /// since most information are identical for all slices
  101. OFString lastPatientID = "";
  102. OFString lastPatientsName = "";
  103. OFString lastPatientsBirthDate = "";
  104. OFString lastStudyInstanceUID = "";
  105. OFString lastSeriesInstanceUID = "";
  106. int lastPatientUID = -1;
  107. /* iterate over all input filenames */
  108. while (iter != last)
  109. {
  110. std::string filename((*iter).c_str());
  111. QString qfilename(filename.c_str());
  112. /// first we check if the file is already in the database
  113. QSqlQuery fileExists(database.database());
  114. fileExists.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  115. fileExists.bindValue(0,qfilename);
  116. fileExists.exec();
  117. if (
  118. fileExists.next() &&
  119. QFileInfo(qfilename).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate)
  120. )
  121. {
  122. MITK_INFO << "File " << filename << " already added.";
  123. continue;
  124. }
  125. MITK_INFO << filename << "\n";
  126. OFCondition status = fileformat.loadFile(filename.c_str());
  127. ++iter;
  128. dataset = fileformat.getDataset();
  129. if (!status.good())
  130. {
  131. MITK_ERROR << "Could not load " << filename << "\nDCMTK says: " << status.text();
  132. continue;
  133. }
  134. OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex,
  135. patientComments, patientsAge;
  136. OFString studyInstanceUID, studyID, studyDate, studyTime,
  137. accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription;
  138. OFString seriesInstanceUID, seriesDate, seriesTime,
  139. seriesDescription, bodyPartExamined, frameOfReferenceUID,
  140. contrastAgent, scanningSequence;
  141. OFString instanceNumber, sopInstanceUID ;
  142. Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0;
  143. //The patient UID is a unique number within the database, generated by the sqlite autoincrement
  144. //Thus, this is _not_ the DICOM Patient ID.
  145. int patientUID = -1;
  146. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  147. if (!dataset->findAndGetOFString(DCM_PatientName, patientsName).good())
  148. {
  149. MITK_ERROR << "Could not read DCM_PatientName from " << filename;
  150. continue;
  151. }
  152. if (!dataset->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).good())
  153. {
  154. MITK_ERROR << "Could not read DCM_StudyInstanceUID from " << filename;
  155. continue;
  156. }
  157. if (!dataset->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).good())
  158. {
  159. MITK_ERROR << "Could not read DCM_SeriesInstanceUID from " << filename;
  160. continue;
  161. }
  162. if (!dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID).good())
  163. {
  164. MITK_ERROR << "Could not read DCM_SOPInstanceUID from " << filename;
  165. continue;
  166. }
  167. if (!dataset->findAndGetOFString(DCM_InstanceNumber, instanceNumber).good())
  168. {
  169. MITK_ERROR << "Could not read DCM_InstanceNumber from " << filename;
  170. continue;
  171. }
  172. dataset->findAndGetOFString(DCM_PatientID, patientID);
  173. dataset->findAndGetOFString(DCM_PatientBirthDate, patientsBirthDate);
  174. dataset->findAndGetOFString(DCM_PatientBirthTime, patientsBirthTime);
  175. dataset->findAndGetOFString(DCM_PatientSex, patientsSex);
  176. dataset->findAndGetOFString(DCM_PatientAge, patientsAge);
  177. dataset->findAndGetOFString(DCM_PatientComments, patientComments);
  178. dataset->findAndGetOFString(DCM_StudyID, studyID);
  179. dataset->findAndGetOFString(DCM_StudyDate, studyDate);
  180. dataset->findAndGetOFString(DCM_StudyTime, studyTime);
  181. dataset->findAndGetOFString(DCM_AccessionNumber, accessionNumber);
  182. dataset->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy);
  183. dataset->findAndGetOFString(DCM_InstitutionName, institutionName);
  184. dataset->findAndGetOFString(DCM_PerformingPhysicianName, performingPhysiciansName);
  185. dataset->findAndGetOFString(DCM_ReferringPhysicianName, referringPhysician);
  186. dataset->findAndGetOFString(DCM_StudyDescription, studyDescription);
  187. dataset->findAndGetOFString(DCM_SeriesDate, seriesDate);
  188. dataset->findAndGetOFString(DCM_SeriesTime, seriesTime);
  189. dataset->findAndGetOFString(DCM_SeriesDescription, seriesDescription);
  190. dataset->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined);
  191. dataset->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID);
  192. dataset->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent);
  193. dataset->findAndGetOFString(DCM_ScanningSequence, scanningSequence);
  194. dataset->findAndGetSint32(DCM_SeriesNumber, seriesNumber);
  195. dataset->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber);
  196. dataset->findAndGetSint32(DCM_EchoNumbers, echoNumber);
  197. dataset->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition);
  198. MITK_INFO << "Adding new items to database:";
  199. MITK_INFO << "studyID: " << studyID;
  200. MITK_INFO << "seriesInstanceUID: " << seriesInstanceUID;
  201. MITK_INFO << "Patient's Name: " << patientsName;
  202. //-----------------------
  203. //Add Patient to Database
  204. //-----------------------
  205. //Speed up: Check if patient is the same as in last file; very probable, as all images belonging to a study have the same patient
  206. bool patientExists = false;
  207. if(lastPatientID.compare(patientID) || lastPatientsBirthDate.compare(patientsBirthDate) || lastPatientsName.compare(patientsName))
  208. {
  209. //Check if patient is already present in the db
  210. QSqlQuery check_exists_query(database.database());
  211. std::stringstream check_exists_query_string;
  212. check_exists_query_string << "SELECT * FROM Patients WHERE PatientID = '" << patientID << "'";
  213. check_exists_query.exec(check_exists_query_string.str().c_str());
  214. /// we check only patients with the same PatientID
  215. /// PatientID is not unique in DICOM, so we also compare Name and BirthDate
  216. /// and assume this is sufficient
  217. while (check_exists_query.next())
  218. {
  219. if (
  220. check_exists_query.record().value("PatientsName").toString() == patientsName.c_str() &&
  221. check_exists_query.record().value("PatientsBirthDate").toString() == patientsBirthDate.c_str()
  222. )
  223. {
  224. /// found it
  225. patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
  226. patientExists = true;
  227. break;
  228. }
  229. }
  230. if(!patientExists)
  231. {
  232. std::stringstream query_string;
  233. query_string << "INSERT INTO Patients VALUES( NULL,'"
  234. << patientsName << "','"
  235. << patientID << "','"
  236. << patientsBirthDate << "','"
  237. << patientsBirthTime << "','"
  238. << patientsSex << "','"
  239. << patientsAge << "','"
  240. << patientComments << "')";
  241. query.exec(query_string.str().c_str());
  242. patientUID = query.lastInsertId().toInt();
  243. MITK_INFO << "New patient inserted: " << patientUID << "\n";
  244. }
  245. }
  246. else
  247. {
  248. patientUID = lastPatientUID;
  249. }
  250. /// keep this for the next image
  251. lastPatientUID = patientUID;
  252. lastPatientID = patientID;
  253. lastPatientsBirthDate = patientsBirthDate;
  254. lastPatientsName = patientsName;
  255. //---------------------
  256. //Add Study to Database
  257. //---------------------
  258. if(lastStudyInstanceUID.compare(studyInstanceUID))
  259. {
  260. QSqlQuery check_exists_query(database.database());
  261. std::stringstream check_exists_query_string;
  262. check_exists_query_string << "SELECT * FROM Studies WHERE StudyInstanceUID = '" << studyInstanceUID << "'";
  263. check_exists_query.exec(check_exists_query_string.str().c_str());
  264. if(!check_exists_query.next())
  265. {
  266. std::stringstream query_string;
  267. query_string << "INSERT INTO Studies VALUES('"
  268. << studyInstanceUID << "','"
  269. << patientUID << "','"
  270. << studyID << "','"
  271. << QDate::fromString(studyDate.c_str(), "yyyyMMdd").toString("yyyy-MM-dd").toStdString() << "','"
  272. << studyTime << "','"
  273. << accessionNumber << "','"
  274. << modalitiesInStudy << "','"
  275. << institutionName << "','"
  276. << referringPhysician << "','"
  277. << performingPhysiciansName << "','"
  278. << studyDescription << "')";
  279. query.exec(query_string.str().c_str());
  280. }
  281. }
  282. lastStudyInstanceUID = studyInstanceUID;
  283. //----------------------
  284. //Add Series to Database
  285. //----------------------
  286. if(lastSeriesInstanceUID.compare(seriesInstanceUID))
  287. {
  288. QSqlQuery check_exists_query(database.database());
  289. std::stringstream check_exists_query_string;
  290. check_exists_query_string << "SELECT * FROM Series WHERE SeriesInstanceUID = '" << seriesInstanceUID << "'";
  291. check_exists_query.exec(check_exists_query_string.str().c_str());
  292. if(!check_exists_query.next())
  293. {
  294. std::stringstream query_string;
  295. query_string << "INSERT INTO Series VALUES('"
  296. << seriesInstanceUID << "','"
  297. << studyInstanceUID << "','"
  298. << static_cast<int>(seriesNumber) << "','"
  299. << QDate::fromString(seriesDate.c_str(), "yyyyMMdd").toString("yyyy-MM-dd").toStdString() << "','"
  300. << seriesTime << "','"
  301. << seriesDescription << "','"
  302. << bodyPartExamined << "','"
  303. << frameOfReferenceUID << "','"
  304. << static_cast<int>(acquisitionNumber) << "','"
  305. << contrastAgent << "','"
  306. << scanningSequence << "','"
  307. << static_cast<int>(echoNumber) << "','"
  308. << static_cast<int>(temporalPosition) << "')";
  309. query.exec(query_string.str().c_str());
  310. }
  311. }
  312. lastSeriesInstanceUID = seriesInstanceUID;
  313. QString studySeriesDirectory = QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str();
  314. //----------------------------------
  315. //Move file to destination directory
  316. //----------------------------------
  317. if (!destinationDirectoryName.isEmpty())
  318. {
  319. QFile currentFile( qfilename );
  320. QDir destinationDir(destinationDirectoryName + "/dicom");
  321. QString destFileName = sopInstanceUID.c_str();
  322. if (createHierarchy)
  323. {
  324. destinationDir.mkpath(studySeriesDirectory);
  325. destFileName.prepend( destinationDir.absolutePath() + "/" + studySeriesDirectory + "/" );
  326. }
  327. currentFile.copy(destFileName);
  328. qfilename = destFileName;
  329. }
  330. if (createThumbnails)
  331. {
  332. if(d->thumbnailGenerator){
  333. QString thumbnailBaseDir = database.databaseDirectory() + "/thumbs/";
  334. QString thumbnailFilename = thumbnailBaseDir + "/" + database.pathForDataset(dataset) + ".png";
  335. QFileInfo thumbnailInfo(thumbnailFilename);
  336. if ( ! ( thumbnailInfo.exists() && thumbnailInfo.lastModified() < QFileInfo(qfilename).lastModified() ) )
  337. {
  338. QDir(thumbnailBaseDir).mkpath(studySeriesDirectory);
  339. DicomImage dcmtkImage(QDir::toNativeSeparators(qfilename).toStdString().c_str());
  340. d->thumbnailGenerator->generateThumbnail(&dcmtkImage, thumbnailFilename);
  341. }
  342. }
  343. }
  344. //------------------------
  345. //Add Filename to Database
  346. //------------------------
  347. // std::stringstream relativeFilePath;
  348. // relativeFilePath << seriesInstanceUID.c_str() << "/" << currentFilePath.getFileName();
  349. QSqlQuery check_exists_query(database.database());
  350. std::stringstream check_exists_query_string;
  351. // check_exists_query_string << "SELECT * FROM Images WHERE Filename = '" << relativeFilePath.str() << "'";
  352. check_exists_query_string << "SELECT * FROM Images WHERE SOPInstanceUID = '" << sopInstanceUID << "'";
  353. check_exists_query.exec(check_exists_query_string.str().c_str());
  354. if(!check_exists_query.next())
  355. {
  356. std::stringstream query_string;
  357. //To save absolute path: destDirectoryPath.str()
  358. query_string << "INSERT INTO Images VALUES('"
  359. << sopInstanceUID << "','" << qfilename.toStdString() << "','" << seriesInstanceUID << "','" << QDateTime::currentDateTime().toString(Qt::ISODate).toStdString() << "')";
  360. query.exec(query_string.str().c_str());
  361. }
  362. }
  363. // db.commit();
  364. // db.close();
  365. }
  366. //------------------------------------------------------------------------------
  367. void ctkDICOMIndexer::refreshDatabase(ctkDICOMDatabase& database, const QString& directoryName)
  368. {
  369. /// get all filenames from the database
  370. QSqlQuery allFilesQuery(database.database());
  371. QStringList databaseFileNames;
  372. QStringList filesToRemove;
  373. allFilesQuery.exec("SELECT Filename from Images;");
  374. while (allFilesQuery.next())
  375. {
  376. QString fileName = allFilesQuery.value(0).toString();
  377. databaseFileNames.append(fileName);
  378. if (! QFile::exists(fileName) )
  379. {
  380. filesToRemove.append(fileName);
  381. }
  382. }
  383. QSet<QString> filesytemFiles;
  384. QDirIterator dirIt(directoryName);
  385. while (dirIt.hasNext())
  386. {
  387. filesytemFiles.insert(dirIt.next());
  388. }
  389. }
  390. //------------------------------------------------------------------------------
  391. void ctkDICOMIndexer::setThumbnailGenerator(ctkDICOMAbstractThumbnailGenerator *generator){
  392. Q_D(ctkDICOMIndexer);
  393. d->thumbnailGenerator = generator;
  394. }
  395. //------------------------------------------------------------------------------
  396. ctkDICOMAbstractThumbnailGenerator* ctkDICOMIndexer::thumbnailGenerator(){
  397. Q_D(ctkDICOMIndexer);
  398. return d->thumbnailGenerator;
  399. }