changeset 1182:d74ac5d0bcaf

New sample: Automated classification of DICOM files
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 09 Oct 2014 17:11:00 +0200
parents 17302d83abfd
children 6ef2c81581cd
files Resources/Samples/Python/AutoClassify.py
diffstat 1 files changed, 113 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/Samples/Python/AutoClassify.py	Thu Oct 09 17:11:00 2014 +0200
@@ -0,0 +1,113 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege,
+# Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+import argparse
+import time
+import os
+import os.path
+import RestToolbox
+
+parser = argparse.ArgumentParser(
+    description = 'Automated classification of DICOM files from Orthanc.',
+    formatter_class = argparse.ArgumentDefaultsHelpFormatter)
+
+parser.add_argument('--host', default = 'localhost',
+                    help = 'The host address that runs Orthanc')
+parser.add_argument('--port', type = int, default = '8042',
+                    help = 'The port number to which Orthanc is listening for the REST API')
+parser.add_argument('--target', default = 'OrthancFiles',
+                    help = 'The target directory where to store the DICOM files')
+parser.add_argument('--all', action = 'store_true',
+                    help = 'Replay the entire history on startup (disabled by default)')
+parser.set_defaults(all = False)
+parser.add_argument('--remove', action = 'store_true',
+                    help = 'Remove DICOM files from Orthanc once classified (disabled by default)')
+parser.set_defaults(remove = False)
+
+
+# Parse the arguments
+args = parser.parse_args()
+URL = 'http://%s:%d' % (args.host, args.port)
+print 'Connecting to Orthanc on address: %s' % URL
+
+# Compute the starting point for the changes loop
+if args.all:
+    current = 0
+else:
+    current = RestToolbox.DoGet(URL + '/changes?last')['Last']
+
+# Polling loop using the "changes" API of Orthanc, waiting for the
+# incoming of new DICOM files
+while True:
+    r = RestToolbox.DoGet(URL + '/changes', {
+            'since' : current,
+            'limit' : 4   # Retrieve at most 4 changes at once
+            })
+
+    for change in r['Changes']:
+        # We are only interested interested in the arrival of new instances
+        if change['ChangeType'] == 'NewInstance':
+            # Extract the patient, study, series and instance information
+            instance = RestToolbox.DoGet('%s/instances/%s' % (URL, change['ID']))
+            series = RestToolbox.DoGet('%s/series/%s' % (URL, instance['ParentSeries']))
+            study = RestToolbox.DoGet('%s/studies/%s' % (URL, series['ParentStudy']))
+            patient = RestToolbox.DoGet('%s/patients/%s' % (URL, study['ParentPatient']))
+
+            # Construct a target path
+            a = '%s - %s' % (patient['MainDicomTags']['PatientID'], 
+                             patient['MainDicomTags']['PatientName'])
+            b = study['MainDicomTags']['StudyDescription']
+            c = '%s - %s' % (series['MainDicomTags']['Modality'],
+                             series['MainDicomTags']['SeriesDescription'])
+            d = '%s.dcm' % instance['MainDicomTags']['SOPInstanceUID']
+
+            p = os.path.join(
+                args.target,
+                a.encode('ascii', 'ignore'),
+                b.encode('ascii', 'ignore'),
+                c.encode('ascii', 'ignore')
+                )
+
+            f = os.path.join(p, d.encode('ascii', 'ignore'))
+                             
+
+            # Copy the DICOM file to the target path
+            print('Writing new DICOM file: %s' % f)
+
+            try:
+                os.makedirs(p)
+            except:
+                # Already existing directory, ignore the error
+                pass
+
+            dcm = RestToolbox.DoGet('%s/instances/%s/file' % (URL, change['ID']))
+            with open(f, 'wb') as g:
+                g.write(dcm)
+            
+            # If requested, remove the instance once it has been copied
+            if args.remove:
+                RestToolbox.DoDelete('%s/instances/%s' % (URL, change['ID']))
+
+    current = r['Last']
+
+    if r['Done']:
+        print "Everything has been processed: Waiting..."
+        time.sleep(1)