|
1
|
|
|
import attr |
|
2
|
|
|
from .image import ImageFactory |
|
3
|
|
|
from .disk_operations import Disk |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
@attr.s |
|
8
|
|
|
class ImageManager: |
|
9
|
|
|
preprocessing_pipeline = attr.ib() |
|
10
|
|
|
image_factory: ImageFactory = \ |
|
11
|
|
|
attr.ib(init=False, default=attr.Factory(lambda: ImageFactory(Disk.load_image))) |
|
12
|
|
|
images_compatible: bool = attr.ib(init=False, default=False) |
|
13
|
|
|
|
|
14
|
|
|
_known_types = attr.ib(init=False, default={'content', 'style'}) |
|
15
|
|
|
|
|
16
|
|
|
def __attrs_post_init__(self): |
|
17
|
|
|
for image_type in self._known_types: |
|
18
|
|
|
setattr(self, f'_{image_type}_image', None) |
|
19
|
|
|
|
|
20
|
|
|
def load_from_disk(self, file_path: str, image_type: str): |
|
21
|
|
|
if image_type not in self._known_types: |
|
22
|
|
|
raise ValueError(f'Expected type of image to be one of {self._known_types}; found {image_type}') |
|
23
|
|
|
# dynamically call the appropriate content/style setter method |
|
24
|
|
|
setattr(self, f'{image_type}_image', |
|
25
|
|
|
self.image_factory.from_disk(file_path, self.preprocessing_pipeline |
|
26
|
|
|
)) |
|
27
|
|
|
|
|
28
|
|
|
def _set_image(self, image, image_type: str): |
|
29
|
|
|
# dynamically set appropriate content/style attribute |
|
30
|
|
|
setattr(self, f'_{image_type}_image', image) |
|
31
|
|
|
if not (self._content_image is None or self._style_image is None): |
|
32
|
|
|
if self._content_image.matrix.shape == self._style_image.matrix.shape: |
|
33
|
|
|
self.images_compatible = True |
|
34
|
|
|
return |
|
35
|
|
|
self.images_compatible = False |
|
36
|
|
|
|
|
37
|
|
|
@property |
|
38
|
|
|
def content_image(self): |
|
39
|
|
|
return self._content_image |
|
40
|
|
|
|
|
41
|
|
|
@content_image.setter |
|
42
|
|
|
def content_image(self, image): |
|
43
|
|
|
self._set_image(image, 'content') |
|
44
|
|
|
|
|
45
|
|
|
@property |
|
46
|
|
|
def style_image(self): |
|
47
|
|
|
return self._style_image |
|
48
|
|
|
|
|
49
|
|
|
@style_image.setter |
|
50
|
|
|
def style_image(self, image): |
|
51
|
|
|
self._set_image(image, 'style') |
|
52
|
|
|
|