纯python实现大漠图色功能

2023-11-03 07:20

本文主要是介绍纯python实现大漠图色功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

大漠图色是一种自动化测试工具,可以用于识别屏幕上的图像并执行相应的操作。在Python中,可以使用第三方库pyautogui来实现大漠图色功能。具体步骤如下:

  1. 安装pyautogui库:在命令行中输入pip install pyautogui。
  2. 导入pyautogui库:在Python脚本中使用import pyautogui语句导入pyautogui库。
  3. 使用pyautogui.locateOnScreen()函数来查找屏幕上的图像,并返回图像的位置坐标。
  4. 使用pyautogui.click()函数来模拟鼠标点击操作。
  5. 使用pyautogui.typewrite()函数来模拟键盘输入操作。

实现如标题,废话不多说,直接看代码:

# 更新StressShow命令import numpy as np
import pyautogui
import copy
import cv2
from sklearn import clusterclass TuSe:def __init__(self):print('欢迎使用')def GetCapture(self, stax, stay, endx, endy):w = endx - staxh = endy - stayim = pyautogui.screenshot(region=(stax, stay, w, h))# im = cv2.cvtColor(np.array(im), cv2.COLOR_BGR2RGB)return np.array(im)def FindPic(self, x1, y1, x2, y2, path, thd):'''找图:param x1: 起点X:param y1: 起点Y:param x2: 终点X:param y2: 终点Y:param path: 图片路径:param thd: 相似度:return: 图片中心坐标'''img = self.GetCapture(x1, y1, x2, y2)img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)template = cv2.imread(path, 0)th, tw = template.shape[::]rv = cv2.matchTemplate(img, template, 1)minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(rv)if 1 - minVal >= thd:return minLoc[0] + tw / 2 + x1, minLoc[1] + th / 2 + y1else:return -1, -1def Hex_to_Rgb(self, hex):'''十六进制转RGB:param hex: 十六进制颜色值:return: RGB'''return np.array(tuple(int(hex[i:i + 2], 16) for i in (0, 2, 4)))def CmpColor(self, x, y, color, sim: float):'''比色:param x: X坐标:param y: Y坐标:param color: 十六进制颜色,可以从大漠直接获取:param sim: 相似偏移:return: 真或加'''img = self.GetCapture(x - 1, y - 1, x + 1, y + 1)img = np.array(img)img = img[1][1]color = self.Hex_to_Rgb(color)res = np.absolute(color - img)sim = int((1 - sim) * 255)return True if np.amax(res) <= sim else Falsedef FindColor(self, x1, y1, x2, y2, des, sim: float):'''找色:param x1: 起点X:param y1: 起点Y:param x2: 终点X:param y2: 终点Y:param des: 十六进制颜色,可以从大漠直接获取:param sim: 相似偏移:return:'''img = self.GetCapture(x1, y1, x2, y2)img = np.array(img)res = np.absolute(img - self.Hex_to_Rgb(des))sim = int((1 - sim) * 255)res = np.argwhere(np.all(res <= sim, axis=2))res = res + (y1, x1)return res[:, [1, 0]]def GetColorNum(self, x1, y1, x2, y2, des, sim: float):'''获取颜色数量:param x1: 起点X:param y1: 起点Y:param x2: 终点X:param y2: 终点Y:param des: 十六进制颜色,可以从大漠直接获取:param sim: 相似偏移:return:'''return len(self.FindColor(x1, y1, x2, y2, des, sim))def FindMultColor(self, stax, stay, endx, endy, des):'''多点找色:param stax::param stay::param endx::param endy::param des: 大漠获取到的多点找色数据,偏色必须写上:return:'''w = endx - staxh = endy - stayimg = pyautogui.screenshot(region=(stax, stay, w, h))img = np.array(img)rgby = []ps = []a = 0firstXY = []res = np.empty([0, 2])for i in des.split(','):rgb_y = i[-13:]r = int(rgb_y[0:2], 16)g = int(rgb_y[2:4], 16)b = int(rgb_y[4:6], 16)y = int(rgb_y[-2:])rgby.append([r, g, b, y])for i in range(1, len(des.split(','))):ps.append([int(des.split(',')[i].split('|')[0]), int(des.split(',')[i].split('|')[1])])for i in rgby:result = np.logical_and(abs(img[:, :, 0:1] - i[0]) < i[3], abs(img[:, :, 1:2] - i[1]) < i[3],abs(img[:, :, 2:3] - i[2]) < i[3])results = np.argwhere(np.all(result == True, axis=2)).tolist()if a == 0:firstXY = copy.deepcopy(results)else:nextnextXY = copy.deepcopy(results)for index in nextnextXY:index[0] = int(index[0]) - ps[a - 1][1]index[1] = int(index[1]) - ps[a - 1][0]q = set([tuple(t) for t in firstXY])w = set([tuple(t) for t in nextnextXY])matched = np.array(list(q.intersection(w)))res = np.append(res, matched, axis=0)a += 1unique, counts = np.unique(res, return_counts=True, axis=0)index = np.argmax(counts)re = unique[index] + (stay, stax)if np.max(counts) == len(des.split(',')) - 1:return np.flipud(re)return np.array([-1, -1])def FindPicEx(self, x1, y1, x2, y2, path, thd=0.9, MIN_MATCH_COUNT=8):'''全分辨率找图:param x1::param y1::param x2::param y2::param path::param thd: 相似度:param MIN_MATCH_COUNT: 特征点数量:return:'''thd = thd - 0.2template = cv2.imread(path, 0)  # queryImage# target = cv2.imread('target.jpg', 0)  # trainImagetarget = self.GetCapture(x1, y1, x2, y2)target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)# Initiate SIFT detector创建sift检测器sift = cv2.xfeatures2d.SIFT_create()# find the keypoints and descriptors with SIFTkp1, des1 = sift.detectAndCompute(template, None)kp2, des2 = sift.detectAndCompute(target, None)# 创建设置FLANN匹配FLANN_INDEX_KDTREE = 0index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)search_params = dict(checks=50)flann = cv2.FlannBasedMatcher(index_params, search_params)matches = flann.knnMatch(des1, des2, k=2)# store all the good matches as per Lowe's ratio test.good = []for m, n in matches:if m.distance < thd * n.distance:good.append(m)if len(good) > MIN_MATCH_COUNT:# 获取关键点的坐标src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)# 计算变换矩阵和MASKM, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)h, w = template.shape# 使用得到的变换矩阵对原图像的四个角进行变换,获得在目标图像上对应的坐标pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)dst = cv2.perspectiveTransform(pts, M)res = (dst[0] + dst[2]) / 2  # [[[ 39.11337  147.11575 ]] [[135.06624  255.12143 ]]return int(res[0][0]) + x1, int(res[0][1]) + y1else:return -1, -1def _FilterRec(self, res, loc):""" 对同一对象的多个框按位置聚类后,按置信度选最大的一个进行保留。:param res: 是 cv2.matchTemplate 返回值:param loc: 是 cv2.np.argwhere(res>threshold) 返回值:return: 返回保留的点的列表 pts"""model = cluster.AffinityPropagation(damping=0.5, max_iter=100, convergence_iter=10, preference=-50).fit(loc)y_pred = model.labels_pts = []for i in set(y_pred):argj = loc[y_pred == i]argi = argj.Tpt = argj[np.argmax(res[tuple(argi)])]pts.append(pt[::-1])return np.array(pts)def FindMultPic(self, x1, y1, x2, y2, path, thd):'''多目标找图:param x1::param y1::param x2::param y2::param path::param thd: 相似度:return:'''target = self.GetCapture(x1, y1, x2, y2)target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)template = cv2.imread(path, 0)w, h = template.shape[:2]res = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)loc = np.argwhere(res >= thd)if len(loc):resc = self._FilterRec(res, loc)return resc + (h / 2 + x1, w / 2 + y1)else:return [[-1, -1]]def FindPic_TM(self, x1, y1, x2, y2, path, thd):'''找透明图,透明色为黑色:param x1: 起点X:param y1: 起点Y:param x2: 终点X:param y2: 终点Y:param path: 图片路径:param thd: 相似度:return: 图片中心坐标'''img = self.GetCapture(x1, y1, x2, y2)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)template = cv2.imread(path)template2 = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)ret, mask = cv2.threshold(template2, 20, 255, cv2.THRESH_BINARY)th, tw = template.shape[:2]rv = cv2.matchTemplate(img, template, 1, mask=mask)minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(rv)if 1 - minVal >= thd:return minLoc[0] + tw / 2 + x1, minLoc[1] + th / 2 + y1else:return -1, -1def StressShow(self, stax, stay, endx, endy, des, type=0):'''保留选中颜色,其他为黑色,相似度根据偏色调整:param stax::param stay::param endx::param endy::param des: 大漠的色彩描述:param type: 0为原来颜色,1为白色:return:'''# des = 'e81010-101010|f9ad08-000000'dess = des.split('|')des = [i[0:6] for i in dess]des = [np.array(self.Hex_to_Rgb(d)) for d in des]pds = [i[-6:] for i in dess]pds = tuple(tuple(int(item[i:i + 2]) for i in range(0, len(item), 2)) for item in pds)img = self.GetCapture(stax, stay, endx, endy)mask = np.zeros(img.shape[:2], dtype=np.bool_)for i, color in enumerate(des):mask += np.all(np.abs(img - color) <= pds[i], axis=-1)new_img = np.where(mask[..., None], [255, 255, 255], [0, 0, 0]) if type else np.where(mask[..., None], img,[0, 0,0])  # 修改这里,将选中的颜色设为白色img_converted = cv2.convertScaleAbs(new_img)img_converted = cv2.cvtColor(np.array(img_converted), cv2.COLOR_BGR2RGB)return img_converteda = TuSe()
b = a.StressShow(0, 0, 1920, 1080, 'e81010-101010|36659e-101010', 0)
cv2.imshow('13', b)
cv2.waitKey(0)
cv2.destroyAllWindows()

这篇关于纯python实现大漠图色功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/336514

相关文章

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的