Skip to content

Commit f478aa4

Browse files
committed
proper detection of "is animated" for PillowImage type annotation
1 parent 5005afa commit f478aa4

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

mltu/annotations/images.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -189,23 +189,26 @@ def __init__(
189189
self.path = image
190190
self._image = PilImage.open(image)
191191

192-
self._updated = False
193192
self.init_successful = True
194193
else:
195194
raise TypeError('Image must be a path to an image')
196195

197-
if not self._image.is_animated:
198-
self._init_attributes()
199-
else:
196+
if self.is_animated:
200197
# initialize whatever attributes we can already determine at this stage, i.e. width & height.
201198
self.width = self._image.width
202199
self.height = self._image.height
203200
self.channels = None
201+
else:
202+
self._init_attributes()
203+
204+
@property
205+
def is_animated(self) -> bool:
206+
return (hasattr(self._image, 'is_animated') and self._image.is_animated)
204207

205208
@property
206209
def image(self) -> np.ndarray:
207-
if not self._updated:
208-
raise Exception('need to update first')
210+
if self.is_animated:
211+
raise Exception('convert to single image first')
209212

210213
return np.asarray(self._image)
211214

@@ -241,20 +244,22 @@ def _init_attributes(self):
241244
self.color = self._image.mode
242245

243246
# save width, height and channels
244-
self.width = self._image.shape[1]
245-
self.height = self._image.shape[0]
246-
self.channels = 1 if len(self._image.shape) == 2 else self._image.shape[2]
247-
248-
self._updated = True
247+
self.width = self.image.shape[1]
248+
self.height = self.image.shape[0]
249+
self.channels = 1 if len(self.image.shape) == 2 else self.image.shape[2]
249250

250251
def update(self, image: PilImage.Image):
251252
if isinstance(image, PilImage.Image):
252253
self._image = image
254+
elif isinstance(image, np.ndarray):
255+
self._image = PilImage.fromarray(image)
256+
else:
257+
raise TypeError(f'image must be a Pillow Image or np.ndarray, not {type(image)}')
258+
259+
if not self.is_animated:
253260
self._init_attributes()
254261

255-
return self
256-
else:
257-
raise TypeError(f'image must be a Pillow Image, not {type(image)}')
262+
return self
258263

259264
def flip(self, axis: int = 0):
260265
""" Flip image along x or y axis
@@ -269,8 +274,8 @@ def flip(self, axis: int = 0):
269274
if axis not in [0, 1]:
270275
raise ValueError(f'axis must be either 0 or 1, not {axis}')
271276

272-
if not self._updated:
273-
raise Exception('need to update first')
277+
if self.is_animated:
278+
raise Exception('convert to single image first')
274279

275280
if axis == 0:
276281
self._image = PilImage.fromarray(np.asarray(self._image)[:, ::-1])

0 commit comments

Comments
 (0)