emoge 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- emoge/__init__.py +1 -0
- emoge/fuzzy_color/__init__.py +75 -0
- emoge/fuzzy_color/lut.py +111 -0
- emoge/fuzzy_color/math/__init__.py +9 -0
- emoge/fuzzy_color/math/membership.py +164 -0
- emoge/fuzzy_color/math/norms.py +110 -0
- emoge/fuzzy_color/model.py +181 -0
- emoge/fuzzy_color/models/__init__.py +5 -0
- emoge/fuzzy_color/models/colibri.py +61 -0
- emoge/fuzzy_color/partitions.py +102 -0
- emoge/fuzzy_color/plots.py +211 -0
- emoge/fuzzy_color/sets.py +82 -0
- emoge/fuzzy_color/shapes.py +104 -0
- emoge/fuzzy_color/spaces/__init__.py +26 -0
- emoge/fuzzy_color/spaces/hsi.py +65 -0
- emoge/fuzzy_color/spaces/hsv.py +57 -0
- emoge/fuzzy_color/spaces/rgb.py +51 -0
- emoge/fuzzy_color/spaces/space.py +51 -0
- emoge/fuzzy_color/variables.py +70 -0
- emoge/py.typed +0 -0
- emoge-0.1.0.dist-info/METADATA +28 -0
- emoge-0.1.0.dist-info/RECORD +24 -0
- emoge-0.1.0.dist-info/WHEEL +4 -0
- emoge-0.1.0.dist-info/licenses/LICENSE +12 -0
emoge/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Research packages: import each one by itself, as `from emoge import fuzzy_color`."""
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Fuzzy color models: every pixel belongs to every named color to a degree.
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
import emoge.fuzzy_color as fc
|
|
5
|
+
```
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from emoge.fuzzy_color.lut import lookup_table
|
|
9
|
+
from emoge.fuzzy_color.math import membership, norms
|
|
10
|
+
from emoge.fuzzy_color.model import ColorModel
|
|
11
|
+
from emoge.fuzzy_color.models import COLIBRI
|
|
12
|
+
from emoge.fuzzy_color.partitions import partition
|
|
13
|
+
from emoge.fuzzy_color.plots import (
|
|
14
|
+
plot_palette,
|
|
15
|
+
plot_swatches,
|
|
16
|
+
plot_terms,
|
|
17
|
+
plot_variable,
|
|
18
|
+
)
|
|
19
|
+
from emoge.fuzzy_color.sets import FuzzySet
|
|
20
|
+
from emoge.fuzzy_color.shapes import (
|
|
21
|
+
falling,
|
|
22
|
+
gaussian,
|
|
23
|
+
generalized_bell,
|
|
24
|
+
pi_shape,
|
|
25
|
+
piecewise_linear,
|
|
26
|
+
rectangle,
|
|
27
|
+
rising,
|
|
28
|
+
s_shape,
|
|
29
|
+
sigmoid,
|
|
30
|
+
sigmoid_difference,
|
|
31
|
+
sigmoid_product,
|
|
32
|
+
singleton,
|
|
33
|
+
trapezoid,
|
|
34
|
+
triangle,
|
|
35
|
+
two_sided_gaussian,
|
|
36
|
+
z_shape,
|
|
37
|
+
)
|
|
38
|
+
from emoge.fuzzy_color.spaces import HSI, HSV, RGB, Channel, Space
|
|
39
|
+
from emoge.fuzzy_color.variables import Variable
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"COLIBRI",
|
|
43
|
+
"HSI",
|
|
44
|
+
"HSV",
|
|
45
|
+
"RGB",
|
|
46
|
+
"Channel",
|
|
47
|
+
"ColorModel",
|
|
48
|
+
"FuzzySet",
|
|
49
|
+
"Space",
|
|
50
|
+
"Variable",
|
|
51
|
+
"falling",
|
|
52
|
+
"gaussian",
|
|
53
|
+
"generalized_bell",
|
|
54
|
+
"lookup_table",
|
|
55
|
+
"membership",
|
|
56
|
+
"norms",
|
|
57
|
+
"partition",
|
|
58
|
+
"pi_shape",
|
|
59
|
+
"piecewise_linear",
|
|
60
|
+
"plot_palette",
|
|
61
|
+
"plot_swatches",
|
|
62
|
+
"plot_terms",
|
|
63
|
+
"plot_variable",
|
|
64
|
+
"rectangle",
|
|
65
|
+
"rising",
|
|
66
|
+
"s_shape",
|
|
67
|
+
"sigmoid",
|
|
68
|
+
"sigmoid_difference",
|
|
69
|
+
"sigmoid_product",
|
|
70
|
+
"singleton",
|
|
71
|
+
"trapezoid",
|
|
72
|
+
"triangle",
|
|
73
|
+
"two_sided_gaussian",
|
|
74
|
+
"z_shape",
|
|
75
|
+
]
|
emoge/fuzzy_color/lut.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""`lookup_table`: the strongest color of every 8-bit pixel, worked out once."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from numpy.typing import NDArray
|
|
12
|
+
|
|
13
|
+
from emoge.fuzzy_color.model import ColorModel
|
|
14
|
+
|
|
15
|
+
# The strongest color of every pixel: its index, or its index and degree.
|
|
16
|
+
type Entries = NDArray[np.unsignedinteger | np.void]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def lookup_table(
|
|
20
|
+
model: ColorModel,
|
|
21
|
+
path: str | os.PathLike[str] | None = None,
|
|
22
|
+
*,
|
|
23
|
+
degree: bool = False,
|
|
24
|
+
) -> Entries:
|
|
25
|
+
"""Return `model.classify` of every 8-bit pixel, as `table[red, green, blue]`.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
table = lookup_table(COLIBRI, "colibri.npz") # built and saved, or loaded
|
|
29
|
+
table[image[..., 0], image[..., 1], image[..., 2]] # COLIBRI.classify(image)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
With `path`, the table is loaded from that compressed .npz file, or built
|
|
33
|
+
in seconds and saved there when there is none yet. A file that disagrees
|
|
34
|
+
with the model on a sample of pixels is refused: delete it to build anew.
|
|
35
|
+
|
|
36
|
+
A color takes the smallest unsigned integer that holds `len(colors)`, the
|
|
37
|
+
index of no color: a byte up to 255 colors. With `degree=True` every entry
|
|
38
|
+
also keeps the degree of its color, in steps of 1/255, the byte it takes in
|
|
39
|
+
a file: `table["color"]` and `table["degree"]`.
|
|
40
|
+
"""
|
|
41
|
+
if path is None:
|
|
42
|
+
return _build(model, degree)
|
|
43
|
+
path = Path(path)
|
|
44
|
+
if path.suffix != ".npz":
|
|
45
|
+
path = path.with_name(path.name + ".npz") # as np.savez names it
|
|
46
|
+
if not path.exists():
|
|
47
|
+
table = _build(model, degree)
|
|
48
|
+
_save(path, table)
|
|
49
|
+
return table
|
|
50
|
+
table = _load(path)
|
|
51
|
+
sample = np.arange(0, 256, 17, dtype=np.uint8) # 16 levels a channel
|
|
52
|
+
red, green, blue = np.meshgrid(sample, sample, sample, indexing="ij")
|
|
53
|
+
expected = _entries(model, np.stack([red, green, blue], axis=-1), degree)
|
|
54
|
+
if (
|
|
55
|
+
table.dtype != expected.dtype
|
|
56
|
+
or table.shape != (256, 256, 256)
|
|
57
|
+
or not np.array_equal(table[red, green, blue], expected)
|
|
58
|
+
):
|
|
59
|
+
raise ValueError(f"{path} holds a table of another model or kind")
|
|
60
|
+
return table
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _build(model: ColorModel, degree: bool) -> Entries:
|
|
64
|
+
levels = np.arange(256, dtype=np.uint8)
|
|
65
|
+
green, blue = np.meshgrid(levels, levels, indexing="ij")
|
|
66
|
+
|
|
67
|
+
def level(red: int) -> Entries: # one red level: 65536 pixels
|
|
68
|
+
pixels = np.stack([np.full_like(green, red), green, blue], axis=-1)
|
|
69
|
+
return _entries(model, pixels, degree)
|
|
70
|
+
|
|
71
|
+
# NumPy lets go of the GIL while it computes, so threads share the levels;
|
|
72
|
+
# past 4 of them memory, not the cores, holds the work back.
|
|
73
|
+
with ThreadPoolExecutor(min(4, os.cpu_count() or 1)) as pool:
|
|
74
|
+
return np.stack(list(pool.map(level, range(256))))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _entries(model: ColorModel, pixels: NDArray[np.uint8], degree: bool) -> Entries:
|
|
78
|
+
"""The strongest color of every pixel, and its degree if it is kept."""
|
|
79
|
+
color, color_degree = model.strongest(pixels)
|
|
80
|
+
color = color.astype(np.min_scalar_type(len(model.colors)))
|
|
81
|
+
if not degree:
|
|
82
|
+
return color
|
|
83
|
+
return _join(color, np.round(color_degree * 255.0) / 255.0)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _join(color: Entries, degree: NDArray[np.floating]) -> Entries:
|
|
87
|
+
table = np.empty(
|
|
88
|
+
color.shape, dtype=[("color", color.dtype), ("degree", np.float16)]
|
|
89
|
+
)
|
|
90
|
+
table["color"] = color
|
|
91
|
+
table["degree"] = degree
|
|
92
|
+
return table
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# A file keeps the color and the degree apart, the degree in a byte, which
|
|
96
|
+
# compresses far better than a float16.
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _save(path: Path, table: NDArray[Any]) -> None:
|
|
100
|
+
if table.dtype.names is None:
|
|
101
|
+
np.savez_compressed(path, color=table)
|
|
102
|
+
return
|
|
103
|
+
in_bytes = np.round(table["degree"].astype(np.float32) * 255.0).astype(np.uint8)
|
|
104
|
+
np.savez_compressed(path, color=table["color"], degree=in_bytes)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _load(path: Path) -> Entries:
|
|
108
|
+
with np.load(path) as file:
|
|
109
|
+
if "degree" not in file.files:
|
|
110
|
+
return file["color"]
|
|
111
|
+
return _join(file["color"], file["degree"] / 255.0)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""The mathematics of fuzzy sets as plain NumPy functions; nothing here knows colors.
|
|
2
|
+
|
|
3
|
+
- `membership`: the shapes of fuzzy sets;
|
|
4
|
+
- `norms`: t-norms and s-norms, ways to join degrees.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from emoge.fuzzy_color.math import membership, norms
|
|
8
|
+
|
|
9
|
+
__all__ = ["membership", "norms"]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Membership functions: the shapes of fuzzy sets, as plain NumPy functions.
|
|
2
|
+
|
|
3
|
+
Every function takes an array of values `x` first, then the parameters of its
|
|
4
|
+
shape, and returns the degree of every value: in [0, 1], in the shape of `x`.
|
|
5
|
+
`FuzzySet(function, parameters)` makes a set of one.
|
|
6
|
+
|
|
7
|
+
Parameters that mark places on the axis ascend. Equal neighbours make a
|
|
8
|
+
vertical edge, where the higher degree holds.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import itertools
|
|
14
|
+
import math
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from numpy.typing import NDArray
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _require_ascending(*parameters: float) -> None:
|
|
22
|
+
if not all(map(math.isfinite, parameters)) or list(parameters) != sorted(
|
|
23
|
+
parameters
|
|
24
|
+
):
|
|
25
|
+
raise ValueError(f"parameters must be finite and ascending, got {parameters}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _require_positive(**parameters: float) -> None:
|
|
29
|
+
for name, value in parameters.items():
|
|
30
|
+
if not (math.isfinite(value) and value > 0.0):
|
|
31
|
+
raise ValueError(f"{name} must be positive and finite, got {value}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# --- straight lines -------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def rising(x: NDArray[np.float64], a: float, b: float) -> NDArray[np.float64]:
|
|
38
|
+
"""0 up to `a`, a straight line, 1 from `b` on."""
|
|
39
|
+
_require_ascending(a, b)
|
|
40
|
+
if a == b:
|
|
41
|
+
return (x >= a).astype(np.float64)
|
|
42
|
+
return np.clip((x - a) / (b - a), 0.0, 1.0)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def falling(x: NDArray[np.float64], a: float, b: float) -> NDArray[np.float64]:
|
|
46
|
+
"""1 up to `a`, a straight line, 0 from `b` on."""
|
|
47
|
+
_require_ascending(a, b)
|
|
48
|
+
if a == b:
|
|
49
|
+
return (x <= a).astype(np.float64)
|
|
50
|
+
return np.clip((b - x) / (b - a), 0.0, 1.0)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def triangle(
|
|
54
|
+
x: NDArray[np.float64], a: float, b: float, c: float
|
|
55
|
+
) -> NDArray[np.float64]:
|
|
56
|
+
"""Rises from `a` to the peak at `b`, falls to `c`."""
|
|
57
|
+
_require_ascending(a, b, c)
|
|
58
|
+
return np.minimum(rising(x, a, b), falling(x, b, c))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def trapezoid(
|
|
62
|
+
x: NDArray[np.float64], a: float, b: float, c: float, d: float
|
|
63
|
+
) -> NDArray[np.float64]:
|
|
64
|
+
"""Rises from `a` to `b`, is 1 until `c`, falls to `d`."""
|
|
65
|
+
_require_ascending(a, b, c, d)
|
|
66
|
+
return np.minimum(rising(x, a, b), falling(x, c, d))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def rectangle(x: NDArray[np.float64], a: float, b: float) -> NDArray[np.float64]:
|
|
70
|
+
"""1 on `[a, b]`, 0 elsewhere."""
|
|
71
|
+
return trapezoid(x, a, a, b, b)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def singleton(x: NDArray[np.float64], a: float) -> NDArray[np.float64]:
|
|
75
|
+
"""1 at `a`, 0 elsewhere."""
|
|
76
|
+
return trapezoid(x, a, a, a, a)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def piecewise_linear(
|
|
80
|
+
x: NDArray[np.float64], points: Sequence[tuple[float, float]]
|
|
81
|
+
) -> NDArray[np.float64]:
|
|
82
|
+
"""Straight lines through `(value, degree)` points, flat before and after them.
|
|
83
|
+
|
|
84
|
+
The values strictly ascend.
|
|
85
|
+
"""
|
|
86
|
+
values = [value for value, _ in points]
|
|
87
|
+
degrees = [degree for _, degree in points]
|
|
88
|
+
if not values or any(left >= right for left, right in itertools.pairwise(values)):
|
|
89
|
+
raise ValueError(f"the values of the points must strictly ascend, got {values}")
|
|
90
|
+
if not all(0.0 <= degree <= 1.0 for degree in degrees):
|
|
91
|
+
raise ValueError(f"the degrees of the points must lie in [0, 1], got {degrees}")
|
|
92
|
+
return np.interp(x, values, degrees)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# --- smooth curves --------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def gaussian(
|
|
99
|
+
x: NDArray[np.float64], center: float, sigma: float
|
|
100
|
+
) -> NDArray[np.float64]:
|
|
101
|
+
"""`exp(-(x - center)**2 / (2 * sigma**2))`."""
|
|
102
|
+
_require_positive(sigma=sigma)
|
|
103
|
+
return np.exp(-((x - center) ** 2) / (2.0 * sigma**2))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def two_sided_gaussian(
|
|
107
|
+
x: NDArray[np.float64], center1: float, sigma1: float, center2: float, sigma2: float
|
|
108
|
+
) -> NDArray[np.float64]:
|
|
109
|
+
"""A gaussian up to `center1`, 1 until `center2`, a gaussian after it."""
|
|
110
|
+
_require_positive(sigma1=sigma1, sigma2=sigma2)
|
|
111
|
+
left = np.minimum(x, center1) - center1 # 0 from center1 on
|
|
112
|
+
right = np.maximum(x, center2) - center2 # 0 up to center2
|
|
113
|
+
return np.exp(-(left**2) / (2.0 * sigma1**2) - right**2 / (2.0 * sigma2**2))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def generalized_bell(
|
|
117
|
+
x: NDArray[np.float64], center: float, width: float, slope: float
|
|
118
|
+
) -> NDArray[np.float64]:
|
|
119
|
+
"""`1 / (1 + |(x - center) / width|**(2 * slope))`."""
|
|
120
|
+
_require_positive(width=width, slope=slope)
|
|
121
|
+
return 1.0 / (1.0 + np.abs((x - center) / width) ** (2.0 * slope))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def sigmoid(x: NDArray[np.float64], center: float, slope: float) -> NDArray[np.float64]:
|
|
125
|
+
"""`1 / (1 + exp(-slope * (x - center)))`; a negative slope makes it fall."""
|
|
126
|
+
with np.errstate(over="ignore"): # exp overflows to inf, which gives 0
|
|
127
|
+
return 1.0 / (1.0 + np.exp(-slope * (x - center)))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def sigmoid_difference(
|
|
131
|
+
x: NDArray[np.float64], center1: float, slope1: float, center2: float, slope2: float
|
|
132
|
+
) -> NDArray[np.float64]:
|
|
133
|
+
"""`|sigmoid(center1, slope1) - sigmoid(center2, slope2)|`."""
|
|
134
|
+
return np.abs(sigmoid(x, center1, slope1) - sigmoid(x, center2, slope2))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sigmoid_product(
|
|
138
|
+
x: NDArray[np.float64], center1: float, slope1: float, center2: float, slope2: float
|
|
139
|
+
) -> NDArray[np.float64]:
|
|
140
|
+
"""`sigmoid(center1, slope1) * sigmoid(center2, slope2)`."""
|
|
141
|
+
return sigmoid(x, center1, slope1) * sigmoid(x, center2, slope2)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def s_shape(x: NDArray[np.float64], a: float, b: float) -> NDArray[np.float64]:
|
|
145
|
+
"""Smooth rise from 0 at `a` to 1 at `b`: `2t**2`, then `1 - 2(1 - t)**2`."""
|
|
146
|
+
_require_ascending(a, b)
|
|
147
|
+
if a == b:
|
|
148
|
+
raise ValueError(f"a smooth rise needs a < b, got {a} and {b}")
|
|
149
|
+
t = np.clip((x - a) / (b - a), 0.0, 1.0)
|
|
150
|
+
lower_half = 2.0 * np.minimum(t, 1.0 - t) ** 2
|
|
151
|
+
return np.where(t <= 0.5, lower_half, 1.0 - lower_half)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def z_shape(x: NDArray[np.float64], a: float, b: float) -> NDArray[np.float64]:
|
|
155
|
+
"""Smooth fall from 1 at `a` to 0 at `b`: `1 - s_shape(a, b)`."""
|
|
156
|
+
return 1.0 - s_shape(x, a, b)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def pi_shape(
|
|
160
|
+
x: NDArray[np.float64], a: float, b: float, c: float, d: float
|
|
161
|
+
) -> NDArray[np.float64]:
|
|
162
|
+
"""Smooth rise from `a` to `b`, 1 until `c`, smooth fall to `d`."""
|
|
163
|
+
_require_ascending(a, b, c, d)
|
|
164
|
+
return s_shape(x, a, b) * z_shape(x, c, d)
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Norms: ways to join two degrees into one.
|
|
2
|
+
|
|
3
|
+
A t-norm joins degrees for "and", an s-norm for "or". Every norm takes two
|
|
4
|
+
broadcastable arrays of degrees and returns the joined degrees.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from numpy.typing import NDArray
|
|
13
|
+
|
|
14
|
+
type Norm = Callable[[NDArray[np.float64], NDArray[np.float64]], NDArray[np.float64]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# --- t-norms: "and" -------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def minimum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
21
|
+
"""`min(a, b)`: the Goedel t-norm, the largest of all."""
|
|
22
|
+
return np.minimum(a, b)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def product(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
26
|
+
"""`a * b`: the product t-norm."""
|
|
27
|
+
return a * b
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def bounded_difference(
|
|
31
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
32
|
+
) -> NDArray[np.float64]:
|
|
33
|
+
"""`max(a + b - 1, 0)`: the Lukasiewicz t-norm."""
|
|
34
|
+
return np.maximum(a + b - 1.0, 0.0)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def drastic_product(
|
|
38
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
39
|
+
) -> NDArray[np.float64]:
|
|
40
|
+
"""`b` if `a` is 1, `a` if `b` is 1, else 0: the smallest of all t-norms."""
|
|
41
|
+
return np.where(a == 1.0, b, np.where(b == 1.0, a, 0.0))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def nilpotent_minimum(
|
|
45
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
46
|
+
) -> NDArray[np.float64]:
|
|
47
|
+
"""`min(a, b)` if `a + b > 1`, else 0."""
|
|
48
|
+
return np.where(a + b > 1.0, np.minimum(a, b), 0.0)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def hamacher_product(
|
|
52
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
53
|
+
) -> NDArray[np.float64]:
|
|
54
|
+
"""`a * b / (a + b - a * b)`, and 0 where both are 0."""
|
|
55
|
+
joined = a * b
|
|
56
|
+
divisor = a + b - joined
|
|
57
|
+
return np.divide(joined, divisor, out=np.zeros_like(divisor), where=divisor > 0.0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def einstein_product(
|
|
61
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
62
|
+
) -> NDArray[np.float64]:
|
|
63
|
+
"""`a * b / (2 - (a + b - a * b))`."""
|
|
64
|
+
return a * b / (2.0 - (a + b - a * b))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# --- s-norms: "or" --------------------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def maximum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
71
|
+
"""`max(a, b)`: the Goedel s-norm, the smallest of all."""
|
|
72
|
+
return np.maximum(a, b)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def probabilistic_sum(
|
|
76
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
77
|
+
) -> NDArray[np.float64]:
|
|
78
|
+
"""`a + b - a * b`: the s-norm of the product."""
|
|
79
|
+
return a + b - a * b
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def bounded_sum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
83
|
+
"""`min(a + b, 1)`: the Lukasiewicz s-norm."""
|
|
84
|
+
return np.minimum(a + b, 1.0)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def drastic_sum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
88
|
+
"""`b` if `a` is 0, `a` if `b` is 0, else 1: the largest of all s-norms."""
|
|
89
|
+
return np.where(a == 0.0, b, np.where(b == 0.0, a, 1.0))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def nilpotent_maximum(
|
|
93
|
+
a: NDArray[np.float64], b: NDArray[np.float64]
|
|
94
|
+
) -> NDArray[np.float64]:
|
|
95
|
+
"""`max(a, b)` if `a + b < 1`, else 1."""
|
|
96
|
+
return np.where(a + b < 1.0, np.maximum(a, b), 1.0)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def hamacher_sum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
100
|
+
"""`(a + b - 2ab) / (1 - ab)`, and 1 where both are 1."""
|
|
101
|
+
joined = a * b
|
|
102
|
+
divisor = 1.0 - joined
|
|
103
|
+
return np.divide(
|
|
104
|
+
a + b - 2.0 * joined, divisor, out=np.ones_like(divisor), where=divisor > 0.0
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def einstein_sum(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
109
|
+
"""`(a + b) / (1 + a * b)`."""
|
|
110
|
+
return (a + b) / (1.0 + a * b)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""`ColorModel`: colors as terms joined by a t-norm, one term from every variable."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from numpy.typing import ArrayLike, NDArray
|
|
11
|
+
|
|
12
|
+
from emoge.fuzzy_color.math.norms import Norm, product
|
|
13
|
+
from emoge.fuzzy_color.spaces.rgb import fit_into_rgb, to_float_rgb
|
|
14
|
+
from emoge.fuzzy_color.spaces.space import Space
|
|
15
|
+
from emoge.fuzzy_color.variables import Variable
|
|
16
|
+
|
|
17
|
+
# Pixels worked on at once: bounds the (colors x pixels) array of degrees.
|
|
18
|
+
_PIXELS_PER_BLOCK = 1 << 16
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ColorModel:
|
|
22
|
+
"""A fuzzy color model: families of colors on the channels of a color space.
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
model = ColorModel("toy", HSI, {
|
|
26
|
+
"tint": [hue, saturation.select("pale", "vivid")],
|
|
27
|
+
"gray": [intensity, saturation.select("gray")],
|
|
28
|
+
})
|
|
29
|
+
model.colors # ("red/pale", "red/vivid", ..., "dark", "light")
|
|
30
|
+
model.label([200, 30, 30]) # array('red/vivid')
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
A family is a list of variables on different channels of the space. Its
|
|
34
|
+
colors take one term from every variable, and the degree of a color is the
|
|
35
|
+
degrees of its terms joined by `and_norm`. With the product and partitions,
|
|
36
|
+
the degrees of all colors of a pixel sum to 1. A color is named after its
|
|
37
|
+
terms joined by "/", leaving out a variable of one term; a family of one
|
|
38
|
+
color takes its name.
|
|
39
|
+
|
|
40
|
+
Pixels have shape `(..., 3)`: 8-bit levels or floats in [0, 1].
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
name: str,
|
|
46
|
+
space: Space,
|
|
47
|
+
families: Mapping[str, Sequence[Variable]],
|
|
48
|
+
and_norm: Norm = product,
|
|
49
|
+
) -> None:
|
|
50
|
+
for family, variables in families.items():
|
|
51
|
+
channels = [variable.channel for variable in variables]
|
|
52
|
+
if not variables or len(set(channels)) < len(channels):
|
|
53
|
+
raise ValueError(f"{family!r} needs variables on different channels")
|
|
54
|
+
strangers = [c.name for c in channels if c not in space.channels]
|
|
55
|
+
if strangers:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"{family!r}: {strangers} are not channels of {space.name}"
|
|
58
|
+
)
|
|
59
|
+
colors = tuple(
|
|
60
|
+
color
|
|
61
|
+
for family, variables in families.items()
|
|
62
|
+
for color in _color_names(family, variables)
|
|
63
|
+
)
|
|
64
|
+
if not colors or len(set(colors)) < len(colors):
|
|
65
|
+
raise ValueError(f"{name!r} needs colors that differ, got {colors}")
|
|
66
|
+
self.name = name
|
|
67
|
+
self.space = space
|
|
68
|
+
self.families = {
|
|
69
|
+
family: tuple(variables) for family, variables in families.items()
|
|
70
|
+
}
|
|
71
|
+
self.and_norm = and_norm
|
|
72
|
+
self.colors = colors
|
|
73
|
+
self._colors_then_empty = np.array([*colors, ""]) # index len(colors): none
|
|
74
|
+
|
|
75
|
+
def degrees(self, rgb: ArrayLike) -> NDArray[np.float64]:
|
|
76
|
+
"""Return the degree of the pixels in every color: `(len(colors), *pixels)`."""
|
|
77
|
+
values = self._channel_values(rgb)
|
|
78
|
+
pixel_shape = np.shape(rgb)[:-1]
|
|
79
|
+
blocks = []
|
|
80
|
+
for variables in self.families.values():
|
|
81
|
+
degrees = np.ones((1, *pixel_shape)) # 1 joins as nothing under a t-norm
|
|
82
|
+
for variable in variables:
|
|
83
|
+
term_degrees = variable.degrees(values[variable.channel.name])
|
|
84
|
+
# Every color so far joined with every term of this variable.
|
|
85
|
+
joined = self.and_norm(degrees[:, None], term_degrees[None])
|
|
86
|
+
degrees = joined.reshape(-1, *pixel_shape)
|
|
87
|
+
blocks.append(degrees)
|
|
88
|
+
return np.concatenate(blocks)
|
|
89
|
+
|
|
90
|
+
def classify(self, rgb: ArrayLike) -> NDArray[np.intp]:
|
|
91
|
+
"""Return the index in `colors` of the strongest color of every pixel.
|
|
92
|
+
|
|
93
|
+
A pixel of no color, which a model with gaps between its terms leaves,
|
|
94
|
+
gets `len(colors)`; of equally strong colors the first wins.
|
|
95
|
+
"""
|
|
96
|
+
return self.strongest(rgb)[0]
|
|
97
|
+
|
|
98
|
+
def strongest(self, rgb: ArrayLike) -> tuple[NDArray[np.intp], NDArray[np.float64]]:
|
|
99
|
+
"""Return the strongest color of every pixel as in `classify`, and its degree.
|
|
100
|
+
|
|
101
|
+
A pixel of no color has degree 0.
|
|
102
|
+
"""
|
|
103
|
+
values = self._channel_values(rgb)
|
|
104
|
+
pixel_shape = np.shape(rgb)[:-1]
|
|
105
|
+
best_index = np.full(pixel_shape, len(self.colors), dtype=np.intp)
|
|
106
|
+
best_degree = np.zeros(pixel_shape)
|
|
107
|
+
first_color = 0
|
|
108
|
+
for variables in self.families.values():
|
|
109
|
+
# A t-norm never falls when one of its degrees grows, so the strongest
|
|
110
|
+
# color of a family is made of the strongest term of every variable.
|
|
111
|
+
index = np.zeros(pixel_shape, dtype=np.intp)
|
|
112
|
+
degree = np.ones(pixel_shape)
|
|
113
|
+
for variable in variables:
|
|
114
|
+
term_degrees = variable.degrees(values[variable.channel.name])
|
|
115
|
+
index = index * len(variable.terms) + term_degrees.argmax(axis=0)
|
|
116
|
+
degree = self.and_norm(degree, term_degrees.max(axis=0))
|
|
117
|
+
stronger = degree > best_degree
|
|
118
|
+
best_index = np.where(stronger, first_color + index, best_index)
|
|
119
|
+
best_degree = np.where(stronger, degree, best_degree)
|
|
120
|
+
first_color += math.prod(len(variable.terms) for variable in variables)
|
|
121
|
+
return best_index, best_degree
|
|
122
|
+
|
|
123
|
+
def label(self, rgb: ArrayLike) -> NDArray[np.str_]:
|
|
124
|
+
"""Return the name of the strongest color of every pixel; "" for no color."""
|
|
125
|
+
index = self.classify(rgb)
|
|
126
|
+
return self._colors_then_empty[index.reshape(-1)].reshape(index.shape)
|
|
127
|
+
|
|
128
|
+
def palette(self, image: ArrayLike) -> NDArray[np.float64]:
|
|
129
|
+
"""Return the mean degree of every color over the pixels of an image."""
|
|
130
|
+
pixels = np.asarray(image)
|
|
131
|
+
pixels = pixels.reshape(
|
|
132
|
+
-1, *pixels.shape[-1:]
|
|
133
|
+
) # `degrees` checks the last axis
|
|
134
|
+
if not len(pixels):
|
|
135
|
+
raise ValueError("an image without pixels has no palette")
|
|
136
|
+
totals = np.zeros(len(self.colors))
|
|
137
|
+
for start in range(0, len(pixels), _PIXELS_PER_BLOCK):
|
|
138
|
+
block = pixels[start : start + _PIXELS_PER_BLOCK]
|
|
139
|
+
totals += self.degrees(block).sum(axis=1)
|
|
140
|
+
return totals / len(pixels)
|
|
141
|
+
|
|
142
|
+
def prototypes(self) -> NDArray[np.float64]:
|
|
143
|
+
"""Return a typical RGB color for every color: shape `(len(colors), 3)`.
|
|
144
|
+
|
|
145
|
+
A channel takes the middle of the core of the color's term, or the middle
|
|
146
|
+
of the channel if the family does not describe it. A color too bright for
|
|
147
|
+
RGB is darkened until it fits.
|
|
148
|
+
"""
|
|
149
|
+
middles = {c.name: (c.low + c.high) / 2.0 for c in self.space.channels}
|
|
150
|
+
rows = []
|
|
151
|
+
for variables in self.families.values():
|
|
152
|
+
all_centers = [variable.core_centers() for variable in variables]
|
|
153
|
+
for centers in itertools.product(*all_centers):
|
|
154
|
+
point = dict(middles)
|
|
155
|
+
for variable, center in zip(variables, centers, strict=True):
|
|
156
|
+
point[variable.channel.name] = float(center)
|
|
157
|
+
rows.append([point[channel.name] for channel in self.space.channels])
|
|
158
|
+
return fit_into_rgb(self.space.to_rgb(np.array(rows)))
|
|
159
|
+
|
|
160
|
+
def _channel_values(self, rgb: ArrayLike) -> dict[str, NDArray[np.float64]]:
|
|
161
|
+
"""The values of every channel of the space for the pixels, by name."""
|
|
162
|
+
values = self.space.from_rgb(to_float_rgb(rgb))
|
|
163
|
+
return {c.name: values[..., i] for i, c in enumerate(self.space.channels)}
|
|
164
|
+
|
|
165
|
+
def __repr__(self) -> str:
|
|
166
|
+
sizes = ", ".join(
|
|
167
|
+
f"{math.prod(len(v.terms) for v in variables)} {family}"
|
|
168
|
+
for family, variables in self.families.items()
|
|
169
|
+
)
|
|
170
|
+
return f"ColorModel({self.name!r}, {self.space.name}: {sizes})"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _color_names(family: str, variables: Sequence[Variable]) -> list[str]:
|
|
174
|
+
"""Name every combination of terms, leaving out variables of one term."""
|
|
175
|
+
names = []
|
|
176
|
+
for terms in itertools.product(*(variable.terms for variable in variables)):
|
|
177
|
+
named = [
|
|
178
|
+
term for term, v in zip(terms, variables, strict=True) if len(v.terms) > 1
|
|
179
|
+
]
|
|
180
|
+
names.append("/".join(named) or family)
|
|
181
|
+
return names
|