ctkDICOMIndexer.cpp 17 KB

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