1 # Rename the dcm extension files of a given drectory according
2 # to series and image number information extracted in each respective header.
4 from gdcmPython import *
10 print "Usage: python ReorganiseFiles.py <SourceDirectory>"
11 print " <SourceDirectory> is the directory containing the source"
12 print " images (defaulted to invocation directory."
15 print "Warning: this script will rename files in the"
16 print " ", DirName, " directory."
17 a = raw_input("Proceed ?[y/n]")
22 SourceDirectory = sys.argv[1]
24 SourceDirectory = os.getcwd()
26 if not os.path.isdir(SourceDirectory):
28 Warning(SourceDirectory)
29 SourceFiles=glob.glob(os.path.join(SourceDirectory, "*.dcm"))
31 for file in SourceFiles:
32 header = gdcmHeader(file)
33 info = header.GetPubElVal()
35 ImNum = info["Image Number"]
36 if len(ImNum) == 0 or ImNum == "gdcm::Unfound":
39 print "Skipped file ", file, " (unfound Image Number tag)."
42 SeNum = info["Series Number"]
43 if len(SeNum) == 0 or SeNum == "gdcm::Unfound":
46 print "Skipped file ", file, " (unfound Series Number tag)."
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.
53 if os.path.isfile(DestFile):
54 print "Skipped file ", file, " (allready existing destination"
55 print " file ", DestFile
57 os.rename(file, DestFile)