Skip to content

Commit a8230ee

Browse files
committed
Use NumPy to convert images to 8-bit before creating GIFs
1 parent b9da8a3 commit a8230ee

1 file changed

Lines changed: 22 additions & 7 deletions

File tree

src/murfey/server/api/workflow.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from pathlib import Path
55
from typing import Any, Dict, List, Optional
66

7+
import numpy as np
78
import sqlalchemy
89
from fastapi import APIRouter, Depends
910
from ispyb.sqlalchemy import (
@@ -1104,29 +1105,43 @@ async def make_gif(
11041105
]
11051106
output_dir = (
11061107
(machine_config.rsync_basepath or Path("")).resolve()
1107-
/ secure_filename(year)
1108+
/ secure_filename(str(year))
11081109
/ secure_filename(visit_name)
11091110
/ "processed"
11101111
)
11111112
output_dir.mkdir(exist_ok=True)
11121113
output_dir = output_dir / secure_filename(gif_params.raw_directory)
11131114
output_dir.mkdir(exist_ok=True)
11141115
output_path = output_dir / f"lamella_{gif_params.lamella_number}_milling.gif"
1115-
image_full_paths = [
1116-
output_dir.parent / gif_params.raw_directory / i for i in gif_params.images
1117-
]
1116+
11181117
if Image is not None:
1119-
images = [Image.open(f) for f in image_full_paths]
1118+
images = [Image.open(f) for f in gif_params.images]
11201119
else:
11211120
images = []
11221121
for im in images:
11231122
im.thumbnail((512, 512))
1124-
images[0].save(
1123+
1124+
# Normalize and convert individual frames to 8-bit
1125+
arr: list[np.ndarray] = []
1126+
for im in images:
1127+
frame = np.array(im).astype(np.float32)
1128+
vmin, vmax = np.percentile(frame, (0.5, 99.5))
1129+
scale = 255 / ((vmax - vmin) or 1)
1130+
np.clip(frame, a_min=vmin, a_max=vmax, out=frame)
1131+
np.subtract(frame, vmin, out=frame)
1132+
np.multiply(frame, scale, out=frame)
1133+
arr.append(frame.astype(np.uint8))
1134+
arr = np.array(arr).astype(np.uint8)
1135+
1136+
# Convert back to Image objects and save as GIF
1137+
converted = [Image.fromarray(arr[f], mode="L") for f in range(len(images))]
1138+
converted[0].save(
11251139
output_path,
11261140
format="GIF",
1127-
append_images=images[1:],
1141+
append_images=converted[1:],
11281142
save_all=True,
11291143
duration=30,
11301144
loop=0,
11311145
)
1146+
11321147
return {"output_gif": str(output_path)}

0 commit comments

Comments
 (0)