ctkDICOMIndexer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) 2010 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.commontk.org/LICENSE
  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. // ctkDICOM includes
  26. #include "ctkDICOMIndexer.h"
  27. // DCMTK includes
  28. #ifndef WIN32
  29. #define HAVE_CONFIG_H
  30. #endif
  31. #include <dcmtk/dcmdata/dcfilefo.h>
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcdeftag.h>
  34. #include <dcmtk/dcmdata/dcdatset.h>
  35. #include <dcmtk/ofstd/ofcond.h>
  36. #include <dcmtk/ofstd/ofstring.h>
  37. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  38. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  39. #define MITK_ERROR std::cout
  40. #define MITK_INFO std::cout
  41. //------------------------------------------------------------------------------
  42. class ctkDICOMIndexerPrivate: public ctkPrivate<ctkDICOMIndexer>
  43. {
  44. public:
  45. ctkDICOMIndexerPrivate();
  46. ~ctkDICOMIndexerPrivate();
  47. };
  48. //------------------------------------------------------------------------------
  49. // ctkDICOMIndexerPrivate methods
  50. //------------------------------------------------------------------------------
  51. ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate()
  52. {
  53. }
  54. //------------------------------------------------------------------------------
  55. ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate()
  56. {
  57. }
  58. //------------------------------------------------------------------------------
  59. // ctkDICOMIndexer methods
  60. //------------------------------------------------------------------------------
  61. ctkDICOMIndexer::ctkDICOMIndexer()
  62. {
  63. }
  64. //------------------------------------------------------------------------------
  65. ctkDICOMIndexer::~ctkDICOMIndexer()
  66. {
  67. }
  68. //------------------------------------------------------------------------------
  69. void ctkDICOMIndexer::addDirectory(QSqlDatabase database, const QString& directoryName,const QString& destinationDirectoryName)
  70. {
  71. QSqlDatabase db = database;
  72. const std::string src_directory(directoryName.toStdString());
  73. OFList<OFString> originalDcmtkFileNames;
  74. OFList<OFString> dcmtkFileNames;
  75. OFStandard::searchDirectoryRecursively( src_directory.c_str(), originalDcmtkFileNames, "", "");
  76. // hack to reverse list of filenames (not neccessary when image loading works correctly)
  77. for ( OFListIterator(OFString) iter = originalDcmtkFileNames.begin(); iter != originalDcmtkFileNames.end(); ++iter )
  78. {
  79. dcmtkFileNames.push_front( *iter );
  80. }
  81. DcmFileFormat fileformat;
  82. OFListIterator(OFString) iter = dcmtkFileNames.begin();
  83. OFListIterator(OFString) last = dcmtkFileNames.end();
  84. if(iter == last) return;
  85. QSqlQuery query(database);
  86. /// these are for optimizing the import of image sequences
  87. /// since most information are identical for all slices
  88. OFString lastPatientID = "";
  89. OFString lastPatientsName = "";
  90. OFString lastPatientsBirthDate = "";
  91. OFString lastStudyInstanceUID = "";
  92. OFString lastSeriesInstanceUID = "";
  93. int lastPatientUID = -1;
  94. /* iterate over all input filenames */
  95. while (iter != last)
  96. {
  97. std::string filename((*iter).c_str());
  98. QString qfilename(filename.c_str());
  99. /// first we check if the file is already in the database
  100. QSqlQuery fileExists(database);
  101. fileExists.prepare("SELECT InsertTimestamp FROM Images WHERE Filename == ?");
  102. fileExists.bindValue(0,qfilename);
  103. fileExists.exec();
  104. if (
  105. fileExists.next() &&
  106. QFileInfo(qfilename).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate)
  107. )
  108. {
  109. MITK_INFO << "File " << filename << " already added.";
  110. continue;
  111. }
  112. MITK_INFO << filename << "\n";
  113. OFCondition status = fileformat.loadFile(filename.c_str());
  114. ++iter;
  115. if (!status.good())
  116. {
  117. MITK_ERROR << "Could not load " << filename << "\nDCMTK says: " << status.text();
  118. continue;
  119. }
  120. OFString patientsName, patientID, patientsBirthDate, patientsBirthTime, patientsSex,
  121. patientComments, patientsAge;
  122. OFString studyInstanceUID, studyID, studyDate, studyTime,
  123. accessionNumber, modalitiesInStudy, institutionName, performingPhysiciansName, referringPhysician, studyDescription;
  124. OFString seriesInstanceUID, seriesDate, seriesTime,
  125. seriesDescription, bodyPartExamined, frameOfReferenceUID,
  126. contrastAgent, scanningSequence;
  127. OFString instanceNumber;
  128. Sint32 seriesNumber = 0, acquisitionNumber = 0, echoNumber = 0, temporalPosition = 0;
  129. //The patient UID is a unique number within the database, generated by the sqlite autoincrement
  130. int patientUID = -1;
  131. //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  132. if (!fileformat.getDataset()->findAndGetOFString(DCM_PatientsName, patientsName).good())
  133. {
  134. MITK_ERROR << "Could not read DCM_PatientsName from " << filename;
  135. continue;
  136. }
  137. if (!fileformat.getDataset()->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).good())
  138. {
  139. MITK_ERROR << "Could not read DCM_StudyInstanceUID from " << filename;
  140. continue;
  141. }
  142. if (!fileformat.getDataset()->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).good())
  143. {
  144. MITK_ERROR << "Could not read DCM_SeriesInstanceUID from " << filename;
  145. continue;
  146. }
  147. if (!fileformat.getDataset()->findAndGetOFString(DCM_InstanceNumber, instanceNumber).good())
  148. {
  149. MITK_ERROR << "Could not read DCM_InstanceNumber from " << filename;
  150. continue;
  151. }
  152. fileformat.getDataset()->findAndGetOFString(DCM_PatientID, patientID);
  153. fileformat.getDataset()->findAndGetOFString(DCM_PatientsBirthDate, patientsBirthDate);
  154. fileformat.getDataset()->findAndGetOFString(DCM_PatientsBirthTime, patientsBirthTime);
  155. fileformat.getDataset()->findAndGetOFString(DCM_PatientsSex, patientsSex);
  156. fileformat.getDataset()->findAndGetOFString(DCM_PatientsAge, patientsAge);
  157. fileformat.getDataset()->findAndGetOFString(DCM_PatientComments, patientComments);
  158. fileformat.getDataset()->findAndGetOFString(DCM_StudyID, studyID);
  159. fileformat.getDataset()->findAndGetOFString(DCM_StudyDate, studyDate);
  160. fileformat.getDataset()->findAndGetOFString(DCM_StudyTime, studyTime);
  161. fileformat.getDataset()->findAndGetOFString(DCM_AccessionNumber, accessionNumber);
  162. fileformat.getDataset()->findAndGetOFString(DCM_ModalitiesInStudy, modalitiesInStudy);
  163. fileformat.getDataset()->findAndGetOFString(DCM_InstitutionName, institutionName);
  164. fileformat.getDataset()->findAndGetOFString(DCM_PerformingPhysiciansName, performingPhysiciansName);
  165. fileformat.getDataset()->findAndGetOFString(DCM_ReferringPhysiciansName, referringPhysician);
  166. fileformat.getDataset()->findAndGetOFString(DCM_StudyDescription, studyDescription);
  167. fileformat.getDataset()->findAndGetOFString(DCM_SeriesDate, seriesDate);
  168. fileformat.getDataset()->findAndGetOFString(DCM_SeriesTime, seriesTime);
  169. fileformat.getDataset()->findAndGetOFString(DCM_SeriesDescription, seriesDescription);
  170. fileformat.getDataset()->findAndGetOFString(DCM_BodyPartExamined, bodyPartExamined);
  171. fileformat.getDataset()->findAndGetOFString(DCM_FrameOfReferenceUID, frameOfReferenceUID);
  172. fileformat.getDataset()->findAndGetOFString(DCM_ContrastBolusAgent, contrastAgent);
  173. fileformat.getDataset()->findAndGetOFString(DCM_ScanningSequence, scanningSequence);
  174. fileformat.getDataset()->findAndGetSint32(DCM_SeriesNumber, seriesNumber);
  175. fileformat.getDataset()->findAndGetSint32(DCM_AcquisitionNumber, acquisitionNumber);
  176. fileformat.getDataset()->findAndGetSint32(DCM_EchoNumbers, echoNumber);
  177. fileformat.getDataset()->findAndGetSint32(DCM_TemporalPositionIdentifier, temporalPosition);
  178. MITK_INFO << "Adding new items to database:";
  179. MITK_INFO << "studyID: " << studyID;
  180. MITK_INFO << "seriesInstanceUID: " << seriesInstanceUID;
  181. MITK_INFO << "Patient's Name: " << patientsName;
  182. //-----------------------
  183. //Add Patient to Database
  184. //-----------------------
  185. //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
  186. bool patientExists = false;
  187. if(lastPatientID.compare(patientID) || lastPatientsBirthDate.compare(patientsBirthDate) || lastPatientsName.compare(patientsName))
  188. {
  189. //Check if patient is already present in the db
  190. QSqlQuery check_exists_query(database);
  191. std::stringstream check_exists_query_string;
  192. check_exists_query_string << "SELECT * FROM Patients WHERE PatientID = '" << patientID << "'";
  193. check_exists_query.exec(check_exists_query_string.str().c_str());
  194. /// we check only patients with the same PatientID
  195. /// PatientID is not unique in DICOM, so we also compare Name and BirthDate
  196. /// and assume this is sufficient
  197. while (check_exists_query.next())
  198. {
  199. if (
  200. check_exists_query.record().value("PatientsName").toString() == patientsName.c_str() &&
  201. check_exists_query.record().value("PatientsBirthDate").toString() == patientsBirthDate.c_str()
  202. )
  203. {
  204. /// found it
  205. patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
  206. break;
  207. }
  208. }
  209. if(!patientExists)
  210. {
  211. std::stringstream query_string;
  212. query_string << "INSERT INTO Patients VALUES( NULL,'"
  213. << patientsName << "','"
  214. << patientID << "','"
  215. << patientsBirthDate << "','"
  216. << patientsBirthTime << "','"
  217. << patientsSex << "','"
  218. << patientsAge << "','"
  219. << patientComments << "')";
  220. query.exec(query_string.str().c_str());
  221. patientUID = query.lastInsertId().toInt();
  222. MITK_INFO << "New patient inserted: " << patientUID << "\n";
  223. }
  224. }
  225. else
  226. {
  227. patientUID = lastPatientUID;
  228. }
  229. /// keep this for the next image
  230. lastPatientUID = patientUID;
  231. lastPatientID = patientID;
  232. lastPatientsBirthDate = patientsBirthDate;
  233. lastPatientsName = patientsName;
  234. //---------------------
  235. //Add Study to Database
  236. //---------------------
  237. if(lastStudyInstanceUID.compare(studyInstanceUID))
  238. {
  239. QSqlQuery check_exists_query(database);
  240. std::stringstream check_exists_query_string;
  241. check_exists_query_string << "SELECT * FROM Studies WHERE StudyInstanceUID = '" << studyInstanceUID << "'";
  242. check_exists_query.exec(check_exists_query_string.str().c_str());
  243. if(!check_exists_query.next())
  244. {
  245. std::stringstream query_string;
  246. query_string << "INSERT INTO Studies VALUES('"
  247. << studyInstanceUID << "','"
  248. << patientUID << "','"
  249. << studyID << "','"
  250. << QDate::fromString(studyDate.c_str(), "yyyyMMdd").toString("yyyy-MM-dd").toStdString() << "','"
  251. << studyTime << "','"
  252. << accessionNumber << "','"
  253. << modalitiesInStudy << "','"
  254. << institutionName << "','"
  255. << referringPhysician << "','"
  256. << performingPhysiciansName << "','"
  257. << studyDescription << "')";
  258. query.exec(query_string.str().c_str());
  259. }
  260. }
  261. lastStudyInstanceUID = studyInstanceUID;
  262. //----------------------
  263. //Add Series to Database
  264. //----------------------
  265. if(lastSeriesInstanceUID.compare(seriesInstanceUID))
  266. {
  267. QSqlQuery check_exists_query(database);
  268. std::stringstream check_exists_query_string;
  269. check_exists_query_string << "SELECT * FROM Series WHERE SeriesInstanceUID = '" << seriesInstanceUID << "'";
  270. check_exists_query.exec(check_exists_query_string.str().c_str());
  271. if(!check_exists_query.next())
  272. {
  273. std::stringstream query_string;
  274. query_string << "INSERT INTO Series VALUES('"
  275. << seriesInstanceUID << "','"
  276. << studyInstanceUID << "','"
  277. << static_cast<int>(seriesNumber) << "','"
  278. << QDate::fromString(seriesDate.c_str(), "yyyyMMdd").toString("yyyy-MM-dd").toStdString() << "','"
  279. << seriesTime << "','"
  280. << seriesDescription << "','"
  281. << bodyPartExamined << "','"
  282. << frameOfReferenceUID << "','"
  283. << static_cast<int>(acquisitionNumber) << "','"
  284. << contrastAgent << "','"
  285. << scanningSequence << "','"
  286. << static_cast<int>(echoNumber) << "','"
  287. << static_cast<int>(temporalPosition) << "')";
  288. query.exec(query_string.str().c_str());
  289. }
  290. }
  291. lastSeriesInstanceUID = seriesInstanceUID;
  292. //----------------------------------
  293. //Move file to destination directory
  294. //----------------------------------
  295. if (!destinationDirectoryName.isEmpty())
  296. {
  297. QFile currentFile( qfilename );
  298. QDir destinationDir(destinationDirectoryName);
  299. QString uniqueDirName = QString(studyInstanceUID.c_str()) + "/" + seriesInstanceUID.c_str();
  300. qDebug() << "MKPath: " << uniqueDirName;
  301. destinationDir.mkpath(uniqueDirName);
  302. QString destFileName = destinationDir.absolutePath().append("/").append(instanceNumber.c_str());
  303. qDebug() << "Copy: " << qfilename << " -> " << destFileName;
  304. currentFile.copy(destFileName);
  305. //for testing only: copy file instead of moving
  306. //currentFile.copyTo(destDirectoryPath.str());
  307. }
  308. // */
  309. //------------------------
  310. //Add Filename to Database
  311. //------------------------
  312. // std::stringstream relativeFilePath;
  313. // relativeFilePath << seriesInstanceUID.c_str() << "/" << currentFilePath.getFileName();
  314. QSqlQuery check_exists_query(database);
  315. std::stringstream check_exists_query_string;
  316. // check_exists_query_string << "SELECT * FROM Images WHERE Filename = '" << relativeFilePath.str() << "'";
  317. check_exists_query_string << "SELECT * FROM Images WHERE Filename = '" << filename << "'";
  318. check_exists_query.exec(check_exists_query_string.str().c_str());
  319. if(!check_exists_query.next())
  320. {
  321. std::stringstream query_string;
  322. //To save absolute path: destDirectoryPath.str()
  323. query_string << "INSERT INTO Images VALUES('"
  324. << /*relativeFilePath.str()*/ filename << "','" << seriesInstanceUID << "','" << QDateTime::currentDateTime().toString(Qt::ISODate).toStdString() << "')";
  325. query.exec(query_string.str().c_str());
  326. }
  327. }
  328. // db.commit();
  329. // db.close();
  330. }
  331. //------------------------------------------------------------------------------
  332. void ctkDICOMIndexer::refreshDatabase(QSqlDatabase database, const QString& directoryName)
  333. {
  334. /// get all filenames from the database
  335. QSqlQuery allFilesQuery(database);
  336. QStringList databaseFileNames;
  337. QStringList filesToRemove;
  338. allFilesQuery.exec("SELECT Filename from Images;");
  339. while (allFilesQuery.next())
  340. {
  341. QString fileName = allFilesQuery.value(0).toString();
  342. databaseFileNames.append(fileName);
  343. if (! QFile::exists(fileName) )
  344. {
  345. filesToRemove.append(fileName);
  346. }
  347. }
  348. QSet<QString> filesytemFiles;
  349. QDirIterator dirIt(directoryName);
  350. while (dirIt.hasNext())
  351. {
  352. filesytemFiles.insert(dirIt.next());
  353. }
  354. }