mirror of
https://github.com/python-pillow/Pillow.git
synced 2025-01-26 01:04:29 +03:00
Merge pull request #7641 from hugovk/optimise-imagemode
Optimise `ImageMode.getmode` using `functools.lru_cache`
This commit is contained in:
commit
1e8bad805e
|
@ -15,9 +15,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
# mode descriptor cache
|
||||
_modes = None
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class ModeDescriptor:
|
||||
|
@ -41,14 +39,13 @@ class ModeDescriptor:
|
|||
return self.mode
|
||||
|
||||
|
||||
@lru_cache
|
||||
def getmode(mode: str) -> ModeDescriptor:
|
||||
"""Gets a mode descriptor for the given mode."""
|
||||
global _modes
|
||||
if not _modes:
|
||||
# initialize mode cache
|
||||
modes = {}
|
||||
endian = "<" if sys.byteorder == "little" else ">"
|
||||
for m, (basemode, basetype, bands, typestr) in {
|
||||
|
||||
modes = {
|
||||
# core modes
|
||||
# Bits need to be extended to bytes
|
||||
"1": ("L", "L", ("1",), "|b1"),
|
||||
|
@ -72,10 +69,12 @@ def getmode(mode: str) -> ModeDescriptor:
|
|||
"LA": ("L", "L", ("L", "A"), "|u1"),
|
||||
"La": ("L", "L", ("L", "a"), "|u1"),
|
||||
"PA": ("RGB", "L", ("P", "A"), "|u1"),
|
||||
}.items():
|
||||
modes[m] = ModeDescriptor(m, bands, basemode, basetype, typestr)
|
||||
# mapping modes
|
||||
for i16mode, typestr in {
|
||||
}
|
||||
if mode in modes:
|
||||
base_mode, base_type, bands, type_str = modes[mode]
|
||||
return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
|
||||
|
||||
mapping_modes = {
|
||||
# I;16 == I;16L, and I;32 == I;32L
|
||||
"I;16": "<u2",
|
||||
"I;16S": "<i2",
|
||||
|
@ -91,8 +90,7 @@ def getmode(mode: str) -> ModeDescriptor:
|
|||
"I;32S": "<i4",
|
||||
"I;32BS": ">i4",
|
||||
"I;32LS": "<i4",
|
||||
}.items():
|
||||
modes[i16mode] = ModeDescriptor(i16mode, ("I",), "L", "L", typestr)
|
||||
# set global mode cache atomically
|
||||
_modes = modes
|
||||
return _modes[mode]
|
||||
}
|
||||
|
||||
type_str = mapping_modes[mode]
|
||||
return ModeDescriptor(mode, ("I",), "L", "L", type_str)
|
||||
|
|
Loading…
Reference in New Issue
Block a user