]> Creatis software - gdcm.git/blob - gdcmPython/demo/ReorganiseFiles.py
3db13f4dffb8331209e7a68b2bcfcd2936ab2c5d
[gdcm.git] / gdcmPython / demo / ReorganiseFiles.py
1 # Rename the dcm extension files of a given directory according
2 # to series and image number information extracted in each respective header.
3
4 from gdcmPython import *
5 import glob
6 import os
7 import sys
8
9 def PrintUsage():
10    print "Usage: python ReorganiseFiles.py <SourceDirectory>"
11    print "       <SourceDirectory> is the directory containing the source"
12    print "                         images (defaulted to invocation directory."
13
14 def Warning(DirName):
15    print "Warning: this script will rename files in the"
16    print "        ", DirName, " directory."
17    a = raw_input("Proceed ?[y/n]")
18    if a != "y":
19       sys.exit()
20
21 try:
22    SourceDirectory = sys.argv[1]
23 except IndexError:
24    SourceDirectory = os.getcwd()
25
26 if not os.path.isdir(SourceDirectory):
27    PrintUsage
28 Warning(SourceDirectory)
29 SourceFiles=glob.glob(os.path.join(SourceDirectory, "*.dcm"))
30
31 for file in SourceFiles:
32    header = gdcmHeader(file)
33    info = header.GetEntry()
34    try:
35       ImNum = info["Image Number"]
36       if len(ImNum) == 0 or ImNum == "gdcm::Unfound":
37          raise KeyError
38    except KeyError:
39       print "Skipped file ", file, " (unfound Image Number tag)."
40       continue
41    try:
42       SeNum = info["Series Number"]
43       if len(SeNum) == 0 or SeNum == "gdcm::Unfound":
44          raise KeyError
45    except KeyError:
46       print "Skipped file ", file, " (unfound Series Number tag)."
47       continue
48    DestFile = "image_%02d_%04d.dcm"
49    DestFile %= (int(info["Image Number"]), int(info["Series Number"]))
50    DestFile = os.path.join(SourceDirectory, DestFile)
51    # necessary to close the file descriptor to enable further rename.
52    del header
53    if os.path.isfile(DestFile):
54       print "Skipped file ", file, " (allready existing destination"
55       print "     file ", DestFile
56       continue
57    os.rename(file, DestFile)