ctkDICOMIndexer.cpp 18 KB

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