基于 OpenCV 的 Python 图色库,方法命名对齐 ascript: 找色 / 比色 / 颜色数量 / 找图 / 边缘检测 / 文字识别 。适合给 uiautomator2 等自动化框架配上"看图、认字"的能力。
图片想怎么传都行: ndarray / 文件路径 / Pillow Image / 返回图片的函数 。
注册一次截图回调,之后所有方法都不用再传 image 。
只做图像处理, 不含设备截图与点击 (这两件事交给回调,库不绑定任何框架)。
Python ≥ 3.9 · MIT · 版本 0.5.4
仓库:
PyPI:
[ocr] 会装 rapidocr>=3.9, 0 且能刷新画面时重试到命中或超时。
Point 支持 p.x / p.y / p[0] / p.as_dict() 。
2. CompareColors — 比色
校验 固定绝对坐标 上的颜色是否符合预期(不搜索位置)。颜色串必须是绝对坐标 "x,y,#RRGGBB|..." 。
sim 是整体相似度:通过点数 / 总点数 ≥ sim 才算成功。 bitmap 是 image 的兼容别名。
colors 支持 | 分隔多色(并集,同一像素只计一次),也支持偏色串;带偏色时 sim 失效(与 ascript 一致)。
调试图: draw_mode=1 命中白/其余黑, draw_mode=2 黑底保留命中原色。
4. FindImages — 找图(模板匹配)
公共参数: (part_img, rect=None, confidence=0.1, rgb=False, image=None, ori=2, scale_range=None) 。
part_img :模板,可为 ndarray、路径、 Path ,或它们的列表(多图搜索,结果带 index )。
confidence :阈值。模板 必须从目标截图同源裁切 才能接近 1.0;跨来源素材分数偏低,需降低阈值。
scale_range=[min, max] :多尺度搜索(约 15 步长,含 1.0),用于跨分辨率。透明 PNG 的 alpha 会作为 mask。
SIFT 匹配( find_sift / find_all_sift ) :用 SIFT 特征 + RANSAC 单应矩阵定位, 天然尺度/旋转不变 ——模板 50×50 匹配截图里 100×100 的目标不用传 scale_range :
适合纹理丰富的图(图标细节、商品图、场景); confidence 是可信度(内点比例×数量加权),建议 0.3~0.5 起调。
简单纯色块/几何图形 没有足够特征点,会自动回退模板匹配(此时 scale_range 生效),保证兼容。
同一图案在图上出现多次且完全相同时 SIFT 难区分,也可能回退模板匹配;不同图案各自匹配则正常返回 index 。
返回 dict: {"rect": [x,y,x1,y1], "center_x":.., "center_y":.., "confidence":.., "index":..} 。
5. Canny — 边缘检测 + 轮廓过滤
构造参数: low_threshold=50, high_threshold=150, mode=RETR_EXTERNAL, draw=DRAW_ALL, desc=False, left_range=None, top_range=None, width_range=None, height_range=None, blur=0, min_area=0 。
draw : DRAW_NONE=0 不绘制 / DRAW_ALL=1 画轮廓 / DRAW_RECT=2 外接矩形 / DRAW_RECT_FILL=3 填充矩形; desc=True 附注文字。
left/top/width/height_range : [min, max] 过滤轮廓; blur 高斯核(奇数,0 不模糊)。
run(image, rect=None) 返回 CannyResult(image, data, contours, edges) ; data 每项含 x/y/width/height/area/perimeter/points 。
函数式入口: canny(img, draw=Canny.DRAW_RECT) 。
6. Ocr — 文字识别便捷方法(RapidOCR)
需安装 [ocr] 。底层统一用 RapidOCR, text 支持正则。
结果 dict: {"text", "rect": [x,y,x1,y1], "center_x", "center_y", "confidence"} 。
点击回调: Ocr.set_clicker(fn) 全局注册一次,或每次传 clicker=lambda x, y: ... 。截图与点击都注册后, Ocr.click("登录") 、 Ocr.wait_click("登录成功", timeout=15) 都无需再传 image 。
引擎参数可用 imgcolor.configure_engine({"Det.unclip_ratio": 2.0}) 调整(默认即 2.0,改善两字短文本漏检),传 None 恢复默认并重建引擎——一般无需改动。
7. OcrX + FontLib — 点阵字库识别(无需 RapidOCR)
适合颜色固定、字体明确的数字/图标识别(如金币数量)。用本库 JSON 字库(ascript 的 font.t 是私有格式,无法直接读)。
OcrX.find_all(font_lib, rect=None, region=0.9, image=None, detail=False, scales=(1.0,), ...) 。
FontLib.load(path) 加载字库; make_font_lib(samples, path, image=...) 批量制作。
binarize(image, color=None, diff=0.9, threshold=None) 二值化,可单独使用。
as_image / read_image / from_rgb / parse_points / parse_color_spec / color_mask / crop 均已导出,可按需组合。例如 color_mask(img_or_path, parse_color_spec("#FF0000")) 直接拿布尔掩码。
The full story
This article is one source in a clustered incident — the cluster page carries the summary, timeline and every other outlet covering it.
