ctkDICOMIndexer.cpp 15 KB

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