Repository navigation
Expand file tree
/
Copy pathconcatenateIview.py
More file actions
197 lines (172 loc) · 8.31 KB
/
Copy pathconcatenateIview.py
File metadata and controls
197 lines (172 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python3
import click
import xml.etree.ElementTree as ET
import os
import shutil
import sys
from PyQt5.QtWidgets import (QFileDialog, QAbstractItemView, QListView,
QTreeView, QApplication, QDialog)
class getExistingDirectories(QFileDialog):
def __init__(self, *args):
super(getExistingDirectories, self).__init__(*args)
self.setOption(self.DontUseNativeDialog, True)
self.setFileMode(self.Directory)
self.setOption(self.ShowDirsOnly, True)
self.findChildren(QListView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)
self.findChildren(QTreeView)[0].setSelectionMode(QAbstractItemView.ExtendedSelection)
class XmlListConfig(list):
def __init__(self, aList):
for element in aList:
if element:
# treat like dict
if len(element) == 1 or element[0].tag != element[1].tag:
self.append(XmlDictConfig(element))
# treat like list
elif element[0].tag == element[1].tag:
self.append(XmlListConfig(element))
elif element.text:
text = element.text.strip()
if text:
self.append(text)
class XmlDictConfig(dict):
'''
Example usage:
>>> tree = ElementTree.parse('your_file.xml')
>>> root = tree.getroot()
>>> xmldict = XmlDictConfig(root)
Or, if you want to use an XML string:
>>> root = ElementTree.XML(xml_string)
>>> xmldict = XmlDictConfig(root)
And then use xmldict for what it is... a dict.
'''
def __init__(self, parent_element):
if parent_element.items():
self.update(dict(parent_element.items()))
for element in parent_element:
if element:
# treat like dict - we assume that if the first two tags
# in a series are different, then they are all different.
if len(element) == 1 or element[0].tag != element[1].tag:
aDict = XmlDictConfig(element)
# treat like list - we assume that if the first two tags
# in a series are the same, then the rest are the same.
else:
# here, we put the list in dictionary; the key is the
# tag name the list elements all share in common, and
# the value is the list itself
aDict = {element[0].tag: XmlListConfig(element)}
# if the tag has attributes, add those to the dict
if element.items():
aDict.update(dict(element.items()))
self.update({element.tag: aDict})
# this assumes that if you've got an attribute in a tag,
# you won't be having any text. This may or may not be a
# good idea -- time will tell. It works for the way we are
# currently doing XML configuration files...
elif element.items():
self.update({element.tag: dict(element.items())})
# finally, if there are no child tags and no attributes, extract
# the text
else:
self.update({element.tag: element.text})
def dict2xml(dict):
string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
string += "<ProjectionSet>\r\n"
string += "\t<!--Do not edit this file-->\r\n"
string += "\t<Station>\r\n"
string += "\t\t<StationName>" + dict["Station"]["StationName"] + "</StationName>\r\n"
string += "\t</Station>\r\n"
string += "\t<Image>\r\n"
string += "\t\t<Energy>" + dict["Image"]["Energy"] + "</Energy>\r\n"
string += "\t\t<Height>" + dict["Image"]["Height"] + "</Height>\r\n"
string += "\t\t<Width>" + dict["Image"]["Width"] + "</Width>\r\n"
string += "\t\t<Depth>" + dict["Image"]["Depth"] + "</Depth>\r\n"
string += "\t\t<DicomUID>" + dict["Image"]["DicomUID"] + "</DicomUID>\r\n"
string += "\t\t<TotalSetBeamMU>" + dict["Image"]["TotalSetBeamMU"] + "</TotalSetBeamMU>\r\n"
string += "\t</Image>\r\n"
string += "\t<Frames>\r\n"
for frame in dict["Frames"]["Frame"]:
string += "\t\t<Frame>\r\n"
string += "\t\t\t<Seq>" + frame["Seq"] + "</Seq>\r\n"
string += "\t\t\t<DeltaMs>" + frame["DeltaMs"] + "</DeltaMs>\r\n"
string += "\t\t\t<HasPixelFactor>" + frame["HasPixelFactor"] + "</HasPixelFactor>\r\n"
string += "\t\t\t<PixelFactor>" + frame["PixelFactor"] + "</PixelFactor>\r\n"
string += "\t\t\t<gantryAngle>" + frame["gantryAngle"] + "</gantryAngle>\r\n"
string += "\t\t\t<CumulativeBeamMU>" + frame["CumulativeBeamMU"] + "</CumulativeBeamMU>\r\n"
string += "\t\t\t<IsBeamMuValid>" + frame["IsBeamMuValid"] + "</IsBeamMuValid>\r\n"
string += "\t\t</Frame>\r\n"
string += "\t</Frames>\r\n"
string += "</ProjectionSet>\r\n"
return(string)
# -----------------------------------------------------------------------------
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('folders', nargs=-1)
@click.option('-o', '--output', default='.', help='Output folder')
def concatenateIview_main(folders, output):
folders = [xs for xs in folders]
concatenateIview(folders)
def concatenateIview(folders='.', output='.'):
qapp = QApplication(sys.argv)
dlg = getExistingDirectories()
if dlg.exec_() == QDialog.Accepted:
print(dlg.selectedFiles())
folders = dlg.selectedFiles()
#Control the minimal number of folders and sort them
if len(folders) < 2:
return()
folders.sort()
#copy the first folder
outputFolder = os.path.join(output, os.path.basename(folders[0]))
print(outputFolder)
print(folders)
if os.path.isdir(outputFolder):
shutil.rmtree(outputFolder)
shutil.copytree(folders[0], outputFolder)
#Read the xml of the first folder
mainXml = ET.parse(os.path.join(outputFolder, '_Frame.xml'))
mainXmldict = XmlDictConfig(mainXml.getroot())
lastSeq = int(mainXmldict['Frames']['Frame'][-1]['Seq'])
lastDeltaMs = int(mainXmldict['Frames']['Frame'][-1]['DeltaMs'])
lastCumulativeBeamMU = float(mainXmldict['Frames']['Frame'][-1]['CumulativeBeamMU'])
#print(xmldict)
#Copy name of the first folder for future copied jpg images
baseJpgImage = os.path.basename(outputFolder)[4:]
#Copy all other folders
for folder in folders:
if folder == folders[0]:
continue
currentXml = ET.parse(os.path.join(folder, '_Frame.xml'))
currentXmldict = XmlDictConfig(currentXml.getroot())
#list file in that folder
files = os.listdir(folder)
jpgFiles = []
for file in files:
if file.endswith('.jpg'):
jpgFiles.append(file)
jpgFiles.sort()
if not len(jpgFiles) == len(currentXmldict['Frames']['Frame']):
print("Error, the number of .jpg is not correct")
for file, xml in zip(jpgFiles, currentXmldict['Frames']['Frame']):
shutil.copyfile(os.path.join(folder, file), os.path.join(outputFolder, str(lastSeq + int(xml['Seq'])).zfill(5) + '.' + baseJpgImage + '.jpg'))
fileSeq = {
'Seq': str(lastSeq + int(xml['Seq'])),
'DeltaMs': str(lastDeltaMs + int(xml['DeltaMs'])),
'HasPixelFactor': xml['HasPixelFactor'],
'PixelFactor': xml['PixelFactor'],
'gantryAngle': xml['gantryAngle'],
'CumulativeBeamMU': str(round(lastCumulativeBeamMU + float(xml['CumulativeBeamMU']), 1)),
'IsBeamMuValid': xml['IsBeamMuValid']}
print(fileSeq)
mainXmldict['Frames']['Frame'].append(fileSeq)
#Update last values
lastSeq = int(mainXmldict['Frames']['Frame'][-1]['Seq'])
lastDeltaMs = int(mainXmldict['Frames']['Frame'][-1]['DeltaMs'])
lastCumulativeBeamMU = float(mainXmldict['Frames']['Frame'][-1]['CumulativeBeamMU'])
outputXml = dict2xml(mainXmldict)
outputFile = open(os.path.join(outputFolder, "_Frame.xml"), "w")
outputFile.write(outputXml)
outputFile.close()
# -----------------------------------------------------------------------------
if __name__ == '__main__':
concatenateIview()