-
-
Notifications
You must be signed in to change notification settings - Fork 345
Expand file tree
/
Copy pathload_image.py
More file actions
195 lines (156 loc) · 5.21 KB
/
load_image.py
File metadata and controls
195 lines (156 loc) · 5.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
from __future__ import annotations
import os
import platform
from pathlib import Path
from typing import Callable, Iterable, Union
import cv2
import numpy as np
import pillow_avif # type: ignore # noqa: F401
from PIL import Image
from sanic.log import logger
from nodes.impl.dds.texconv import dds_to_png_texconv
from nodes.impl.image_formats import (
get_available_image_formats,
get_opencv_formats,
get_pil_formats,
)
from nodes.properties.inputs import ImageFileInput
from nodes.properties.outputs import DirectoryOutput, FileNameOutput, LargeImageOutput
from nodes.utils.utils import get_h_w_c, split_file_path
from .. import io_group
_Decoder = Callable[[Path], Union[np.ndarray, None]]
"""
An image decoder.
Of the given image is naturally not supported, the decoder may return `None`
instead of raising an exception. E.g. when the file extension indicates an
unsupported format.
"""
def get_ext(path: Path | str) -> str:
return split_file_path(path)[2].lower()
def remove_unnecessary_alpha(img: np.ndarray) -> np.ndarray:
"""
Removes the alpha channel from an image if it is not used.
"""
if get_h_w_c(img)[2] != 4:
return img
unnecessary = (
(img.dtype == np.uint8 and np.all(img[:, :, 3] == 255))
or (img.dtype == np.uint16 and np.all(img[:, :, 3] == 65536))
or (img.dtype == np.float32 and np.all(img[:, :, 3] == 1.0))
or (img.dtype == np.float64 and np.all(img[:, :, 3] == 1.0))
)
if unnecessary:
return img[:, :, :3]
return img
def _read_cv(path: Path) -> np.ndarray | None:
if get_ext(path) not in get_opencv_formats():
# not supported
return None
img = None
try:
img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
except Exception as cv_err:
logger.warning(f"Error loading image, trying with imdecode: {cv_err}")
if img is None:
try:
img = cv2.imread(str(path), cv2.IMREAD_UNCHANGED)
except Exception as e:
raise RuntimeError(
f'Error reading image image from path "{path}". Image may be corrupt.'
) from e
if img is None: # type: ignore
raise RuntimeError(
f'Error reading image image from path "{path}". Image may be corrupt.'
)
return img
def _read_pil(path: Path) -> np.ndarray | None:
if get_ext(path) not in get_pil_formats():
# not supported
return None
im = Image.open(path)
if im.mode == "P":
# convert color palette to actual colors
im = im.convert(im.palette.mode)
img = np.array(im)
_, _, c = get_h_w_c(img)
if c == 3:
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
elif c == 4:
img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGRA)
return img
def _read_dds(path: Path) -> np.ndarray | None:
if get_ext(path) != ".dds":
# not supported
return None
if platform.system() != "Windows":
# texconv is only supported on Windows.
return None
png = dds_to_png_texconv(path)
try:
img = _read_cv(png)
if img is not None:
img = remove_unnecessary_alpha(img)
return img
finally:
os.remove(png)
def _for_ext(ext: str | Iterable[str], decoder: _Decoder) -> _Decoder:
ext_set: set[str] = set()
if isinstance(ext, str):
ext_set.add(ext)
else:
ext_set.update(ext)
return lambda path: decoder(path) if get_ext(path) in ext_set else None
_decoders: list[tuple[str, _Decoder]] = [
("pil-jpeg", _for_ext([".jpg", ".jpeg"], _read_pil)),
("cv", _read_cv),
("texconv-dds", _read_dds),
("pil", _read_pil),
]
valid_formats = get_available_image_formats()
@io_group.register(
schema_id="chainner:image:load",
name="Load Image",
description=(
"Load image from specified file. This node will output the loaded image, the"
" directory of the image file, and the name of the image file (without file"
" extension)."
),
icon="BsFillImageFill",
inputs=[
ImageFileInput(primary_input=True).with_docs(
"Select the path of an image file."
)
],
outputs=[
LargeImageOutput()
.with_docs(
"The node will display a preview of the selected image as well as type"
" information for it. Connect this output to the input of another node to"
" pass the image to it."
)
.suggest(),
DirectoryOutput("Directory", of_input=0),
FileNameOutput("Name", of_input=0),
],
side_effects=True,
)
def load_image_node(path: Path) -> tuple[np.ndarray, Path, str]:
logger.debug(f"Reading image from path: {path}")
dirname, basename, _ = split_file_path(path)
img = None
error = None
for name, decoder in _decoders:
try:
img = decoder(Path(path))
except Exception as e:
error = e
logger.warning(f"Decoder {name} failed")
if img is not None:
break
if img is None:
if error is not None:
raise error
raise RuntimeError(
f'The image "{path}" you are trying to read cannot be read by chaiNNer.'
)
return img, dirname, basename