mullion 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.
- mullion/__init__.py +111 -0
- mullion/background.py +304 -0
- mullion/page.py +146 -0
- mullion/py.typed +0 -0
- mullion/source.py +162 -0
- mullion-0.1.0.dist-info/METADATA +211 -0
- mullion-0.1.0.dist-info/RECORD +9 -0
- mullion-0.1.0.dist-info/WHEEL +4 -0
- mullion-0.1.0.dist-info/licenses/LICENSE +201 -0
mullion/__init__.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Mullion — get an image in correctly, once.
|
|
2
|
+
|
|
3
|
+
A mullion is the upright that divides a window into panes: one stone member,
|
|
4
|
+
every pane set against it. The name is the point of the library. Every
|
|
5
|
+
application that accepts user images opens them somewhere, and if it opens them
|
|
6
|
+
in six places it gets six different answers — which is not a hypothesis.
|
|
7
|
+
Measured across one real codebase, the same transparent PNG came back on a
|
|
8
|
+
**black** rectangle through three upload paths and correctly through four
|
|
9
|
+
others, because each had reached for ``Image.open(...).convert("RGB")``
|
|
10
|
+
independently.
|
|
11
|
+
|
|
12
|
+
Nothing about that failure is loud. The response is a 200, the picture renders,
|
|
13
|
+
the layout is right. It is only *wrong*, in a way a status-code test cannot see
|
|
14
|
+
and a reviewer looking at one image at a time will not catch.
|
|
15
|
+
|
|
16
|
+
So this library is deliberately small, and does the three things that keep
|
|
17
|
+
coming back:
|
|
18
|
+
|
|
19
|
+
:mod:`mullion.source`
|
|
20
|
+
One correct open — EXIF orientation applied, transparency resolved rather
|
|
21
|
+
than dropped — with adapters for the two things callers actually hold:
|
|
22
|
+
``bytes`` from object storage and a filesystem path.
|
|
23
|
+
|
|
24
|
+
:mod:`mullion.background`
|
|
25
|
+
Border-seeded background cleaning, so a near-white product shot sits flush
|
|
26
|
+
on a white surface without a global threshold eating the subject's own
|
|
27
|
+
highlights.
|
|
28
|
+
|
|
29
|
+
:mod:`mullion.page`
|
|
30
|
+
Page geometry and DPI, so "A4 at 300" resolves to pixels that agree with
|
|
31
|
+
the resolution written into the file.
|
|
32
|
+
|
|
33
|
+
Importing this package costs nothing: Pillow is imported inside the functions
|
|
34
|
+
that need it, so a service that only reaches for :mod:`mullion.page`, or that
|
|
35
|
+
imports at module scope and opens images rarely, does not pay for it at start-up.
|
|
36
|
+
|
|
37
|
+
Quick start::
|
|
38
|
+
|
|
39
|
+
from mullion import open_bytes, open_path, clean_background, keeps_alpha
|
|
40
|
+
|
|
41
|
+
image = open_bytes(upload.read()) # RGB, upright, no black box
|
|
42
|
+
avatar = open_path(p, keep_alpha=True) # RGBA preserved
|
|
43
|
+
|
|
44
|
+
mode = "flatten"
|
|
45
|
+
shot = open_path(p, keep_alpha=keeps_alpha(mode))
|
|
46
|
+
cleaned, result = clean_background(shot, mode=mode)
|
|
47
|
+
print(result.message)
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
from .background import (
|
|
53
|
+
DEFAULT_BORDER_COVERAGE,
|
|
54
|
+
DEFAULT_BORDER_TOLERANCE,
|
|
55
|
+
DEFAULT_TOLERANCE,
|
|
56
|
+
BackgroundCleanMode,
|
|
57
|
+
CleanResult,
|
|
58
|
+
clean_background,
|
|
59
|
+
keeps_alpha,
|
|
60
|
+
looks_like_white_background,
|
|
61
|
+
)
|
|
62
|
+
from .page import (
|
|
63
|
+
DEFAULT_DPI,
|
|
64
|
+
MM_PER_INCH,
|
|
65
|
+
NAMED_PAGE_SIZES_MM,
|
|
66
|
+
PageGeometry,
|
|
67
|
+
PageUnit,
|
|
68
|
+
named_page_geometry,
|
|
69
|
+
resolve_page_geometry,
|
|
70
|
+
to_pixels,
|
|
71
|
+
validate_dpi,
|
|
72
|
+
)
|
|
73
|
+
from .source import (
|
|
74
|
+
WHITE,
|
|
75
|
+
Matte,
|
|
76
|
+
flatten_onto,
|
|
77
|
+
has_transparency,
|
|
78
|
+
normalize,
|
|
79
|
+
open_bytes,
|
|
80
|
+
open_path,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
__version__ = "0.1.0"
|
|
84
|
+
|
|
85
|
+
__all__ = [
|
|
86
|
+
"DEFAULT_BORDER_COVERAGE",
|
|
87
|
+
"DEFAULT_BORDER_TOLERANCE",
|
|
88
|
+
"DEFAULT_DPI",
|
|
89
|
+
"DEFAULT_TOLERANCE",
|
|
90
|
+
"MM_PER_INCH",
|
|
91
|
+
"NAMED_PAGE_SIZES_MM",
|
|
92
|
+
"WHITE",
|
|
93
|
+
"BackgroundCleanMode",
|
|
94
|
+
"CleanResult",
|
|
95
|
+
"Matte",
|
|
96
|
+
"PageGeometry",
|
|
97
|
+
"PageUnit",
|
|
98
|
+
"__version__",
|
|
99
|
+
"clean_background",
|
|
100
|
+
"flatten_onto",
|
|
101
|
+
"has_transparency",
|
|
102
|
+
"keeps_alpha",
|
|
103
|
+
"looks_like_white_background",
|
|
104
|
+
"named_page_geometry",
|
|
105
|
+
"normalize",
|
|
106
|
+
"open_bytes",
|
|
107
|
+
"open_path",
|
|
108
|
+
"resolve_page_geometry",
|
|
109
|
+
"to_pixels",
|
|
110
|
+
"validate_dpi",
|
|
111
|
+
]
|
mullion/background.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Clean a near-white background so a subject sits flush on a white surface.
|
|
2
|
+
|
|
3
|
+
The problem is visible on any page or card built from photographed or
|
|
4
|
+
JPEG-compressed source images: a "white" background is rarely ``#FFFFFF``. It
|
|
5
|
+
is ``#FBFBFA`` from a scanner, ``#F7F8F9`` from a phone's auto white balance,
|
|
6
|
+
or a ring of ``#FDFDFD`` compression noise around a cutout. Every one of those
|
|
7
|
+
reads as a faint rectangle around the image — a grid looks gridded, a card
|
|
8
|
+
looks pasted on, exactly where the design wanted neither.
|
|
9
|
+
|
|
10
|
+
Two rules make this reliable rather than destructive.
|
|
11
|
+
|
|
12
|
+
**Only clean what touches the border.** A global "every pixel brighter than
|
|
13
|
+
``threshold`` becomes white" pass is the obvious implementation and it eats the
|
|
14
|
+
subject: the highlight on a white mug, the page of an open book, a bride's
|
|
15
|
+
dress, the sky behind a building. This module flood-fills *inward from the
|
|
16
|
+
edges* instead, so a pixel is only cleaned when there is a continuous
|
|
17
|
+
near-white path from it to the frame. Interior highlights are unreachable and
|
|
18
|
+
are therefore never touched.
|
|
19
|
+
|
|
20
|
+
**Decide per image whether there is a background at all.** An image whose
|
|
21
|
+
border is not near-white — a full-bleed photograph, a dark render — is returned
|
|
22
|
+
untouched rather than partially eaten. ``border_tolerance`` draws that line,
|
|
23
|
+
and :func:`looks_like_white_background` answers it on its own so a caller can
|
|
24
|
+
*report* the decision instead of silently doing nothing.
|
|
25
|
+
|
|
26
|
+
Output modes differ only in what the cleaned region becomes:
|
|
27
|
+
|
|
28
|
+
``flatten`` the region becomes the matte colour — what a white page wants.
|
|
29
|
+
``transparent`` the region becomes alpha 0, for a caller compositing onto a
|
|
30
|
+
non-white surface, or writing a cutout PNG.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from enum import StrEnum
|
|
37
|
+
from typing import TYPE_CHECKING, Any, Protocol, cast
|
|
38
|
+
|
|
39
|
+
from .source import WHITE, Matte
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING: # pragma: no cover - typing only
|
|
42
|
+
from PIL.Image import Image as PILImage
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"DEFAULT_BORDER_COVERAGE",
|
|
46
|
+
"DEFAULT_BORDER_TOLERANCE",
|
|
47
|
+
"DEFAULT_TOLERANCE",
|
|
48
|
+
"BackgroundCleanMode",
|
|
49
|
+
"CleanResult",
|
|
50
|
+
"clean_background",
|
|
51
|
+
"keeps_alpha",
|
|
52
|
+
"looks_like_white_background",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
# A pixel is "near white" when every channel is at or above this value. 240 is
|
|
56
|
+
# deliberately conservative: it clears JPEG noise and scanner grey while
|
|
57
|
+
# leaving genuinely light-grey subject matter (a #E8E8E8 product shadow) alone.
|
|
58
|
+
DEFAULT_TOLERANCE = 240
|
|
59
|
+
|
|
60
|
+
# How near-white the frame itself must be, on average, before this image is
|
|
61
|
+
# treated as having a white background at all.
|
|
62
|
+
DEFAULT_BORDER_TOLERANCE = 232
|
|
63
|
+
|
|
64
|
+
# Fraction of the border that must read as near-white. One dark object running
|
|
65
|
+
# off the edge of an otherwise white product shot should not disqualify it.
|
|
66
|
+
DEFAULT_BORDER_COVERAGE = 0.55
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class BackgroundCleanMode(StrEnum):
|
|
70
|
+
"""What the detected background region becomes."""
|
|
71
|
+
|
|
72
|
+
OFF = "off"
|
|
73
|
+
FLATTEN = "flatten"
|
|
74
|
+
TRANSPARENT = "transparent"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def keeps_alpha(mode: BackgroundCleanMode | str) -> bool:
|
|
78
|
+
"""Whether ``mode`` needs the source image's own alpha channel preserved.
|
|
79
|
+
|
|
80
|
+
Exists so a caller picking an open mode does not have to restate the rule::
|
|
81
|
+
|
|
82
|
+
image = open_path(p, keep_alpha=keeps_alpha(mode))
|
|
83
|
+
cleaned, result = clean_background(image, mode=mode)
|
|
84
|
+
|
|
85
|
+
Getting it wrong is quiet rather than loud: an already-transparent PNG
|
|
86
|
+
opened without ``keep_alpha`` is flattened onto white *before* it is
|
|
87
|
+
cleaned, so its anti-aliased edges keep the white they were blended with
|
|
88
|
+
and the cutout comes back with a pale fringe.
|
|
89
|
+
"""
|
|
90
|
+
return BackgroundCleanMode(str(mode)) is BackgroundCleanMode.TRANSPARENT
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True, slots=True)
|
|
94
|
+
class CleanResult:
|
|
95
|
+
"""What a clean pass did, so callers can report rather than guess."""
|
|
96
|
+
|
|
97
|
+
cleaned: bool
|
|
98
|
+
reason: str
|
|
99
|
+
background_ratio: float
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def message(self) -> str:
|
|
103
|
+
"""A sentence fit to show a user, either way."""
|
|
104
|
+
if self.cleaned:
|
|
105
|
+
return f"Cleaned background ({self.background_ratio:.0%} of the image)."
|
|
106
|
+
return self.reason
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ``Image.load()`` is typed ``PixelAccess | None``, and what a subscript on it
|
|
110
|
+
# yields depends on the image's mode — a triple for ``RGB``, a single level for
|
|
111
|
+
# ``L``. This module reads both, so one return type cannot be honest about
|
|
112
|
+
# either. The two protocols below say which is expected, and the loaders below
|
|
113
|
+
# them establish it: they assert the mode rather than assuming it, so a future
|
|
114
|
+
# caller handing one of these functions the wrong image fails at the assert
|
|
115
|
+
# instead of reading a shape nothing checks. That is the whole reason these are
|
|
116
|
+
# not ``# type: ignore`` comments — an ignore would silence the checker without
|
|
117
|
+
# recording what it was silenced *for*.
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _RgbPixels(Protocol):
|
|
121
|
+
"""Pixel access for an ``RGB`` image."""
|
|
122
|
+
|
|
123
|
+
def __getitem__(self, position: tuple[int, int]) -> tuple[int, int, int]: ...
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class _GreyPixels(Protocol):
|
|
127
|
+
"""Pixel access for an ``L`` image."""
|
|
128
|
+
|
|
129
|
+
def __getitem__(self, position: tuple[int, int]) -> int: ...
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _rgb_pixels(image: PILImage) -> _RgbPixels:
|
|
133
|
+
"""Pixel access for ``image``, which must already be ``RGB``."""
|
|
134
|
+
if image.mode != "RGB":
|
|
135
|
+
raise ValueError(f"expected an RGB image, got mode {image.mode!r}")
|
|
136
|
+
access = image.load()
|
|
137
|
+
if access is None: # pragma: no cover - Pillow only answers None for an unreadable image
|
|
138
|
+
raise ValueError("image has no pixel access")
|
|
139
|
+
return cast("_RgbPixels", access)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _grey_pixels(image: PILImage) -> _GreyPixels:
|
|
143
|
+
"""Pixel access for ``image``, which must already be ``L``."""
|
|
144
|
+
if image.mode != "L":
|
|
145
|
+
raise ValueError(f"expected an L image, got mode {image.mode!r}")
|
|
146
|
+
access = image.load()
|
|
147
|
+
if access is None: # pragma: no cover - Pillow only answers None for an unreadable image
|
|
148
|
+
raise ValueError("image has no pixel access")
|
|
149
|
+
return cast("_GreyPixels", access)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _border_pixels(image: PILImage) -> list[tuple[int, int, int]]:
|
|
153
|
+
"""The one-pixel frame around ``image``, as RGB triples.
|
|
154
|
+
|
|
155
|
+
``image`` must already be ``RGB`` — that is what makes the return type
|
|
156
|
+
true, and ``_rgb_pixels`` enforces it rather than trusting the caller.
|
|
157
|
+
"""
|
|
158
|
+
width, height = image.size
|
|
159
|
+
if width == 0 or height == 0:
|
|
160
|
+
return []
|
|
161
|
+
|
|
162
|
+
pixels = _rgb_pixels(image)
|
|
163
|
+
frame: list[tuple[int, int, int]] = []
|
|
164
|
+
for x in range(width):
|
|
165
|
+
frame.append(pixels[x, 0])
|
|
166
|
+
if height > 1:
|
|
167
|
+
frame.append(pixels[x, height - 1])
|
|
168
|
+
for y in range(1, max(1, height - 1)):
|
|
169
|
+
frame.append(pixels[0, y])
|
|
170
|
+
if width > 1:
|
|
171
|
+
frame.append(pixels[width - 1, y])
|
|
172
|
+
return frame
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def looks_like_white_background(
|
|
176
|
+
image: PILImage | Any,
|
|
177
|
+
*,
|
|
178
|
+
border_tolerance: int = DEFAULT_BORDER_TOLERANCE,
|
|
179
|
+
border_coverage: float = DEFAULT_BORDER_COVERAGE,
|
|
180
|
+
) -> bool:
|
|
181
|
+
"""Whether enough of ``image``'s frame is near-white to call it a background.
|
|
182
|
+
|
|
183
|
+
Asked *before* any pixel is modified. An image that fails it is returned
|
|
184
|
+
untouched — a full-bleed photograph has no background to clean, and
|
|
185
|
+
flood-filling from its corners would eat whatever happens to be light
|
|
186
|
+
there.
|
|
187
|
+
"""
|
|
188
|
+
frame = _border_pixels(image.convert("RGB"))
|
|
189
|
+
if not frame:
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
near_white = sum(1 for pixel in frame if min(pixel) >= border_tolerance)
|
|
193
|
+
return (near_white / len(frame)) >= border_coverage
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _background_mask(image: PILImage, *, tolerance: int) -> tuple[PILImage, float]:
|
|
197
|
+
"""A mask of the edge-connected near-white region, and its area ratio.
|
|
198
|
+
|
|
199
|
+
White in the mask means background. Built by flood-filling a scratch canvas
|
|
200
|
+
inward from every border pixel that is already near-white, so interior
|
|
201
|
+
highlights of the same colour are unreachable and survive.
|
|
202
|
+
"""
|
|
203
|
+
from PIL import ImageDraw
|
|
204
|
+
|
|
205
|
+
width, height = image.size
|
|
206
|
+
greyscale = image.convert("L")
|
|
207
|
+
|
|
208
|
+
# Everything near-white starts as a fill candidate (255); everything else
|
|
209
|
+
# is a wall (0). The flood then decides which candidates are edge-connected.
|
|
210
|
+
candidates = greyscale.point(lambda level: 255 if level >= tolerance else 0)
|
|
211
|
+
|
|
212
|
+
# Pillow's floodfill spreads across equal-ish values, so seeding a third
|
|
213
|
+
# value (128) marks exactly the reached region and leaves unreachable
|
|
214
|
+
# candidates at 255 to be discarded below.
|
|
215
|
+
working = candidates.copy()
|
|
216
|
+
working_pixels = _grey_pixels(working)
|
|
217
|
+
|
|
218
|
+
seeds: list[tuple[int, int]] = []
|
|
219
|
+
for x in range(width):
|
|
220
|
+
seeds.append((x, 0))
|
|
221
|
+
if height > 1:
|
|
222
|
+
seeds.append((x, height - 1))
|
|
223
|
+
for y in range(height):
|
|
224
|
+
seeds.append((0, y))
|
|
225
|
+
if width > 1:
|
|
226
|
+
seeds.append((width - 1, y))
|
|
227
|
+
|
|
228
|
+
for seed in seeds:
|
|
229
|
+
# Read through the access object rather than getpixel: floodfill
|
|
230
|
+
# mutates ``working`` in place and the access object sees it, so this
|
|
231
|
+
# also skips seeds an earlier flood has already swallowed.
|
|
232
|
+
if working_pixels[seed] == 255:
|
|
233
|
+
ImageDraw.floodfill(working, seed, 128, thresh=0)
|
|
234
|
+
|
|
235
|
+
mask = working.point(lambda level: 255 if level == 128 else 0)
|
|
236
|
+
|
|
237
|
+
histogram = mask.histogram()
|
|
238
|
+
background_pixels = histogram[255] if len(histogram) > 255 else 0
|
|
239
|
+
total = width * height
|
|
240
|
+
return mask, (background_pixels / total if total else 0.0)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def clean_background(
|
|
244
|
+
image: PILImage | Any,
|
|
245
|
+
*,
|
|
246
|
+
mode: BackgroundCleanMode | str = BackgroundCleanMode.FLATTEN,
|
|
247
|
+
tolerance: int = DEFAULT_TOLERANCE,
|
|
248
|
+
border_tolerance: int = DEFAULT_BORDER_TOLERANCE,
|
|
249
|
+
border_coverage: float = DEFAULT_BORDER_COVERAGE,
|
|
250
|
+
feather: int = 1,
|
|
251
|
+
matte: Matte = WHITE,
|
|
252
|
+
) -> tuple[PILImage, CleanResult]:
|
|
253
|
+
"""Return ``image`` with its edge-connected near-white background cleaned.
|
|
254
|
+
|
|
255
|
+
``feather`` softens the mask by that many pixels before it is applied,
|
|
256
|
+
which is what removes the grey halo left by anti-aliased cutout edges. Pass
|
|
257
|
+
``0`` for a hard edge.
|
|
258
|
+
|
|
259
|
+
The image is never mutated; when nothing is cleaned it is returned as-is,
|
|
260
|
+
which is what lets a caller pass every image through unconditionally.
|
|
261
|
+
"""
|
|
262
|
+
from PIL import Image, ImageChops, ImageFilter
|
|
263
|
+
|
|
264
|
+
normalized_mode = BackgroundCleanMode(str(mode))
|
|
265
|
+
if normalized_mode is BackgroundCleanMode.OFF:
|
|
266
|
+
return image, CleanResult(False, "Background cleaning is off.", 0.0)
|
|
267
|
+
|
|
268
|
+
if not 0 <= tolerance <= 255:
|
|
269
|
+
raise ValueError("tolerance must be between 0 and 255.")
|
|
270
|
+
if feather < 0:
|
|
271
|
+
raise ValueError("feather must be zero or greater.")
|
|
272
|
+
|
|
273
|
+
rgb = image.convert("RGB")
|
|
274
|
+
if not looks_like_white_background(
|
|
275
|
+
rgb,
|
|
276
|
+
border_tolerance=border_tolerance,
|
|
277
|
+
border_coverage=border_coverage,
|
|
278
|
+
):
|
|
279
|
+
return image, CleanResult(
|
|
280
|
+
False,
|
|
281
|
+
"No white background detected; image left unchanged.",
|
|
282
|
+
0.0,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
mask, background_ratio = _background_mask(rgb, tolerance=tolerance)
|
|
286
|
+
if background_ratio <= 0:
|
|
287
|
+
return image, CleanResult(
|
|
288
|
+
False,
|
|
289
|
+
"No background pixels matched the tolerance.",
|
|
290
|
+
0.0,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
if feather:
|
|
294
|
+
mask = mask.filter(ImageFilter.GaussianBlur(radius=feather))
|
|
295
|
+
|
|
296
|
+
if normalized_mode is BackgroundCleanMode.TRANSPARENT:
|
|
297
|
+
cleaned = image.convert("RGBA")
|
|
298
|
+
# Subtract the background mask from whatever alpha the image already
|
|
299
|
+
# carries, so an already-cut-out PNG is not given its corners back.
|
|
300
|
+
cleaned.putalpha(ImageChops.subtract(cleaned.getchannel("A"), mask))
|
|
301
|
+
else:
|
|
302
|
+
cleaned = Image.composite(Image.new("RGB", rgb.size, matte), rgb, mask)
|
|
303
|
+
|
|
304
|
+
return cleaned, CleanResult(True, "Background cleaned.", background_ratio)
|
mullion/page.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Page size in physical units, and the DPI that makes it mean something.
|
|
2
|
+
|
|
3
|
+
A page is usually specified in **pixels**. That is a complete description for a
|
|
4
|
+
screen and an incomplete one for print: 3000 px is 10 inches at 300 DPI and
|
|
5
|
+
41.7 inches at 72 DPI, and nothing in the file says which unless something
|
|
6
|
+
writes the resolution into it.
|
|
7
|
+
|
|
8
|
+
This module is the other half of that. It lets a caller say what they actually
|
|
9
|
+
mean — "A4 at 300 DPI", "8x10in at 300" — and get back the pixel dimensions
|
|
10
|
+
*together with* the DPI they were derived at, so the two numbers cannot
|
|
11
|
+
disagree. Pass :attr:`PageGeometry.dpi` to your encoder (Pillow takes
|
|
12
|
+
``dpi=(x, y)`` on both PNG and JPEG saves) and the file then says what it is.
|
|
13
|
+
|
|
14
|
+
Nothing here imports Pillow, or anything else. It is arithmetic with the
|
|
15
|
+
constants written down.
|
|
16
|
+
|
|
17
|
+
.. note::
|
|
18
|
+
A PNG stores resolution in its ``pHYs`` chunk as pixels *per metre*, as an
|
|
19
|
+
integer. 300 DPI is 11811.02... px/m, so it is stored as 11811 and reads
|
|
20
|
+
back as 299.9994 rather than 300. That is the format, not a defect; compare
|
|
21
|
+
with a tolerance rather than for equality.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Literal
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"DEFAULT_DPI",
|
|
31
|
+
"MM_PER_INCH",
|
|
32
|
+
"NAMED_PAGE_SIZES_MM",
|
|
33
|
+
"PageGeometry",
|
|
34
|
+
"PageUnit",
|
|
35
|
+
"named_page_geometry",
|
|
36
|
+
"resolve_page_geometry",
|
|
37
|
+
"to_pixels",
|
|
38
|
+
"validate_dpi",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
# 300 DPI is the ordinary floor for photographic print. It is the default here
|
|
42
|
+
# because the page presets are print-shaped (3000x4000 = 10x13.3in at 300).
|
|
43
|
+
DEFAULT_DPI = 300
|
|
44
|
+
|
|
45
|
+
MM_PER_INCH = 25.4
|
|
46
|
+
|
|
47
|
+
PageUnit = Literal["px", "in", "mm"]
|
|
48
|
+
|
|
49
|
+
# Common page sizes in millimetres, for callers that would rather name one.
|
|
50
|
+
NAMED_PAGE_SIZES_MM: dict[str, tuple[float, float]] = {
|
|
51
|
+
"a4": (210.0, 297.0),
|
|
52
|
+
"a3": (297.0, 420.0),
|
|
53
|
+
"a5": (148.0, 210.0),
|
|
54
|
+
"letter": (215.9, 279.4),
|
|
55
|
+
"legal": (215.9, 355.6),
|
|
56
|
+
"tabloid": (279.4, 431.8),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True, slots=True)
|
|
61
|
+
class PageGeometry:
|
|
62
|
+
"""A page's pixel dimensions together with the DPI they were derived at."""
|
|
63
|
+
|
|
64
|
+
width_px: int
|
|
65
|
+
height_px: int
|
|
66
|
+
dpi: int
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def width_inches(self) -> float:
|
|
70
|
+
return self.width_px / self.dpi
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def height_inches(self) -> float:
|
|
74
|
+
return self.height_px / self.dpi
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def description(self) -> str:
|
|
78
|
+
return (
|
|
79
|
+
f"{self.width_px}x{self.height_px}px "
|
|
80
|
+
f"({self.width_inches:.2f}x{self.height_inches:.2f}in at {self.dpi} DPI)"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def to_pixels(value: float, unit: PageUnit, dpi: int) -> int:
|
|
85
|
+
"""Convert ``value`` in ``unit`` to whole pixels at ``dpi``."""
|
|
86
|
+
if value <= 0:
|
|
87
|
+
raise ValueError("Page dimensions must be greater than zero.")
|
|
88
|
+
if unit == "px":
|
|
89
|
+
pixels = value
|
|
90
|
+
elif unit == "in":
|
|
91
|
+
pixels = value * dpi
|
|
92
|
+
elif unit == "mm":
|
|
93
|
+
pixels = (value / MM_PER_INCH) * dpi
|
|
94
|
+
else:
|
|
95
|
+
raise ValueError(f"Unsupported unit '{unit}'. Use 'px', 'in' or 'mm'.")
|
|
96
|
+
|
|
97
|
+
rounded = int(round(pixels))
|
|
98
|
+
if rounded <= 0:
|
|
99
|
+
raise ValueError("Page dimensions rounded to zero pixels; increase the size or DPI.")
|
|
100
|
+
return rounded
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def resolve_page_geometry(
|
|
104
|
+
*,
|
|
105
|
+
page_width: float,
|
|
106
|
+
page_height: float,
|
|
107
|
+
unit: PageUnit = "px",
|
|
108
|
+
dpi: int = DEFAULT_DPI,
|
|
109
|
+
) -> PageGeometry:
|
|
110
|
+
"""Resolve a requested page size to pixels at ``dpi``.
|
|
111
|
+
|
|
112
|
+
With ``unit="px"`` the dimensions pass through unchanged and ``dpi`` only
|
|
113
|
+
decides what gets written into the exported file's metadata — which is the
|
|
114
|
+
backward-compatible path every existing caller takes.
|
|
115
|
+
"""
|
|
116
|
+
validate_dpi(dpi)
|
|
117
|
+
return PageGeometry(
|
|
118
|
+
width_px=to_pixels(page_width, unit, dpi),
|
|
119
|
+
height_px=to_pixels(page_height, unit, dpi),
|
|
120
|
+
dpi=dpi,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def named_page_geometry(name: str, *, dpi: int = DEFAULT_DPI) -> PageGeometry:
|
|
125
|
+
"""Resolve a named page size (``a4``, ``letter``, ...) at ``dpi``."""
|
|
126
|
+
key = name.strip().lower()
|
|
127
|
+
if key not in NAMED_PAGE_SIZES_MM:
|
|
128
|
+
supported = ", ".join(sorted(NAMED_PAGE_SIZES_MM))
|
|
129
|
+
raise ValueError(f"Unknown page size '{name}'. Supported: {supported}.")
|
|
130
|
+
|
|
131
|
+
width_mm, height_mm = NAMED_PAGE_SIZES_MM[key]
|
|
132
|
+
return resolve_page_geometry(
|
|
133
|
+
page_width=width_mm,
|
|
134
|
+
page_height=height_mm,
|
|
135
|
+
unit="mm",
|
|
136
|
+
dpi=dpi,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def validate_dpi(dpi: int) -> int:
|
|
141
|
+
"""Reject a DPI that would make the export meaningless."""
|
|
142
|
+
if dpi <= 0:
|
|
143
|
+
raise ValueError("DPI must be greater than zero.")
|
|
144
|
+
if dpi > 1200:
|
|
145
|
+
raise ValueError("DPI above 1200 is not supported.")
|
|
146
|
+
return int(dpi)
|
mullion/py.typed
ADDED
|
File without changes
|
mullion/source.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""One correct way to open an image, whatever you are holding.
|
|
2
|
+
|
|
3
|
+
Every consumer of a user-supplied image opens it, and the obvious spelling —
|
|
4
|
+
``Image.open(...).convert("RGB")`` — is wrong in two ways that both render as a
|
|
5
|
+
*plausible* picture rather than an error. That is why neither is noticed by a
|
|
6
|
+
status-code test, a screenshot review, or a human looking at one image at a
|
|
7
|
+
time.
|
|
8
|
+
|
|
9
|
+
**Transparency composites against black.** ``convert("RGB")`` on an ``RGBA``
|
|
10
|
+
image drops the alpha channel and keeps whatever RGB sits underneath it. In a
|
|
11
|
+
PNG written by almost every tool, fully transparent pixels carry ``(0, 0, 0)``
|
|
12
|
+
— so a cutout PNG lands on a white page inside a black rectangle. The same is
|
|
13
|
+
true of ``LA`` (greyscale + alpha), and of palette ``P`` images carrying a
|
|
14
|
+
``transparency`` entry, which is what most "small" PNGs are saved as. That last
|
|
15
|
+
one is the one that is easy to miss: the alpha is not in the mode string, it is
|
|
16
|
+
a key in ``info``.
|
|
17
|
+
|
|
18
|
+
**EXIF orientation is ignored.** A photo shot in portrait on a phone is stored
|
|
19
|
+
landscape with an orientation tag telling the viewer to rotate it. Pillow does
|
|
20
|
+
not apply that tag on open, so the image is placed rotated — and because most
|
|
21
|
+
placement is aspect-preserving, a wrongly-rotated image is merely *small and
|
|
22
|
+
sideways* rather than obviously broken.
|
|
23
|
+
|
|
24
|
+
:func:`normalize` fixes both, once. The two adapters exist because callers hold
|
|
25
|
+
different things: a web service holds ``bytes`` it just read from object
|
|
26
|
+
storage, and a desktop or batch tool holds a filesystem path. Neither should
|
|
27
|
+
have to reach for ``PIL`` to get an image in correctly.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
from io import BytesIO
|
|
34
|
+
from typing import TYPE_CHECKING, Any
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING: # pragma: no cover - typing only
|
|
37
|
+
from PIL.Image import Image as PILImage
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"WHITE",
|
|
41
|
+
"Matte",
|
|
42
|
+
"flatten_onto",
|
|
43
|
+
"has_transparency",
|
|
44
|
+
"normalize",
|
|
45
|
+
"open_bytes",
|
|
46
|
+
"open_path",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
# Modes that carry per-pixel transparency. ``P`` is deliberately absent: it
|
|
50
|
+
# carries transparency out of band, in ``info["transparency"]``, and is handled
|
|
51
|
+
# separately in :func:`has_transparency`.
|
|
52
|
+
_ALPHA_MODES = frozenset({"RGBA", "LA", "PA"})
|
|
53
|
+
|
|
54
|
+
#: An RGB triple to composite transparency onto.
|
|
55
|
+
Matte = tuple[int, int, int]
|
|
56
|
+
|
|
57
|
+
#: The default matte. White, because the surfaces that flatten are pages and
|
|
58
|
+
#: cards, which are white.
|
|
59
|
+
WHITE: Matte = (255, 255, 255)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def has_transparency(image: PILImage | Any) -> bool:
|
|
63
|
+
"""Whether ``image`` carries transparency in any of its three shapes.
|
|
64
|
+
|
|
65
|
+
Reads attributes rather than importing Pillow, so this stays usable against
|
|
66
|
+
a stand-in in a test that does not want the dependency.
|
|
67
|
+
"""
|
|
68
|
+
mode = getattr(image, "mode", "")
|
|
69
|
+
if mode in _ALPHA_MODES:
|
|
70
|
+
return True
|
|
71
|
+
return mode == "P" and "transparency" in getattr(image, "info", {})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def flatten_onto(image: PILImage | Any, matte: Matte = WHITE) -> PILImage:
|
|
75
|
+
"""Composite ``image`` onto a solid ``matte``, returning ``RGB``.
|
|
76
|
+
|
|
77
|
+
An image with no transparency is simply converted, so this is safe to call
|
|
78
|
+
unconditionally.
|
|
79
|
+
"""
|
|
80
|
+
from PIL import Image
|
|
81
|
+
|
|
82
|
+
if not has_transparency(image):
|
|
83
|
+
return image.convert("RGB")
|
|
84
|
+
|
|
85
|
+
# Normalize every transparent shape to RGBA first. Converting a P-mode
|
|
86
|
+
# image straight to RGB would discard info["transparency"] silently; going
|
|
87
|
+
# via RGBA is what promotes it to a real alpha channel.
|
|
88
|
+
rgba = image.convert("RGBA")
|
|
89
|
+
background = Image.new("RGBA", rgba.size, (*matte, 255))
|
|
90
|
+
return Image.alpha_composite(background, rgba).convert("RGB")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def normalize(
|
|
94
|
+
image: PILImage | Any,
|
|
95
|
+
*,
|
|
96
|
+
keep_alpha: bool = False,
|
|
97
|
+
matte: Matte = WHITE,
|
|
98
|
+
) -> PILImage:
|
|
99
|
+
"""Return ``image`` upright, with its transparency resolved.
|
|
100
|
+
|
|
101
|
+
``keep_alpha=False`` composites transparency onto ``matte`` and returns
|
|
102
|
+
``RGB`` — what an opaque destination wants, since it has no use for an
|
|
103
|
+
alpha channel and dropping one carelessly is the black-rectangle defect
|
|
104
|
+
this module exists for. ``keep_alpha=True`` returns ``RGBA`` instead, for a
|
|
105
|
+
caller that will composite itself or write a cutout.
|
|
106
|
+
|
|
107
|
+
Always returns a new image; the input is never mutated.
|
|
108
|
+
"""
|
|
109
|
+
from PIL import ImageOps
|
|
110
|
+
|
|
111
|
+
# exif_transpose returns a new image with the tag applied and removed, and
|
|
112
|
+
# is a no-op for a file with no orientation tag. Older Pillow returns None
|
|
113
|
+
# rather than a copy in that case, hence the fallback.
|
|
114
|
+
upright = ImageOps.exif_transpose(image) or image
|
|
115
|
+
|
|
116
|
+
if not has_transparency(upright):
|
|
117
|
+
# Convert unconditionally rather than returning ``upright`` as-is: the
|
|
118
|
+
# adapters below open inside a ``with`` block, so a lazily-loaded image
|
|
119
|
+
# would be read from a file that has since closed. ``convert`` forces
|
|
120
|
+
# the load, which is what makes the return value safe to outlive it.
|
|
121
|
+
return upright.convert("RGBA") if keep_alpha else upright.convert("RGB")
|
|
122
|
+
|
|
123
|
+
if keep_alpha:
|
|
124
|
+
return upright.convert("RGBA")
|
|
125
|
+
return flatten_onto(upright, matte)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def open_bytes(
|
|
129
|
+
data: bytes | bytearray | memoryview,
|
|
130
|
+
*,
|
|
131
|
+
keep_alpha: bool = False,
|
|
132
|
+
matte: Matte = WHITE,
|
|
133
|
+
) -> PILImage:
|
|
134
|
+
"""Open image ``data`` held in memory, normalized.
|
|
135
|
+
|
|
136
|
+
The adapter a web service wants: an upload or an object-storage read hands
|
|
137
|
+
you bytes, and there is no file to point Pillow at.
|
|
138
|
+
|
|
139
|
+
Raises whatever ``Image.open`` raises for data that is not an image —
|
|
140
|
+
callers that treat an unreadable upload as a refusal already handle it.
|
|
141
|
+
"""
|
|
142
|
+
from PIL import Image
|
|
143
|
+
|
|
144
|
+
with Image.open(BytesIO(bytes(data))) as source:
|
|
145
|
+
return normalize(source, keep_alpha=keep_alpha, matte=matte)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def open_path(
|
|
149
|
+
path: str | os.PathLike[str],
|
|
150
|
+
*,
|
|
151
|
+
keep_alpha: bool = False,
|
|
152
|
+
matte: Matte = WHITE,
|
|
153
|
+
) -> PILImage:
|
|
154
|
+
"""Open the image at ``path``, normalized.
|
|
155
|
+
|
|
156
|
+
The adapter a batch or desktop tool wants. The file handle is closed before
|
|
157
|
+
this returns; see :func:`normalize` for why that is safe.
|
|
158
|
+
"""
|
|
159
|
+
from PIL import Image
|
|
160
|
+
|
|
161
|
+
with Image.open(path) as source:
|
|
162
|
+
return normalize(source, keep_alpha=keep_alpha, matte=matte)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mullion
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: One correct way to open an image: EXIF orientation applied, transparency resolved, backgrounds cleaned.
|
|
5
|
+
Project-URL: Homepage, https://github.com/sigrix-io/mullion
|
|
6
|
+
Project-URL: Source, https://github.com/sigrix-io/mullion
|
|
7
|
+
Project-URL: Issues, https://github.com/sigrix-io/mullion/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/sigrix-io/mullion/blob/main/CHANGELOG.md
|
|
9
|
+
Author: Sigrix
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: background-removal,dpi,exif,images,pillow,png,transparency
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Requires-Dist: pillow>=10.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: mypy==2.3.1; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff==0.16.5; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# Mullion
|
|
32
|
+
|
|
33
|
+
**One correct way to open an image.** EXIF orientation applied, transparency
|
|
34
|
+
resolved rather than dropped, and a background cleaner that does not eat the
|
|
35
|
+
subject.
|
|
36
|
+
|
|
37
|
+
A mullion is the upright that divides a window into panes — one stone member,
|
|
38
|
+
every pane set against it. That is the argument of this library: an application
|
|
39
|
+
that opens user images in six places gets six different answers, and the fix is
|
|
40
|
+
one member they all lean on.
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from mullion import open_bytes, open_path
|
|
44
|
+
|
|
45
|
+
image = open_bytes(upload.read()) # RGB, upright, no black rectangle
|
|
46
|
+
avatar = open_path(path, keep_alpha=True) # RGBA preserved
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## The defect this exists for
|
|
50
|
+
|
|
51
|
+
`Image.open(...).convert("RGB")` is the spelling everyone reaches for, and it is
|
|
52
|
+
wrong in two ways that both render as a *plausible* picture rather than an error.
|
|
53
|
+
|
|
54
|
+
**Transparency composites against black.** `convert("RGB")` on an `RGBA` image
|
|
55
|
+
drops the alpha channel and keeps whatever RGB sits underneath. In a PNG written
|
|
56
|
+
by almost every tool, fully transparent pixels carry `(0, 0, 0)` — so a cutout
|
|
57
|
+
lands on a white page inside a black box.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
>>> from PIL import Image
|
|
61
|
+
>>> logo = Image.open("cutout.png") # RGBA, transparent corners
|
|
62
|
+
>>> logo.convert("RGB").getpixel((0, 0))
|
|
63
|
+
(0, 0, 0)
|
|
64
|
+
>>> open_path("cutout.png").getpixel((0, 0))
|
|
65
|
+
(255, 255, 255)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The same is true of `LA` (greyscale + alpha) and of palette `P` images carrying
|
|
69
|
+
a `transparency` entry — which is what most "small" PNGs are saved as, and the
|
|
70
|
+
one that is easiest to miss, because the alpha is not in the mode string at all.
|
|
71
|
+
It is a key in `info`.
|
|
72
|
+
|
|
73
|
+
**EXIF orientation is ignored.** A photo shot in portrait on a phone is stored
|
|
74
|
+
landscape with a tag telling the viewer to rotate it. Pillow does not apply that
|
|
75
|
+
tag on open. Because placement is usually aspect-preserving, a wrongly-rotated
|
|
76
|
+
photo comes out *small and sideways* rather than obviously broken.
|
|
77
|
+
|
|
78
|
+
Neither is loud. The response is a 200, the picture renders, the layout is
|
|
79
|
+
right. A status-code test cannot see it and a reviewer looking at one image at a
|
|
80
|
+
time will not catch it.
|
|
81
|
+
|
|
82
|
+
This is measured, not hypothetical. Across one production codebase the same
|
|
83
|
+
transparent PNG came back on a black rectangle through three upload paths and
|
|
84
|
+
correctly through four others, because each had been written independently.
|
|
85
|
+
|
|
86
|
+
## Install
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
pip install mullion
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Python 3.11+, and Pillow is the only dependency.
|
|
93
|
+
|
|
94
|
+
Importing the package costs nothing — Pillow is imported inside the functions
|
|
95
|
+
that need it, so a service that imports at module scope and opens images rarely
|
|
96
|
+
does not pay for it at start-up.
|
|
97
|
+
|
|
98
|
+
## What it does
|
|
99
|
+
|
|
100
|
+
### `mullion.source` — one correct open
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from mullion import normalize, open_bytes, open_path, has_transparency, flatten_onto
|
|
104
|
+
|
|
105
|
+
normalize(pil_image) # the core: any Image in, upright RGB out
|
|
106
|
+
normalize(pil_image, keep_alpha=True) # RGBA out instead
|
|
107
|
+
normalize(pil_image, matte=(18, 18, 22)) # composite onto something other than white
|
|
108
|
+
|
|
109
|
+
open_bytes(data) # adapter: bytes from object storage or an upload
|
|
110
|
+
open_path("photo.jpg") # adapter: a filesystem path
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`normalize` is the whole rule and the adapters are three lines each. That split
|
|
114
|
+
is deliberate: a path-only API is unusable from a web service holding bytes, and
|
|
115
|
+
a bytes-only API forces a batch tool to read every file into memory first.
|
|
116
|
+
|
|
117
|
+
`keep_alpha=False` composites transparency onto `matte` and returns `RGB` — what
|
|
118
|
+
an opaque destination wants. `keep_alpha=True` returns `RGBA`, for a caller that
|
|
119
|
+
will composite itself or write a cutout. Neither mutates the input.
|
|
120
|
+
|
|
121
|
+
### `mullion.background` — clean a near-white background
|
|
122
|
+
|
|
123
|
+
A "white" background is rarely `#FFFFFF`. It is `#FBFBFA` from a scanner,
|
|
124
|
+
`#F7F8F9` from a phone's auto white balance, or a ring of `#FDFDFD` compression
|
|
125
|
+
noise around a cutout. Each reads as a faint rectangle around the image.
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from mullion import clean_background, keeps_alpha
|
|
129
|
+
|
|
130
|
+
mode = "flatten" # or "transparent", or "off"
|
|
131
|
+
image = open_path(path, keep_alpha=keeps_alpha(mode))
|
|
132
|
+
cleaned, result = clean_background(image, mode=mode)
|
|
133
|
+
|
|
134
|
+
print(result.message)
|
|
135
|
+
# Cleaned background (63% of the image).
|
|
136
|
+
# ...or: No white background detected; image left unchanged.
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Two rules make this safe to run over everything:
|
|
140
|
+
|
|
141
|
+
- **Only what touches the border is cleaned.** A global "brighter than
|
|
142
|
+
*threshold* becomes white" pass is the obvious implementation and it eats the
|
|
143
|
+
subject — the highlight on a white mug, the page of an open book, a bride's
|
|
144
|
+
dress, the sky behind a building. This flood-fills *inward from the edges*, so
|
|
145
|
+
a pixel is cleaned only when there is a continuous near-white path from it to
|
|
146
|
+
the frame. Interior highlights are unreachable and survive.
|
|
147
|
+
- **Each image decides whether it has a background at all.** An image whose
|
|
148
|
+
border is not near-white — a full-bleed photograph, a dark render — comes back
|
|
149
|
+
untouched rather than partly eaten, and `result` says so. Ask
|
|
150
|
+
`looks_like_white_background()` directly if you want the verdict without the
|
|
151
|
+
work.
|
|
152
|
+
|
|
153
|
+
There is deliberately no `open_and_clean` convenience. It would have to restate
|
|
154
|
+
every keyword argument of both halves, and `keeps_alpha()` already names the one
|
|
155
|
+
coupling between them — opening without it flattens an existing cutout onto
|
|
156
|
+
white *before* cleaning, which leaves a pale fringe on the anti-aliased edges.
|
|
157
|
+
|
|
158
|
+
### `mullion.page` — page geometry and DPI
|
|
159
|
+
|
|
160
|
+
3000 px is 10 inches at 300 DPI and 41.7 inches at 72. Nothing in a file says
|
|
161
|
+
which unless something writes the resolution into it.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from mullion import named_page_geometry, resolve_page_geometry
|
|
165
|
+
|
|
166
|
+
page = named_page_geometry("a4", dpi=300)
|
|
167
|
+
page.description # '2480x3508px (8.27x11.69in at 300 DPI)'
|
|
168
|
+
|
|
169
|
+
page = resolve_page_geometry(page_width=8, page_height=10, unit="in", dpi=300)
|
|
170
|
+
canvas = Image.new("RGB", (page.width_px, page.height_px), "white")
|
|
171
|
+
canvas.save("out.png", dpi=(page.dpi, page.dpi))
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The pixels and the DPI travel together, so the two cannot disagree. `a4`, `a3`,
|
|
175
|
+
`a5`, `letter`, `legal` and `tabloid` are named; anything else is `px`, `in` or
|
|
176
|
+
`mm`. This module imports nothing at all — it is arithmetic with the constants
|
|
177
|
+
written down.
|
|
178
|
+
|
|
179
|
+
> A PNG stores resolution in its `pHYs` chunk as pixels *per metre*, as an
|
|
180
|
+
> integer. 300 DPI is 11811.02… px/m, so it is stored as 11811 and reads back as
|
|
181
|
+
> 299.9994. That is the format, not a defect — compare with a tolerance.
|
|
182
|
+
|
|
183
|
+
## What it is not
|
|
184
|
+
|
|
185
|
+
Not a general imaging toolkit. Pillow already is one, and this library is a thin
|
|
186
|
+
correctness layer over it, not a wrapper around it — you get a real
|
|
187
|
+
`PIL.Image.Image` back and do whatever you like with it.
|
|
188
|
+
|
|
189
|
+
Specifically out of scope: resizing and cropping (`ImageOps.fit` and friends
|
|
190
|
+
already do this well), format conversion, colour management, subject-aware or
|
|
191
|
+
model-based background removal, and laying multiple images out on a page. That
|
|
192
|
+
last one is where the line falls: **this library handles one image; composing
|
|
193
|
+
several is the application's job.**
|
|
194
|
+
|
|
195
|
+
## Versioning
|
|
196
|
+
|
|
197
|
+
Pre-1.0. Nothing is stable, and any `0.x` release may break any other — see
|
|
198
|
+
[VERSIONING.md](VERSIONING.md), which is blunt about what that means. If you are
|
|
199
|
+
building on `0.x`, please [open an issue](../../issues) saying so; the practical
|
|
200
|
+
difference between an announced breaking change and a surprising one is knowing
|
|
201
|
+
somebody is out there.
|
|
202
|
+
|
|
203
|
+
## Contributing
|
|
204
|
+
|
|
205
|
+
[CONTRIBUTING.md](CONTRIBUTING.md) is candid about what a small team can promise.
|
|
206
|
+
Security findings go to **security@sigrix.io** and never to a public issue —
|
|
207
|
+
[SECURITY.md](SECURITY.md).
|
|
208
|
+
|
|
209
|
+
## Licence
|
|
210
|
+
|
|
211
|
+
[Apache-2.0](LICENSE).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
mullion/__init__.py,sha256=QCt-nnv_nvlOtEu27gfLNhtnrOgJElvIYb74HzHfDgU,3293
|
|
2
|
+
mullion/background.py,sha256=NQXI5EpiAyXLwOsEVSzmnzPJrzvnfVwmQr5A-TXK1nk,11677
|
|
3
|
+
mullion/page.py,sha256=F2IKoc0lByhrNmmAd23Jhvgs63S8VWXk-q7lK873Zps,4628
|
|
4
|
+
mullion/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
mullion/source.py,sha256=0WMTynEsOIWnXGDjrJTLcs_XNtORsnuj78Tems5coDA,6127
|
|
6
|
+
mullion-0.1.0.dist-info/METADATA,sha256=3geLAR41hnnNkaVmrdALvRB7z50ZYaVt2g1CvH_G5TY,8975
|
|
7
|
+
mullion-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
8
|
+
mullion-0.1.0.dist-info/licenses/LICENSE,sha256=oHcgULuYGIbHR4QEnAgN4_coCdJLwrsNUQ6_TGdOHEk,11336
|
|
9
|
+
mullion-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Sigrix
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|