FindColors:精准像素点阵查找
FindColors 模块用于在屏幕或指定图像中查找符合特定颜色分布的点阵。它通过定义一个基准点颜色和若干偏移点的颜色,实现对目标的唯一化定位。
1. 导入模块
# 导入多点找色类
from ascript.windows.screen import FindColors
2. 静态方法
🎯 查找单个目标 find()
查找并返回第一个满足多点颜色匹配条件的坐标。
代码块:
# 查找第一个匹配点
FindColors.find(colors, rect=None, threshold=0.95, ori=2, exclusion_radius=5, im_source=None)
参数详解:
- colors (str): 颜色描述字符串。格式为
"x,y,color|dx,dy,color|..."。- 示例:
"100,200,#FFFFFF|10,0,#FF0000"表示基准点为 (100,200) 且颜色为白色,相对其右侧 10 像素处需为红色。
- 示例:
- rect (list): 查找区域
[左, 上, 右, 下]。若为None则查找全屏。 - threshold (float): 颜色相似度阈值(0.0 ~ 1.0)。
1.0为完全匹配。 - ori (int): 查找方向(1-8)。常用
2表示从上到下、从左到右。 - exclusion_radius (int): 排除半径。找到一个点后,忽略其周围指定像素范围内的其他点,防止结果重复。
- im_source: 图像源。若为
None则自动截取当前屏幕。
返回值:
- 成功返回坐标元组
(x, y),失败返回None。
🔍 全量查找目标 find_all()
在指定范围内查找所有符合条件的颜色点阵。
代码块:
# 查找所有匹配点
FindColors.find_all(colors, rect=None, threshold=0.95, ori=2, exclusion_radius=5, im_source=None, max_res=0)
参数详解:
- colors / rect / threshold / ori / exclusion_radius / im_source: 同
find()方法。 - max_res (int): 最大返回结果数量。
0表示返回所有找到的结果。
返回值:
- 返回坐标元组列表,例如:
[(120, 240), (450, 600)]。
💡 案例演示
from ascript.windows.screen import FindColors
# 1. 定义目标特征:基准点及其相对偏移点的颜色
# 格式:x,y,颜色|相对x,相对y,颜色
target_feature = "0,0,#3B82F6|5,5,#FFFFFF|-5,5,#FFFFFF"
# 2. 在全屏范围查找第一个符合特征的位置
pos = FindColors.find(target_feature, threshold=0.9)
if pos:
print(f"找到目标坐标: {pos}")
else:
print("未找到目标")
# 3. 指定 ROI 区域查找所有目标
# 仅在屏幕左上角 500x500 范围内查找
results = FindColors.find_all(
colors=target_feature,
rect=[0, 0, 500, 500],
threshold=0.95,
max_res=10
)
for x, y in results:
print(f"匹配到点:({x}, {y})")