Skip to main content

OpenCV 轻量扩展(Unicode 路径/HALCON 缩放/形状匹配),可选 UNet 分割训练与推理

Project description

ydl2

ydl2 是对 OpenCV 的轻量补充:解决 Windows 中文路径 读写问题,提供与 HALCON 语义一致的灰度缩放算子,以及基于 HALCON 的形状模板匹配封装。

安装

# 核心(轻量,仅 numpy + opencv):中文路径、HALCON 缩放、形状匹配
pip install ydl2

# 额外解锁 UNet 分割训练与推理(会安装 torch 等)
pip install ydl2[cnn]

# 再额外需要 ONNX 导出/推理时
pip install "ydl2[cnn,cnn-onnx]"

pip install ydl2 与现在一致,只有 HALCON / OpenCV 相关功能;只有 pip install ydl2[cnn] 之后,下方的 ydl2.cnn(UNet 训练/推理)才可用。

快速使用

Unicode 路径 & 灰度缩放

import ydl2

# Unicode 路径读写(Windows 中文路径)
img = ydl2.imread(r"D:\图片\测试.png")
ydl2.imwrite(r"D:\图片\输出.png", img)

# HALCON 等价算子
stretched = ydl2.scale_image_max(img)
inverted  = ydl2.scale_image(img, -1.0, 255.0)
mapped    = ydl2.scale_image_range(img, 100, 200)

形状模板匹配

import ydl2
import cv2

# 加载模板(只需一次)
model = ydl2.read_shape_model(r"model.yyds")

# 读图并创建图像句柄(首次)
mat = cv2.imread(r"image.jpg")
b, g, r = cv2.split(mat)
handle = ydl2.any_to_tiyoo(r, g, b)

# 匹配
results = ydl2.find_shape_model(handle, model)
for res in results:
    print(res['row'], res['col'], res['score'])

# 后续帧原地更新(零内存分配)
handle = ydl2.any_to_tiyoo(r, g, b, handle=handle)

# 释放
ydl2.clear_image(handle)
ydl2.clear_shape_model(model)

API

函数 说明
imread / imwrite / imshow 支持中文路径的读写与显示
scale_image_max 每通道 min/max 拉伸到 0–255
scale_image g' = g * Mult + Add
scale_image_range 区间线性映射
any_to_tiyoo numpy 数组 → Halcon 图像句柄(创建或原地更新)
tiyoo_to_any Halcon 图像句柄 → numpy 数组
read_image / write_image / clear_image Halcon 图像文件读写与释放
read_shape_model / clear_shape_model 加载 / 释放 Halcon 模板文件
find_shape_model 形状模板匹配,返回 [{'row', 'col', 'angle', 'score'}]

分割(CNN):UNet 训练与推理

ydl2.cnn 提供 YOLO 风格的极简分割接口(基于 PyTorch + segmentation-models-pytorch 的 UNet)。 需先安装 pip install ydl2[cnn];未安装时导入会给出中文安装提示,不影响核心包。

训练

from ydl2.cnn import Seg

# 用配置文件训练(配置写法见 train-x 的 configs/segmentation/*.yaml)
Seg("smp_unet_xray_defect_fast.yaml").train()

# 断点续训
Seg("cfg.yaml").train(resume="work_dir/checkpoints/last.pth")

训练已内置深度优化:AMP(bf16/fp16)、channels_last、梯度累积、LR 预热、 权重 EMA、CUDA 预取、内存缓存、GPU 端流式验证指标等(可在配置的 runner/hooks 中开关)。

推理

from ydl2.cnn import Seg

m = Seg("best.pth", config="cfg.yaml", device="cuda")
m.warmup()                              # 预热,消除首图冷启动

mask = m.predict("a.png")               # 传路径或 numpy 数组,返回 mask
vis, mask = m.predict("a.png", visualize=True)   # 叠加可视化
masks = m.predict_batch(["a.png", "b.png"])      # 批量推理

m.release()                             # 释放显存/上下文

推理已启用 channels_last、inference_mode、autocast(可选 FP16)、GPU 端最近邻还原尺寸等优化。

预热 / 保温 / 释放

针对“进程常驻但久未推理后,第一张图明显变慢(GPU 空闲自动降频)”的工业场景:

m.warmup(n=3)                # 预热:用真实输入尺寸预跑,触发 cudnn 自整定与显存预热

# 保温:低功耗脉冲(默认)
m.keep_warm(True, mode="pulse", interval=30)
# 保温:锁频(首图最快、功耗较高,需要管理员权限锁 GPU 时钟)
m.keep_warm(True, mode="lock")
m.keep_warm(False)           # 关闭保温

m.release()                  # 停止保温线程并释放资源;也支持 with Seg(...) as m:

保温设计要点:

  • 保温线程与推理共享同一把锁,脉冲用“非阻塞拿锁”,真实推理在跑时直接跳过本次脉冲, 绝不阻塞或拖慢正常工业检测推理;
  • 刚推理过的活跃期内不脉冲,省电;
  • 功耗权衡:
    • pulse(默认):每 interval 秒一次极短前向,平均增量功耗很小;极长空闲后首图可能仍略慢;
    • lock:用 nvidia-smi 把 GPU 时钟钉在高位,首图最快,但空闲功耗明显上升;锁频失败(无权限/不支持)会自动回退为高频脉冲。

依赖

  • Python >= 3.8
  • numpy >= 1.21
  • opencv-python >= 4.6
  • 分割功能(可选 [cnn]):torch >= 2.0、torchvision、segmentation-models-pytorch、pyyaml、addict、tqdm、pillow
  • ONNX(可选 [cnn-onnx]):onnx、onnxruntime

链接

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ydl2-0.2.0.tar.gz (89.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ydl2-0.2.0-py3-none-any.whl (117.5 kB view details)

Uploaded Python 3

File details

Details for the file ydl2-0.2.0.tar.gz.

File metadata

  • Download URL: ydl2-0.2.0.tar.gz
  • Upload date:
  • Size: 89.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.6

File hashes

Hashes for ydl2-0.2.0.tar.gz
Algorithm Hash digest
SHA256 e0ebc49e5e0403f79239be6c02b0f617682c4290f40877822cb7d51f286aace6
MD5 97ff223231ac4420c16de9d6aa4bedae
BLAKE2b-256 d3a5212c3385a86a47e5650d039c89224113eddaa484f7c0a59e4d82050c876e

See more details on using hashes here.

File details

Details for the file ydl2-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: ydl2-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 117.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.6

File hashes

Hashes for ydl2-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c30b3dbce5b1a8f73c7c800c5fc8ca4837a9635f283f91a04c22206e24859357
MD5 3abbb0778edc33a20294957eab090899
BLAKE2b-256 f0207b47032a403981c0f1b979817406f46313280e0b4ebb5d3c500dae4a7e4c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page