@@ -104,31 +104,32 @@ async def make_gif(
104104 continue
105105
106106 # Load the images as PIL Image objects
107- images = [PIL .Image .open (f ) for f in gif_params .images ]
108- for im in images :
109- im .thumbnail ((512 , 512 ))
110-
111- # Normalize and convert individual frames to 8-bit
112107 arr : list [np .ndarray ] = []
113- for im in images :
114- frame = np .array (im ).astype (np .float32 )
115- vmin , vmax = np .percentile (frame , (0.5 , 99.5 ))
116- scale = 255 / ((vmax - vmin ) or 1 )
117- np .clip (frame , a_min = vmin , a_max = vmax , out = frame )
118- np .subtract (frame , vmin , out = frame )
119- np .multiply (frame , scale , out = frame )
120- arr .append (frame .astype (np .uint8 ))
108+ for f in gif_params .images :
109+ with PIL .Image .open (f ) as im :
110+ im .thumbnail ((512 , 512 ))
111+ frame = np .array (im , dtype = np .float32 )
112+ vmin , vmax = np .percentile (frame , (0.5 , 99.5 ))
113+ scale = 255 / ((vmax - vmin ) or 1 )
114+ np .clip (frame , a_min = vmin , a_max = vmax , out = frame )
115+ np .subtract (frame , vmin , out = frame )
116+ np .multiply (frame , scale , out = frame )
117+ arr .append (frame .astype (np .uint8 ))
121118 arr = np .array (arr ).astype (np .uint8 )
122119
123120 # Convert back to PIL.Image objects and save as GIF
124- converted = [PIL .Image .fromarray (arr [f ], mode = "L" ) for f in range (len (images ))]
125- converted [0 ].save (
126- output_file ,
127- format = "GIF" ,
128- append_images = converted [1 :],
129- save_all = True ,
130- duration = 30 ,
131- loop = 0 ,
132- )
133- logger .info (f"Created GIF file { output_file } " )
134- return {"output_gif" : str (output_file )}
121+ try :
122+ converted = [PIL .Image .fromarray (a , mode = "L" ) for a in arr ]
123+ converted [0 ].save (
124+ output_file ,
125+ format = "GIF" ,
126+ append_images = converted [1 :],
127+ save_all = True ,
128+ duration = 30 ,
129+ loop = 0 ,
130+ )
131+ logger .info (f"Created GIF file { output_file } " )
132+ return {"output_gif" : str (output_file )}
133+ finally :
134+ for im in converted :
135+ im .close ()
0 commit comments