Conditions | 7 |
Total Lines | 54 |
Code Lines | 43 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.
There are several approaches to avoid long parameter lists:
1 | import warnings |
||
176 | def make_gif( |
||
177 | tensor: torch.Tensor, |
||
178 | axis: int, |
||
179 | duration: float, # of full gif |
||
180 | output_path: TypePath, |
||
181 | loop: int = 0, |
||
182 | optimize: bool = True, |
||
183 | rescale: bool = True, |
||
184 | reverse: bool = False, |
||
185 | ) -> None: |
||
186 | try: |
||
187 | from PIL import Image as ImagePIL |
||
188 | except ModuleNotFoundError as e: |
||
189 | message = ( |
||
190 | 'Please install Pillow to use Image.to_gif():' |
||
191 | ' pip install Pillow' |
||
192 | ) |
||
193 | raise RuntimeError(message) from e |
||
194 | tensor = RescaleIntensity((0, 255))(tensor) if rescale else tensor |
||
195 | single_channel = len(tensor) == 1 |
||
196 | |||
197 | # Move channels dimension to the end and bring selected axis to 0 |
||
198 | axes = np.roll(range(1, 4), -axis) |
||
199 | tensor = tensor.permute(*axes, 0) |
||
200 | |||
201 | if single_channel: |
||
202 | mode = 'P' |
||
203 | tensor = tensor[..., 0] |
||
204 | else: |
||
205 | mode = 'RGB' |
||
206 | array = tensor.byte().numpy() |
||
207 | n = 2 if axis == 1 else 1 |
||
208 | images = [ImagePIL.fromarray(rotate(i, n=n)).convert(mode) for i in array] |
||
209 | num_images = len(images) |
||
210 | images = list(reversed(images)) if reverse else images |
||
211 | frame_duration_ms = duration / num_images * 1000 |
||
212 | if frame_duration_ms < 10: |
||
213 | fps = round(1000 / frame_duration_ms) |
||
214 | frame_duration_ms = 10 |
||
215 | new_duration = frame_duration_ms * num_images / 1000 |
||
216 | message = ( |
||
217 | 'The computed frame rate from the given duration is too high' |
||
218 | f' ({fps} fps). The highest possible frame rate in the GIF' |
||
219 | ' file format specification is 100 fps. The duration has been set' |
||
220 | f' to {new_duration:.1f} seconds, instead of {duration:.1f}' |
||
221 | ) |
||
222 | warnings.warn(message) |
||
223 | images[0].save( |
||
224 | output_path, |
||
225 | save_all=True, |
||
226 | append_images=images[1:], |
||
227 | optimize=optimize, |
||
228 | duration=frame_duration_ms, |
||
229 | loop=loop, |
||
230 | ) |
||
231 |