好友
阅读权限20
听众
最后登录1970-1-1
|
import pyautogui
def FindColorEx(x1, y1, x2, y2, color, search_mode, similarity):
global x, y
# 将颜色值从字符串转换为RGB格式
bgr_color = int(color[4:6], 16), int(color[2:4], 16), int(color[0:2], 16)
bgr_color = bgr_color[::-1]
print(bgr_color)
# 获取屏幕截图
screenshot = pyautogui.screenshot(region=(x1, y1, x2 - x1, y2 - y1))
screenshot.save("1.png")
# 根据查找方式选择查找顺序
if search_mode == 0:
search_order = [(x, y) for y in range(y1, y2) for x in range(x1, x2)]
elif search_mode == 1:
center_x = (x1 + x2) // 2
center_y = (y1 + y2) // 2
search_order = sorted([(x, y) for y in range(y1, y2) for x in range(x1, x2)],
key=lambda pos: ((pos[0] - center_x) ** 2 + (pos[1] - center_y) ** 2))
else:
raise ValueError(
"Invalid search mode. Use 0 for left-to-right, top-to-bottom search or 1 for center-outward search.")
# 开始查找颜色
for pos_x, pos_y in search_order:
pixel_color = screenshot.getpixel((pos_x - x1, pos_y - y1))
if color_match(pixel_color, bgr_color, similarity):
# 如果找到相似的颜色,修改全局变量
x = pos_x
y = pos_y
return
# 如果没找到,全局变量仍保持为-1
x = -1
y = -1
def color_match(color1, color2, similarity):
# 计算两个颜色的相似度
delta_blue = abs(color1[0] - color2[0])
delta_green = abs(color1[1] - color2[1])
delta_red = abs(color1[2] - color2[2])
similarity_score = 1 - (delta_blue + delta_green + delta_red) / (255 * 3)
return similarity_score >= similarity
# 示例使用
# 初始化变量
x = -1
y = -1
# 调用函数
FindColorEx(0, 0, 500, 500, "fafafa", 0, 1.0)
# 输出结果
print("返回坐标x:", x)
print("返回坐标y:", y)
|
|