optimise some dicom manipulations

This commit is contained in:
Ross
2025-06-30 11:04:39 +01:00
parent bc26209f07
commit 153045a3e4
2 changed files with 46 additions and 50 deletions
+23 -29
View File
@@ -568,41 +568,35 @@ class SeriesBase(models.Model):
n = n + 1
def order_by_dicom(self, field="SliceLocation"):
"""
Orders images in the series by the given DICOM field (default: SliceLocation).
Only keeps minimal data in memory and uses bulk_update for efficiency.
"""
images = self.images.filter(removed=False)
sortable = []
for img in images:
try:
ds = pydicom.dcmread(img.image.path, stop_before_pixels=True)
value = getattr(ds, field, None)
if value is not None:
sortable.append((value, img))
except Exception:
continue # Skip unreadable or invalid DICOMs
files = []
for i in images:
files.append((i, pydicom.dcmread(i.image.path)))
# print("file count: {}".format(len(files)))
# skip files with no SliceLocation (eg scout views)
slices = []
map = {}
skipcount = 0
for i, f in files:
if hasattr(f, field):
slices.append(f)
# map[f.SliceLocation] = i
map[f[field].value] = i
else:
skipcount = skipcount + 1
if not slices:
if not sortable:
return
# ensure they are in the correct order
slices = sorted(slices, key=lambda s: s[field].value)
# Sort by the DICOM field value
sortable.sort(key=lambda x: x[0])
# print(slices)
n = 1
for f in slices:
i = map[f[field].value]
i.position = n
i.save()
n = n + 1
# Assign new positions and collect for bulk update
for idx, (value, img) in enumerate(sortable, start=1):
img.position = idx
# Bulk update all changed images
SeriesImage = self.images.model
SeriesImage.objects.bulk_update([img for _, img in sortable], ['position'])
def get_total_image_size(self, refresh=False):
"""Returns the total size of all images in the series.