47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
import os
|
|
import cv2
|
|
import numpy as np
|
|
|
|
|
|
def imread_unicode(path: str, flags: int = cv2.IMREAD_COLOR):
|
|
"""
|
|
Unicode-safe image read. Works around cv2.imread limitations on Windows for non-ASCII paths.
|
|
Returns None if file can't be read or doesn't exist.
|
|
"""
|
|
try:
|
|
if not isinstance(path, (str, bytes)):
|
|
return None
|
|
if not os.path.exists(path):
|
|
return None
|
|
data = np.fromfile(path, dtype=np.uint8)
|
|
if data.size == 0:
|
|
return None
|
|
img = cv2.imdecode(data, flags)
|
|
return img
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def imwrite_unicode(path: str, image) -> bool:
|
|
"""
|
|
Unicode-safe image write. Uses cv2.imencode + buffer.tofile.
|
|
Returns True on success, False otherwise.
|
|
"""
|
|
try:
|
|
# Ensure directory exists
|
|
dir_name = os.path.dirname(path)
|
|
if dir_name and not os.path.exists(dir_name):
|
|
os.makedirs(dir_name, exist_ok=True)
|
|
ext = os.path.splitext(path)[1]
|
|
if not ext:
|
|
ext = '.png'
|
|
path = path + ext
|
|
ok, buf = cv2.imencode(ext, image)
|
|
if not ok:
|
|
return False
|
|
buf.tofile(path)
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|