Files

33 lines
851 B
Python

"""Unicode-safe image read/write.
``cv2.imread``/``cv2.imwrite`` mishandle non-ASCII paths on Windows. These
helpers go through ``np.fromfile``/``ndarray.tofile`` + ``imdecode``/``imencode``
so paths with Cyrillic (etc.) work regardless of the system locale.
"""
from __future__ import annotations
import os
import cv2
import numpy as np
def imread_unicode(path: str) -> np.ndarray | None:
try:
data = np.fromfile(path, dtype=np.uint8)
except OSError:
return None
if data.size == 0:
return None
return cv2.imdecode(data, cv2.IMREAD_COLOR)
def imwrite_unicode(path: str, image: np.ndarray, params: list[int] | None = None) -> bool:
ext = os.path.splitext(path)[1] or ".jpg"
ok, buf = cv2.imencode(ext, image, params or [])
if not ok:
return False
buf.tofile(path)
return True