准备上传
This commit is contained in:
Binary file not shown.
@@ -3,7 +3,17 @@ from typing import Dict, List, Tuple
|
||||
import cv2
|
||||
import numpy as np
|
||||
import logging
|
||||
from pyzbar.pyzbar import decode, ZBarSymbol
|
||||
|
||||
# 尝试延迟引入 pyzbar;在未安装 zbar 运行库的环境下,保证服务可启动,
|
||||
# 后续仅使用自研 EAN-13 解码或返回空结果。
|
||||
try:
|
||||
from pyzbar.pyzbar import decode as _pyzbar_decode, ZBarSymbol as _ZBarSymbol
|
||||
_PYZBAR_AVAILABLE = True
|
||||
except Exception as _e: # ImportError 或 zbar 动态库缺失
|
||||
_PYZBAR_AVAILABLE = False
|
||||
_PYZBAR_IMPORT_ERR = _e
|
||||
_pyzbar_decode = None
|
||||
_ZBarSymbol = None
|
||||
|
||||
|
||||
def _prepare_images(gray: np.ndarray, try_invert: bool, rotations: List[int]) -> List[Tuple[np.ndarray, int, bool]]:
|
||||
@@ -29,7 +39,7 @@ def _prepare_images(gray: np.ndarray, try_invert: bool, rotations: List[int]) ->
|
||||
return images
|
||||
|
||||
|
||||
def _collect_supported_symbols() -> List[ZBarSymbol]:
|
||||
def _collect_supported_symbols() -> List["_ZBarSymbol"]:
|
||||
names = [
|
||||
"EAN13",
|
||||
"EAN8",
|
||||
@@ -42,16 +52,22 @@ def _collect_supported_symbols() -> List[ZBarSymbol]:
|
||||
"ITF",
|
||||
"I25",
|
||||
]
|
||||
symbols: List[ZBarSymbol] = []
|
||||
symbols: List["_ZBarSymbol"] = []
|
||||
if not _PYZBAR_AVAILABLE:
|
||||
return symbols
|
||||
for n in names:
|
||||
if hasattr(ZBarSymbol, n):
|
||||
symbols.append(getattr(ZBarSymbol, n))
|
||||
if hasattr(_ZBarSymbol, n):
|
||||
symbols.append(getattr(_ZBarSymbol, n))
|
||||
# 若列表为空,退回由 zbar 自行决定的默认集合
|
||||
return symbols
|
||||
|
||||
|
||||
def decode_with_pyzbar(image_bgr: np.ndarray, try_invert: bool, rotations: List[int]) -> List[Dict[str, str]]:
|
||||
logger = logging.getLogger("pyzbar_engine")
|
||||
if not _PYZBAR_AVAILABLE or _pyzbar_decode is None:
|
||||
# 缺少 pyzbar/zbar,返回空集合并提示
|
||||
logger.warning("pyzbar 或 zbar 未就绪,已跳过 pyzbar 解码: %s", str(locals().get('_PYZBAR_IMPORT_ERR', ''))) # type: ignore
|
||||
return []
|
||||
# 输入 BGR,转灰度
|
||||
gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
|
||||
results: List[Dict[str, str]] = []
|
||||
@@ -59,7 +75,7 @@ def decode_with_pyzbar(image_bgr: np.ndarray, try_invert: bool, rotations: List[
|
||||
logger.debug("调用 pyzbar: symbols=%d, rotations=%s, try_invert=%s", len(symbols) if symbols else 0, rotations, try_invert)
|
||||
for img, ang, inv in _prepare_images(gray, try_invert=try_invert, rotations=rotations):
|
||||
# pyzbar 要求 8bit 图像
|
||||
decoded = decode(img, symbols=symbols or None)
|
||||
decoded = _pyzbar_decode(img, symbols=symbols or None)
|
||||
for obj in decoded:
|
||||
data = obj.data.decode("utf-8", errors="ignore")
|
||||
typ = obj.type
|
||||
|
||||
Reference in New Issue
Block a user