Files
PartsInquiry/backend/txm/app/io_utils.py
2025-09-27 22:57:59 +08:00

40 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Optional
import os
import logging
import numpy as np
import cv2
def read_image_bgr(path: str) -> Optional[np.ndarray]:
"""读取图片为 BGR兼容中文/非 ASCII 路径)。
优先使用 np.fromfile + cv2.imdecode 规避 Windows 路径编码问题,
若失败再回退到 cv2.imread。
"""
logger = logging.getLogger(__name__)
if not path:
logger.warning("read_image_bgr 收到空路径")
return None
# 优先使用 fromfile 方案,处理中文路径
try:
data = np.fromfile(path, dtype=np.uint8)
if data.size > 0:
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
if img is not None:
logger.debug("read_image_bgr 使用 fromfile 解码成功: %s", path)
return img
except Exception as e:
logger.exception("read_image_bgr fromfile 失败: %s", e)
# 回退到 imread
try:
img = cv2.imread(path, cv2.IMREAD_COLOR)
if img is None:
logger.warning("read_image_bgr imread 返回 None: %s", path)
return img
except Exception as e:
logger.exception("read_image_bgr imread 异常: %s", e)
return None