imgcolor 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- imgcolor-0.5.0/.gitignore +28 -0
- imgcolor-0.5.0/PKG-INFO +260 -0
- imgcolor-0.5.0/README.md +239 -0
- imgcolor-0.5.0/examples/1.png +0 -0
- imgcolor-0.5.0/examples/image.png +0 -0
- imgcolor-0.5.0/examples//347/244/272/344/276/213_OCR/346/226/207/345/255/227/350/257/206/345/210/253.py +58 -0
- imgcolor-0.5.0/examples//347/244/272/344/276/213_/345/277/253/351/200/237/344/270/212/346/211/213.py +156 -0
- imgcolor-0.5.0/pyproject.toml +42 -0
- imgcolor-0.5.0/src/imgcolor/__init__.py +75 -0
- imgcolor-0.5.0/src/imgcolor/_core.py +406 -0
- imgcolor-0.5.0/src/imgcolor/canny.py +167 -0
- imgcolor-0.5.0/src/imgcolor/colors.py +100 -0
- imgcolor-0.5.0/src/imgcolor/comparecolors.py +92 -0
- imgcolor-0.5.0/src/imgcolor/findcolors.py +193 -0
- imgcolor-0.5.0/src/imgcolor/findimages.py +305 -0
- imgcolor-0.5.0/src/imgcolor/fontlib.py +213 -0
- imgcolor-0.5.0/src/imgcolor/ocrx.py +305 -0
- imgcolor-0.5.0/src/imgcolor/rapidocr_engine.py +227 -0
- imgcolor-0.5.0/tests/_helpers.py +71 -0
- imgcolor-0.5.0/tests/conftest.py +10 -0
- imgcolor-0.5.0/tests/test_canny.py +66 -0
- imgcolor-0.5.0/tests/test_colors.py +65 -0
- imgcolor-0.5.0/tests/test_comparecolors.py +93 -0
- imgcolor-0.5.0/tests/test_findcolors.py +137 -0
- imgcolor-0.5.0/tests/test_findimages.py +160 -0
- imgcolor-0.5.0/tests/test_image_inputs.py +321 -0
- imgcolor-0.5.0/tests/test_integration.py +65 -0
- imgcolor-0.5.0/tests/test_ocr_rapidocr.py +267 -0
- imgcolor-0.5.0/tests/test_ocrx.py +109 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Python 缓存与编译产物
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
*.egg
|
|
6
|
+
.pytest_cache/
|
|
7
|
+
.mypy_cache/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
|
|
10
|
+
# 虚拟环境
|
|
11
|
+
.venv/
|
|
12
|
+
venv/
|
|
13
|
+
env/
|
|
14
|
+
|
|
15
|
+
# 构建产物(whl/sdist 由 CI 产出,不入库)
|
|
16
|
+
dist/
|
|
17
|
+
build/
|
|
18
|
+
*.whl
|
|
19
|
+
*.tar.gz
|
|
20
|
+
|
|
21
|
+
# 编辑器与系统
|
|
22
|
+
.vscode/
|
|
23
|
+
.idea/
|
|
24
|
+
.DS_Store
|
|
25
|
+
Thumbs.db
|
|
26
|
+
|
|
27
|
+
# 日志
|
|
28
|
+
*.log
|
imgcolor-0.5.0/PKG-INFO
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: imgcolor
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: 基于 OpenCV 的 Python 图色库:多点找色、找图、边缘检测、点阵字库、RapidOCR 文字识别便捷方法(支持图片路径与 Pillow Image)
|
|
5
|
+
Project-URL: Homepage, https://www.ascript.cn/docs/android/api/screen/findcolors/
|
|
6
|
+
Author: 岳士太
|
|
7
|
+
License: MIT
|
|
8
|
+
Keywords: opencv,uiautomator2,图色,找色,比色,点阵字库
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Requires-Dist: numpy>=1.24
|
|
13
|
+
Requires-Dist: opencv-python>=4.8
|
|
14
|
+
Requires-Dist: pillow>=10.0
|
|
15
|
+
Provides-Extra: ocr
|
|
16
|
+
Requires-Dist: onnxruntime>=1.16; extra == 'ocr'
|
|
17
|
+
Requires-Dist: rapidocr<3.10,>=3.9; extra == 'ocr'
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=8.0; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# imgcolor
|
|
23
|
+
|
|
24
|
+
基于 OpenCV 的 Python 图色库,对齐 [ascript 图色 API](https://www.ascript.cn/docs/android/api/screen/findcolors/) 的使用习惯:**多点找色 / 单点找色 / 多点比色 / 颜色数量 / 找图 / 边缘检测 / 文字识别**。
|
|
25
|
+
|
|
26
|
+
本库只做**纯图像处理**——不截图、不点击设备。图片由调用方通过 `image=` 传入,输出坐标可直接喂给 uiautomator2 等自动化框架。
|
|
27
|
+
|
|
28
|
+
- Python ≥ 3.9,MIT 协议
|
|
29
|
+
- 版本:`0.5.0`
|
|
30
|
+
- 仓库:https://github.com/yst-one/py_imgcolor
|
|
31
|
+
- PyPI:https://pypi.org/project/imgcolor/
|
|
32
|
+
|
|
33
|
+
## 安装
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# 基础功能(找色 / 比色 / 找图 / 边缘检测 / 点阵字库)
|
|
37
|
+
pip install imgcolor
|
|
38
|
+
|
|
39
|
+
# 额外启用 RapidOCR 文字识别(Ocr.find / find_all / exists / click / wait / wait_click)
|
|
40
|
+
pip install "imgcolor[ocr]"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`[ocr]` 会安装 `rapidocr>=3.9,<3.10` 和 `onnxruntime`(首次识别会下载模型)。限定 `<3.10` 是因为 rapidocr 3.10+ 依赖 `opencv-python-headless`,会和本库的 `opencv-python` 产生双 `cv2` 冲突。
|
|
44
|
+
|
|
45
|
+
源码开发:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
uv sync --extra test --extra ocr
|
|
49
|
+
uv run pytest -q
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## 核心约定(先看这段)
|
|
53
|
+
|
|
54
|
+
**1. 图像输入——所有 `image=` / `bitmap=` / `source_img=` / 模板参数都支持四种类型:**
|
|
55
|
+
|
|
56
|
+
| 输入 | 说明 |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `numpy.ndarray` | BGR(默认)、RGB、灰度、BGRA、float 0~1 均可,自动规范化为 BGR/uint8/3 通道 |
|
|
59
|
+
| 文件路径 | `str` 或 `Path`,支持中文/空格路径 |
|
|
60
|
+
| `PIL.Image` | 任意 mode;`P`/`1` 有量化色损,精确比色建议先 `convert("RGB")` |
|
|
61
|
+
| 无参函数 | 返回上述任意类型,配合 `until` / `timeout` 做轮询取图 |
|
|
62
|
+
|
|
63
|
+
**2. 颜色是 RGB、图像是 BGR。** 颜色串一律写 `#RRGGBB`,与 OpenCV 的 BGR 内存顺序相反,库内部自动转换。若你手上是 RGB ndarray(PIL / mss / uiautomator2 截图),用 `imgcolor.from_rgb(arr)` 转换,或给方法传 `color_order="RGB"`。路径和 Pillow 输入已自动规范化,无需该参数。
|
|
64
|
+
|
|
65
|
+
**3. `until` / `timeout` 的重试只在 `image` 传函数时生效。** 传静态 ndarray / 路径时只算一次,不会阻塞等待。
|
|
66
|
+
|
|
67
|
+
**4. `rect` 一律是 `[x, y, x1, y1]`**(左上、右下,右/下边界不含),`None` 表示全图。
|
|
68
|
+
|
|
69
|
+
## 快速上手
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import cv2
|
|
73
|
+
from imgcolor import FindColors, CompareColors, Colors, Canny, FindImages
|
|
74
|
+
|
|
75
|
+
img = cv2.imread("screen.png") # BGR ndarray;也可直接传路径 "screen.png"
|
|
76
|
+
|
|
77
|
+
# 多点找色:锚点(10,10)红 + 右移2像素绿
|
|
78
|
+
p = FindColors.find("10,10,#FF0000|12,10,#00FF00", image=img)
|
|
79
|
+
print(p.x, p.y) # Point 对象,也可 p[0]/p[1]、dict(p.as_dict())
|
|
80
|
+
|
|
81
|
+
# 单点找色 / 统计颜色数量
|
|
82
|
+
pt = FindColors.find_color("#FF0000", image=img) # {"x":..,"y":..} 或 None
|
|
83
|
+
n = Colors.count("#05D395-#101010", rect=[0,0,500,500], image=img)
|
|
84
|
+
|
|
85
|
+
# 比色:判断固定坐标的颜色是否符合预期
|
|
86
|
+
ok = CompareColors.compare("10,10,#FF0000|12,10,#00FF00", image=img)
|
|
87
|
+
|
|
88
|
+
# 找图:模板可为 ndarray / 路径,返回命中矩形与置信度
|
|
89
|
+
hit = FindImages.find("btn.png", image=img, confidence=0.9)
|
|
90
|
+
if hit:
|
|
91
|
+
print(hit["rect"], hit["center_x"], hit["center_y"], hit["confidence"])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
完整可运行示例见 [`examples/示例_快速上手.py`](examples/示例_快速上手.py)(合成图,无需手机)和 [`examples/示例_OCR文字识别.py`](examples/示例_OCR文字识别.py)。
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## API 参考
|
|
99
|
+
|
|
100
|
+
### 1. `FindColors` — 找色
|
|
101
|
+
|
|
102
|
+
特征串格式:`"x,y,#RRGGBB|x,y,#RRGGBB|..."`,第一个点为锚点,其余按相对偏移验证。颜色支持偏色写法 `#RRGGBB-#101010`(逐通道容差,优先级高于 `diff`)。
|
|
103
|
+
|
|
104
|
+
| 方法 | 签名要点 | 返回 |
|
|
105
|
+
|---|---|---|
|
|
106
|
+
| `find` | `(colors, rect=None, space=5, ori=2, diff=0.98, image=None, mode=0, until=0)` | 第一个 `Point` 或 `None` |
|
|
107
|
+
| `find_all` | 同上 + `p_max_num=999999` | `list[Point]` 或 `None` |
|
|
108
|
+
| `find_color` | `(color, rect=None, diff=0.98, mode=0, image=None)` | `{"x":..,"y":..}` 或 `None` |
|
|
109
|
+
| `find_all_color` | `(color, rect=None, diff=0.98, mode=0, max_num=999999, image=None)` | `list[dict]` 或 `None` |
|
|
110
|
+
|
|
111
|
+
- `diff`:颜色相似度 0~1,默认 0.98。
|
|
112
|
+
- `mode`:`0`=RGB 空间比较,`1`=Norm 归一化颜色(抗整体亮度变化)。
|
|
113
|
+
- `space`:结果间距去重,欧氏距离 ≤ `space` 的候选点只保留排序靠前者。
|
|
114
|
+
- `until`:毫秒,`>0` 且 `image` 为函数时持续重试直到命中或超时。
|
|
115
|
+
|
|
116
|
+
`Point` 支持 `p.x` / `p[0]` / `p.as_dict()`。
|
|
117
|
+
|
|
118
|
+
**`ori` 找色方向(1-8):**
|
|
119
|
+
|
|
120
|
+
| ori | 方向 | ori | 方向 |
|
|
121
|
+
|---|---|---|---|
|
|
122
|
+
| 1 | 左上起,纵向(列优先) | 2(默认) | 左上起,横向(行优先) |
|
|
123
|
+
| 3 | 右上起,横向 | 4 | 右上起,纵向 |
|
|
124
|
+
| 5 | 右下起,横向 | 6 | 右下起,纵向 |
|
|
125
|
+
| 7 | 左下起,横向 | 8 | 左下起,纵向 |
|
|
126
|
+
|
|
127
|
+
### 2. `CompareColors` — 比色
|
|
128
|
+
|
|
129
|
+
颜色串必须是**绝对坐标** `"x,y,#RRGGBB|..."`。
|
|
130
|
+
|
|
131
|
+
| 方法 | 签名要点 | 返回 |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| `compare` | `(colors, diff=0.9, bitmap=None, mode=0, until=0, sim=1.0, image=None)` | `bool` |
|
|
134
|
+
| `compare_multi` | `(colors_list, diff=0.9, mode=0, sim=1.0, image=None, until=0)` | 第一个匹配的索引(0 起),全不匹配 `-1` |
|
|
135
|
+
|
|
136
|
+
`sim` 是整体相似度:`通过点数 / 总点数 ≥ sim` 才算成功。`bitmap` 是 ascript 兼容别名,等价于 `image`。
|
|
137
|
+
|
|
138
|
+
### 3. `Colors` — 颜色数量
|
|
139
|
+
|
|
140
|
+
| 方法 | 签名要点 | 返回 |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `mask` | `(colors, rect=None, sim=1, image=None)` | 布尔掩码 ndarray(区域局部坐标) |
|
|
143
|
+
| `count` | `(colors, rect=None, sim=1, image=None)` | `int` 像素数量 |
|
|
144
|
+
| `count_image` | `(colors, rect=None, sim=1, image=None, draw_mode=1)` | `(数量, 调试图 ndarray)` |
|
|
145
|
+
|
|
146
|
+
- `colors` 支持 `|` 分隔多色(并集,同一像素只计一次),也支持偏色串。
|
|
147
|
+
- 颜色串带偏色值时 `sim` 失效(与 ascript 一致)。
|
|
148
|
+
- 调试图:`draw_mode=1` 命中画白/其余黑;`draw_mode=2` 黑底保留命中原色。
|
|
149
|
+
|
|
150
|
+
### 4. `FindImages` — 找图(模板匹配)
|
|
151
|
+
|
|
152
|
+
| 方法 | 说明 |
|
|
153
|
+
|---|---|
|
|
154
|
+
| `find(...)` | 找单个,多图/多尺度时返回置信度最高者 |
|
|
155
|
+
| `find_all(..., maxcnt=0)` | 找全部,`maxcnt=0` 不限数量 |
|
|
156
|
+
| `find_template` / `find_all_template` | 同上别名,默认 `confidence=0.5` |
|
|
157
|
+
| `find_sift` / `find_all_sift` | 兼容入口,降级为模板匹配 |
|
|
158
|
+
|
|
159
|
+
公共参数:`(part_img, rect=None, confidence=0.1, rgb=False, image=None, ori=2, scale_range=None, color_order="BGR")`。
|
|
160
|
+
|
|
161
|
+
- `part_img`:模板,可为 ndarray、路径、`Path`,或它们的列表(多图搜索,结果带 `index` 字段)。
|
|
162
|
+
- `confidence`:相似度阈值。模板图**必须从目标截图同源裁切**才能接近 1.0;跨来源素材(比如从别处保存的图标)分数会明显偏低,需降低阈值。
|
|
163
|
+
- `scale_range=[min, max]`:多尺度搜索(约 15 个步长,含 1.0),用于跨分辨率。
|
|
164
|
+
- 透明 PNG 的 alpha 通道会作为 mask 参与匹配。
|
|
165
|
+
|
|
166
|
+
返回 dict:`{"rect": [x, y, x1, y1], "center_x":.., "center_y":.., "confidence":.., "index":..}`。
|
|
167
|
+
|
|
168
|
+
### 5. `Canny` — 边缘检测 + 轮廓过滤
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
res = Canny(width_range=[100, 500], draw=Canny.DRAW_RECT).run(img)
|
|
172
|
+
for c in res.data:
|
|
173
|
+
print(c["x"], c["y"], c["width"], c["height"], c["area"])
|
|
174
|
+
cv2.imwrite("debug.png", res.image)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
构造参数:`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`。
|
|
178
|
+
|
|
179
|
+
- `draw`:`DRAW_NONE=0` 不绘制 / `DRAW_ALL=1` 画轮廓 / `DRAW_RECT=2` 画外接矩形 / `DRAW_RECT_FILL=3` 填充矩形;`desc=True` 附注文字。
|
|
180
|
+
- `left/top/width/height_range`:`[min, max]` 过滤轮廓;`blur` 高斯核(奇数,0 不模糊)。
|
|
181
|
+
- `run(image, rect=None)` 返回 `CannyResult(image, data, contours, edges)`;`data` 每项含 `x/y/width/height/area/perimeter/points`。
|
|
182
|
+
- 函数式入口:`canny(img, draw=Canny.DRAW_RECT)`。
|
|
183
|
+
|
|
184
|
+
### 6. `Ocr` — 文字识别便捷方法(RapidOCR)
|
|
185
|
+
|
|
186
|
+
需安装 `[ocr]`。对齐 ascript 便捷方法,`text` 支持正则。
|
|
187
|
+
|
|
188
|
+
| 方法 | 签名要点 | 返回 |
|
|
189
|
+
|---|---|---|
|
|
190
|
+
| `find` | `(text, rect=None, binary=-1, confidence=0.1, image=None)` | 第一个结果 dict 或 `None` |
|
|
191
|
+
| `find_all` | `(text=None, rect=None, binary=-1, confidence=0.1, image=None)` | 全部结果列表或 `None`;`text=None` 返回全部文字 |
|
|
192
|
+
| `exists` | 同 `find` | `bool` |
|
|
193
|
+
| `click` | `(text, ..., timeout=0, image=None, clicker=None)` | 找到并点击中心,成功 `True` |
|
|
194
|
+
| `wait` | `(text, timeout=10, ..., image=None)` | 等待出现,超时 `None`(超时单位**秒**) |
|
|
195
|
+
| `wait_click` | `(text, timeout=10, ..., image=None, clicker=None)` | 等待并点击,超时 `False` |
|
|
196
|
+
|
|
197
|
+
结果 dict:`{"text", "rect": [x,y,x1,y1], "center_x", "center_y", "confidence"}`。
|
|
198
|
+
|
|
199
|
+
**点击靠回调注入**(本库不操作设备):
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
import uiautomator2 as u2
|
|
203
|
+
d = u2.connect()
|
|
204
|
+
Ocr.set_clicker(lambda x, y: d.click(x, y)) # 全局注册
|
|
205
|
+
Ocr.click("登录", image=img) # 或每次传 clicker=lambda x, y: d.click(x, y)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
**持续等待要传取图函数:**
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
def grab():
|
|
212
|
+
return cv2.cvtColor(np.asarray(d.screenshot()), cv2.COLOR_RGB2BGR)
|
|
213
|
+
|
|
214
|
+
Ocr.wait_click("登录成功", timeout=15, image=grab)
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
引擎调优:`from imgcolor import configure_engine; configure_engine({"Det.unclip_ratio": 2.0})`(默认已设为 2.0,改善「登录」这类 2 字短按钮漏检);传 `None` 恢复默认并重建引擎。
|
|
218
|
+
|
|
219
|
+
### 7. `OcrX` + `FontLib` — 点阵字库识别(无需 RapidOCR)
|
|
220
|
+
|
|
221
|
+
适用于颜色固定、字体明确的数字/图标识别(如金币数量)。ascript 的 `font.t` 是私有格式无法直接读,用本库 JSON 字库。
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
from imgcolor import FontLib, OcrX, Ocr
|
|
225
|
+
|
|
226
|
+
lib = FontLib(color="#FFFFFF", diff=0.95)
|
|
227
|
+
lib.add("1", digit_1_matrix) # 二维 0/1 点阵
|
|
228
|
+
lib.add_from_image("2", img, rect=[10, 20, 15, 27]) # 从图框选生成字模
|
|
229
|
+
lib.save("font.json")
|
|
230
|
+
|
|
231
|
+
found = OcrX.find_all("font.json", image=img) # ['1', '2', ...];detail=True 出位置
|
|
232
|
+
text = Ocr.matrix("font.json", image=img) # "12"
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
- `OcrX.find_all(font_lib, rect=None, region=0.9, image=None, detail=False, scales=(1.0,), ...)`。
|
|
236
|
+
- `FontLib.load(path)` 加载字库;`make_font_lib(samples, path, image=...)` 批量制作。
|
|
237
|
+
- `binarize(image, color=None, diff=0.9, threshold=None)` 二值化,可单独使用。
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## 底层工具函数
|
|
242
|
+
|
|
243
|
+
`as_image` / `read_image` / `from_rgb` / `parse_points` / `parse_color_spec` / `color_mask` / `crop` 均已导出,可按需组合。例如 `color_mask(img_or_path, parse_color_spec("#FF0000"))` 直接拿布尔掩码。
|
|
244
|
+
|
|
245
|
+
## 常见坑
|
|
246
|
+
|
|
247
|
+
| 现象 | 原因 / 处理 |
|
|
248
|
+
|---|---|
|
|
249
|
+
| 找色/比色全不命中 | 颜色串是 RGB、图是 BGR;RGB 图请用 `from_rgb` 或 `color_order="RGB"` |
|
|
250
|
+
| 找图分数很低 | 模板与截图不同源;从目标截图同源裁切,或降低 `confidence` / 用 `scale_range` |
|
|
251
|
+
| Pillow `P`/`1` 模式比色不准 | 调色板量化色损,先 `convert("RGB")` |
|
|
252
|
+
| `click` 报未配置回调 | 先 `Ocr.set_clicker(fn)` 或传 `clicker=` |
|
|
253
|
+
| `until`/`timeout` 不等待 | `image` 传的是静态图;要重试必须传返回新图的函数 |
|
|
254
|
+
| 中文路径读图失败 | 本库内部用 `np.fromfile + imdecode`,已支持;若自己用 `cv2.imread` 需同样处理 |
|
|
255
|
+
| 首次 OCR 慢 | 首次识别下载模型;之后有缓存 |
|
|
256
|
+
|
|
257
|
+
## 参考文档
|
|
258
|
+
|
|
259
|
+
- [多点找色](https://www.ascript.cn/docs/android/api/screen/findcolors/) · [多点比色](https://www.ascript.cn/docs/android/api/screen/comparecolors/) · [颜色数量](https://www.ascript.cn/docs/android/api/screen/colors/)
|
|
260
|
+
- [边缘检测](https://www.ascript.cn/docs/android/api/screen/canny/) · [找图](https://www.ascript.cn/docs/android/api/screen/findimages/) · [点阵字库](https://www.ascript.cn/docs/android/api/screen/ocrx/) · [OCR 便捷方法](https://www.ascript.cn/docs/android/api/screen/ocr/)
|
imgcolor-0.5.0/README.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# imgcolor
|
|
2
|
+
|
|
3
|
+
基于 OpenCV 的 Python 图色库,对齐 [ascript 图色 API](https://www.ascript.cn/docs/android/api/screen/findcolors/) 的使用习惯:**多点找色 / 单点找色 / 多点比色 / 颜色数量 / 找图 / 边缘检测 / 文字识别**。
|
|
4
|
+
|
|
5
|
+
本库只做**纯图像处理**——不截图、不点击设备。图片由调用方通过 `image=` 传入,输出坐标可直接喂给 uiautomator2 等自动化框架。
|
|
6
|
+
|
|
7
|
+
- Python ≥ 3.9,MIT 协议
|
|
8
|
+
- 版本:`0.5.0`
|
|
9
|
+
- 仓库:https://github.com/yst-one/py_imgcolor
|
|
10
|
+
- PyPI:https://pypi.org/project/imgcolor/
|
|
11
|
+
|
|
12
|
+
## 安装
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
# 基础功能(找色 / 比色 / 找图 / 边缘检测 / 点阵字库)
|
|
16
|
+
pip install imgcolor
|
|
17
|
+
|
|
18
|
+
# 额外启用 RapidOCR 文字识别(Ocr.find / find_all / exists / click / wait / wait_click)
|
|
19
|
+
pip install "imgcolor[ocr]"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`[ocr]` 会安装 `rapidocr>=3.9,<3.10` 和 `onnxruntime`(首次识别会下载模型)。限定 `<3.10` 是因为 rapidocr 3.10+ 依赖 `opencv-python-headless`,会和本库的 `opencv-python` 产生双 `cv2` 冲突。
|
|
23
|
+
|
|
24
|
+
源码开发:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
uv sync --extra test --extra ocr
|
|
28
|
+
uv run pytest -q
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## 核心约定(先看这段)
|
|
32
|
+
|
|
33
|
+
**1. 图像输入——所有 `image=` / `bitmap=` / `source_img=` / 模板参数都支持四种类型:**
|
|
34
|
+
|
|
35
|
+
| 输入 | 说明 |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `numpy.ndarray` | BGR(默认)、RGB、灰度、BGRA、float 0~1 均可,自动规范化为 BGR/uint8/3 通道 |
|
|
38
|
+
| 文件路径 | `str` 或 `Path`,支持中文/空格路径 |
|
|
39
|
+
| `PIL.Image` | 任意 mode;`P`/`1` 有量化色损,精确比色建议先 `convert("RGB")` |
|
|
40
|
+
| 无参函数 | 返回上述任意类型,配合 `until` / `timeout` 做轮询取图 |
|
|
41
|
+
|
|
42
|
+
**2. 颜色是 RGB、图像是 BGR。** 颜色串一律写 `#RRGGBB`,与 OpenCV 的 BGR 内存顺序相反,库内部自动转换。若你手上是 RGB ndarray(PIL / mss / uiautomator2 截图),用 `imgcolor.from_rgb(arr)` 转换,或给方法传 `color_order="RGB"`。路径和 Pillow 输入已自动规范化,无需该参数。
|
|
43
|
+
|
|
44
|
+
**3. `until` / `timeout` 的重试只在 `image` 传函数时生效。** 传静态 ndarray / 路径时只算一次,不会阻塞等待。
|
|
45
|
+
|
|
46
|
+
**4. `rect` 一律是 `[x, y, x1, y1]`**(左上、右下,右/下边界不含),`None` 表示全图。
|
|
47
|
+
|
|
48
|
+
## 快速上手
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import cv2
|
|
52
|
+
from imgcolor import FindColors, CompareColors, Colors, Canny, FindImages
|
|
53
|
+
|
|
54
|
+
img = cv2.imread("screen.png") # BGR ndarray;也可直接传路径 "screen.png"
|
|
55
|
+
|
|
56
|
+
# 多点找色:锚点(10,10)红 + 右移2像素绿
|
|
57
|
+
p = FindColors.find("10,10,#FF0000|12,10,#00FF00", image=img)
|
|
58
|
+
print(p.x, p.y) # Point 对象,也可 p[0]/p[1]、dict(p.as_dict())
|
|
59
|
+
|
|
60
|
+
# 单点找色 / 统计颜色数量
|
|
61
|
+
pt = FindColors.find_color("#FF0000", image=img) # {"x":..,"y":..} 或 None
|
|
62
|
+
n = Colors.count("#05D395-#101010", rect=[0,0,500,500], image=img)
|
|
63
|
+
|
|
64
|
+
# 比色:判断固定坐标的颜色是否符合预期
|
|
65
|
+
ok = CompareColors.compare("10,10,#FF0000|12,10,#00FF00", image=img)
|
|
66
|
+
|
|
67
|
+
# 找图:模板可为 ndarray / 路径,返回命中矩形与置信度
|
|
68
|
+
hit = FindImages.find("btn.png", image=img, confidence=0.9)
|
|
69
|
+
if hit:
|
|
70
|
+
print(hit["rect"], hit["center_x"], hit["center_y"], hit["confidence"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
完整可运行示例见 [`examples/示例_快速上手.py`](examples/示例_快速上手.py)(合成图,无需手机)和 [`examples/示例_OCR文字识别.py`](examples/示例_OCR文字识别.py)。
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## API 参考
|
|
78
|
+
|
|
79
|
+
### 1. `FindColors` — 找色
|
|
80
|
+
|
|
81
|
+
特征串格式:`"x,y,#RRGGBB|x,y,#RRGGBB|..."`,第一个点为锚点,其余按相对偏移验证。颜色支持偏色写法 `#RRGGBB-#101010`(逐通道容差,优先级高于 `diff`)。
|
|
82
|
+
|
|
83
|
+
| 方法 | 签名要点 | 返回 |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| `find` | `(colors, rect=None, space=5, ori=2, diff=0.98, image=None, mode=0, until=0)` | 第一个 `Point` 或 `None` |
|
|
86
|
+
| `find_all` | 同上 + `p_max_num=999999` | `list[Point]` 或 `None` |
|
|
87
|
+
| `find_color` | `(color, rect=None, diff=0.98, mode=0, image=None)` | `{"x":..,"y":..}` 或 `None` |
|
|
88
|
+
| `find_all_color` | `(color, rect=None, diff=0.98, mode=0, max_num=999999, image=None)` | `list[dict]` 或 `None` |
|
|
89
|
+
|
|
90
|
+
- `diff`:颜色相似度 0~1,默认 0.98。
|
|
91
|
+
- `mode`:`0`=RGB 空间比较,`1`=Norm 归一化颜色(抗整体亮度变化)。
|
|
92
|
+
- `space`:结果间距去重,欧氏距离 ≤ `space` 的候选点只保留排序靠前者。
|
|
93
|
+
- `until`:毫秒,`>0` 且 `image` 为函数时持续重试直到命中或超时。
|
|
94
|
+
|
|
95
|
+
`Point` 支持 `p.x` / `p[0]` / `p.as_dict()`。
|
|
96
|
+
|
|
97
|
+
**`ori` 找色方向(1-8):**
|
|
98
|
+
|
|
99
|
+
| ori | 方向 | ori | 方向 |
|
|
100
|
+
|---|---|---|---|
|
|
101
|
+
| 1 | 左上起,纵向(列优先) | 2(默认) | 左上起,横向(行优先) |
|
|
102
|
+
| 3 | 右上起,横向 | 4 | 右上起,纵向 |
|
|
103
|
+
| 5 | 右下起,横向 | 6 | 右下起,纵向 |
|
|
104
|
+
| 7 | 左下起,横向 | 8 | 左下起,纵向 |
|
|
105
|
+
|
|
106
|
+
### 2. `CompareColors` — 比色
|
|
107
|
+
|
|
108
|
+
颜色串必须是**绝对坐标** `"x,y,#RRGGBB|..."`。
|
|
109
|
+
|
|
110
|
+
| 方法 | 签名要点 | 返回 |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `compare` | `(colors, diff=0.9, bitmap=None, mode=0, until=0, sim=1.0, image=None)` | `bool` |
|
|
113
|
+
| `compare_multi` | `(colors_list, diff=0.9, mode=0, sim=1.0, image=None, until=0)` | 第一个匹配的索引(0 起),全不匹配 `-1` |
|
|
114
|
+
|
|
115
|
+
`sim` 是整体相似度:`通过点数 / 总点数 ≥ sim` 才算成功。`bitmap` 是 ascript 兼容别名,等价于 `image`。
|
|
116
|
+
|
|
117
|
+
### 3. `Colors` — 颜色数量
|
|
118
|
+
|
|
119
|
+
| 方法 | 签名要点 | 返回 |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `mask` | `(colors, rect=None, sim=1, image=None)` | 布尔掩码 ndarray(区域局部坐标) |
|
|
122
|
+
| `count` | `(colors, rect=None, sim=1, image=None)` | `int` 像素数量 |
|
|
123
|
+
| `count_image` | `(colors, rect=None, sim=1, image=None, draw_mode=1)` | `(数量, 调试图 ndarray)` |
|
|
124
|
+
|
|
125
|
+
- `colors` 支持 `|` 分隔多色(并集,同一像素只计一次),也支持偏色串。
|
|
126
|
+
- 颜色串带偏色值时 `sim` 失效(与 ascript 一致)。
|
|
127
|
+
- 调试图:`draw_mode=1` 命中画白/其余黑;`draw_mode=2` 黑底保留命中原色。
|
|
128
|
+
|
|
129
|
+
### 4. `FindImages` — 找图(模板匹配)
|
|
130
|
+
|
|
131
|
+
| 方法 | 说明 |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `find(...)` | 找单个,多图/多尺度时返回置信度最高者 |
|
|
134
|
+
| `find_all(..., maxcnt=0)` | 找全部,`maxcnt=0` 不限数量 |
|
|
135
|
+
| `find_template` / `find_all_template` | 同上别名,默认 `confidence=0.5` |
|
|
136
|
+
| `find_sift` / `find_all_sift` | 兼容入口,降级为模板匹配 |
|
|
137
|
+
|
|
138
|
+
公共参数:`(part_img, rect=None, confidence=0.1, rgb=False, image=None, ori=2, scale_range=None, color_order="BGR")`。
|
|
139
|
+
|
|
140
|
+
- `part_img`:模板,可为 ndarray、路径、`Path`,或它们的列表(多图搜索,结果带 `index` 字段)。
|
|
141
|
+
- `confidence`:相似度阈值。模板图**必须从目标截图同源裁切**才能接近 1.0;跨来源素材(比如从别处保存的图标)分数会明显偏低,需降低阈值。
|
|
142
|
+
- `scale_range=[min, max]`:多尺度搜索(约 15 个步长,含 1.0),用于跨分辨率。
|
|
143
|
+
- 透明 PNG 的 alpha 通道会作为 mask 参与匹配。
|
|
144
|
+
|
|
145
|
+
返回 dict:`{"rect": [x, y, x1, y1], "center_x":.., "center_y":.., "confidence":.., "index":..}`。
|
|
146
|
+
|
|
147
|
+
### 5. `Canny` — 边缘检测 + 轮廓过滤
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
res = Canny(width_range=[100, 500], draw=Canny.DRAW_RECT).run(img)
|
|
151
|
+
for c in res.data:
|
|
152
|
+
print(c["x"], c["y"], c["width"], c["height"], c["area"])
|
|
153
|
+
cv2.imwrite("debug.png", res.image)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
构造参数:`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`。
|
|
157
|
+
|
|
158
|
+
- `draw`:`DRAW_NONE=0` 不绘制 / `DRAW_ALL=1` 画轮廓 / `DRAW_RECT=2` 画外接矩形 / `DRAW_RECT_FILL=3` 填充矩形;`desc=True` 附注文字。
|
|
159
|
+
- `left/top/width/height_range`:`[min, max]` 过滤轮廓;`blur` 高斯核(奇数,0 不模糊)。
|
|
160
|
+
- `run(image, rect=None)` 返回 `CannyResult(image, data, contours, edges)`;`data` 每项含 `x/y/width/height/area/perimeter/points`。
|
|
161
|
+
- 函数式入口:`canny(img, draw=Canny.DRAW_RECT)`。
|
|
162
|
+
|
|
163
|
+
### 6. `Ocr` — 文字识别便捷方法(RapidOCR)
|
|
164
|
+
|
|
165
|
+
需安装 `[ocr]`。对齐 ascript 便捷方法,`text` 支持正则。
|
|
166
|
+
|
|
167
|
+
| 方法 | 签名要点 | 返回 |
|
|
168
|
+
|---|---|---|
|
|
169
|
+
| `find` | `(text, rect=None, binary=-1, confidence=0.1, image=None)` | 第一个结果 dict 或 `None` |
|
|
170
|
+
| `find_all` | `(text=None, rect=None, binary=-1, confidence=0.1, image=None)` | 全部结果列表或 `None`;`text=None` 返回全部文字 |
|
|
171
|
+
| `exists` | 同 `find` | `bool` |
|
|
172
|
+
| `click` | `(text, ..., timeout=0, image=None, clicker=None)` | 找到并点击中心,成功 `True` |
|
|
173
|
+
| `wait` | `(text, timeout=10, ..., image=None)` | 等待出现,超时 `None`(超时单位**秒**) |
|
|
174
|
+
| `wait_click` | `(text, timeout=10, ..., image=None, clicker=None)` | 等待并点击,超时 `False` |
|
|
175
|
+
|
|
176
|
+
结果 dict:`{"text", "rect": [x,y,x1,y1], "center_x", "center_y", "confidence"}`。
|
|
177
|
+
|
|
178
|
+
**点击靠回调注入**(本库不操作设备):
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
import uiautomator2 as u2
|
|
182
|
+
d = u2.connect()
|
|
183
|
+
Ocr.set_clicker(lambda x, y: d.click(x, y)) # 全局注册
|
|
184
|
+
Ocr.click("登录", image=img) # 或每次传 clicker=lambda x, y: d.click(x, y)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
**持续等待要传取图函数:**
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
def grab():
|
|
191
|
+
return cv2.cvtColor(np.asarray(d.screenshot()), cv2.COLOR_RGB2BGR)
|
|
192
|
+
|
|
193
|
+
Ocr.wait_click("登录成功", timeout=15, image=grab)
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
引擎调优:`from imgcolor import configure_engine; configure_engine({"Det.unclip_ratio": 2.0})`(默认已设为 2.0,改善「登录」这类 2 字短按钮漏检);传 `None` 恢复默认并重建引擎。
|
|
197
|
+
|
|
198
|
+
### 7. `OcrX` + `FontLib` — 点阵字库识别(无需 RapidOCR)
|
|
199
|
+
|
|
200
|
+
适用于颜色固定、字体明确的数字/图标识别(如金币数量)。ascript 的 `font.t` 是私有格式无法直接读,用本库 JSON 字库。
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from imgcolor import FontLib, OcrX, Ocr
|
|
204
|
+
|
|
205
|
+
lib = FontLib(color="#FFFFFF", diff=0.95)
|
|
206
|
+
lib.add("1", digit_1_matrix) # 二维 0/1 点阵
|
|
207
|
+
lib.add_from_image("2", img, rect=[10, 20, 15, 27]) # 从图框选生成字模
|
|
208
|
+
lib.save("font.json")
|
|
209
|
+
|
|
210
|
+
found = OcrX.find_all("font.json", image=img) # ['1', '2', ...];detail=True 出位置
|
|
211
|
+
text = Ocr.matrix("font.json", image=img) # "12"
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
- `OcrX.find_all(font_lib, rect=None, region=0.9, image=None, detail=False, scales=(1.0,), ...)`。
|
|
215
|
+
- `FontLib.load(path)` 加载字库;`make_font_lib(samples, path, image=...)` 批量制作。
|
|
216
|
+
- `binarize(image, color=None, diff=0.9, threshold=None)` 二值化,可单独使用。
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## 底层工具函数
|
|
221
|
+
|
|
222
|
+
`as_image` / `read_image` / `from_rgb` / `parse_points` / `parse_color_spec` / `color_mask` / `crop` 均已导出,可按需组合。例如 `color_mask(img_or_path, parse_color_spec("#FF0000"))` 直接拿布尔掩码。
|
|
223
|
+
|
|
224
|
+
## 常见坑
|
|
225
|
+
|
|
226
|
+
| 现象 | 原因 / 处理 |
|
|
227
|
+
|---|---|
|
|
228
|
+
| 找色/比色全不命中 | 颜色串是 RGB、图是 BGR;RGB 图请用 `from_rgb` 或 `color_order="RGB"` |
|
|
229
|
+
| 找图分数很低 | 模板与截图不同源;从目标截图同源裁切,或降低 `confidence` / 用 `scale_range` |
|
|
230
|
+
| Pillow `P`/`1` 模式比色不准 | 调色板量化色损,先 `convert("RGB")` |
|
|
231
|
+
| `click` 报未配置回调 | 先 `Ocr.set_clicker(fn)` 或传 `clicker=` |
|
|
232
|
+
| `until`/`timeout` 不等待 | `image` 传的是静态图;要重试必须传返回新图的函数 |
|
|
233
|
+
| 中文路径读图失败 | 本库内部用 `np.fromfile + imdecode`,已支持;若自己用 `cv2.imread` 需同样处理 |
|
|
234
|
+
| 首次 OCR 慢 | 首次识别下载模型;之后有缓存 |
|
|
235
|
+
|
|
236
|
+
## 参考文档
|
|
237
|
+
|
|
238
|
+
- [多点找色](https://www.ascript.cn/docs/android/api/screen/findcolors/) · [多点比色](https://www.ascript.cn/docs/android/api/screen/comparecolors/) · [颜色数量](https://www.ascript.cn/docs/android/api/screen/colors/)
|
|
239
|
+
- [边缘检测](https://www.ascript.cn/docs/android/api/screen/canny/) · [找图](https://www.ascript.cn/docs/android/api/screen/findimages/) · [点阵字库](https://www.ascript.cn/docs/android/api/screen/ocrx/) · [OCR 便捷方法](https://www.ascript.cn/docs/android/api/screen/ocr/)
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""OCR 便捷方法示例 —— 基于 RapidOCR,对齐 ascript Ocr 便捷 API。
|
|
2
|
+
|
|
3
|
+
安装可选依赖:pip install "imgcolor[ocr]"
|
|
4
|
+
运行:uv run python "examples/示例_OCR文字识别.py"(在项目目录下)
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
import cv2
|
|
11
|
+
import numpy as np
|
|
12
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
13
|
+
|
|
14
|
+
from imgcolor import Ocr, configure_engine
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def make_screen():
|
|
18
|
+
"""渲染一张模拟界面截图(文字用系统黑体)。"""
|
|
19
|
+
font = ImageFont.truetype(r"C:\Windows\Fonts\simhei.ttf", 48)
|
|
20
|
+
canvas = Image.new("RGB", (640, 360), (245, 245, 245))
|
|
21
|
+
d = ImageDraw.Draw(canvas)
|
|
22
|
+
d.text((60, 60), "登录确认", font=font, fill=(0, 0, 0))
|
|
23
|
+
d.text((60, 160), "欢迎使用", font=font, fill=(0, 0, 0))
|
|
24
|
+
return cv2.cvtColor(np.asarray(canvas), cv2.COLOR_RGB2BGR)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main():
|
|
28
|
+
configure_engine() # 可选:调整 RapidOCR 参数后重建引擎
|
|
29
|
+
img = make_screen()
|
|
30
|
+
|
|
31
|
+
print("① find ->", Ocr.find("登录", confidence=0.5, image=img))
|
|
32
|
+
print(" find(正则)->", Ocr.find("确认|欢迎", confidence=0.5, image=img))
|
|
33
|
+
print("② find_all ->", Ocr.find_all(confidence=0.5, image=img))
|
|
34
|
+
print("③ exists ->", Ocr.exists("欢迎", confidence=0.5, image=img))
|
|
35
|
+
|
|
36
|
+
p = Path(tempfile.gettempdir()) / "imgcolor_ocr_screen.png"
|
|
37
|
+
cv2.imwrite(str(p), img)
|
|
38
|
+
|
|
39
|
+
clicked = []
|
|
40
|
+
print("④ click ->", Ocr.click("登录", confidence=0.5, image=str(p),
|
|
41
|
+
clicker=lambda x, y: clicked.append((x, y))),
|
|
42
|
+
"点击坐标:", clicked)
|
|
43
|
+
|
|
44
|
+
n = {"v": 0}
|
|
45
|
+
|
|
46
|
+
def provider():
|
|
47
|
+
"""模拟持续取图(真实场景可接 u2 截图)。"""
|
|
48
|
+
n["v"] += 1
|
|
49
|
+
return img
|
|
50
|
+
|
|
51
|
+
print("⑤ wait ->", Ocr.wait("欢迎", timeout=1, image=provider))
|
|
52
|
+
print("⑥ wait_click ->", Ocr.wait_click("欢迎", timeout=1, image=img,
|
|
53
|
+
clicker=lambda x, y: clicked.append((x, y))),
|
|
54
|
+
"点击次数:", len(clicked))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
main()
|