python識別圖標并點擊功能實現(xiàn)
python識別圖標并點擊
首相片帖子已經(jīng)重復的太多了,我試一下感覺還是很好用的,我就是記錄一下 這篇帖子可以直接制作出很多自動點擊的工具,甚至是游戲物理輔助工具(因為我就在用)! 視頻展示
庫 | 安裝 | 作用 |
---|---|---|
pillow | pip install pillow | 加載圖片 |
pyscreeze | pip install pyscreeze | 截屏 |
pyautogui | pip install pyautogui | 控制鼠標或鍵盤 |
opencv-python | pip install opencv-python==4.3.0.38 | 識別匹配圖片 |
import time import pyautogui import pyscreeze import cv2 # 屏幕縮放系數(shù) mac縮放是2 windows一般是1 screenScale=1 #事先讀取按鈕截圖 target= cv2.imread(r"./image/ssk.png",cv2.IMREAD_GRAYSCALE) # 先截圖 screenshot=pyscreeze.screenshot('my_screenshot.png') # 讀取圖片 灰色會快 temp = cv2.imread(r'my_screenshot.png',cv2.IMREAD_GRAYSCALE) theight, twidth = target.shape[:2] tempheight, tempwidth = temp.shape[:2] print("目標圖寬高:"+str(twidth)+"-"+str(theight)) print("模板圖寬高:"+str(tempwidth)+"-"+str(tempheight)) # 先縮放屏幕截圖 INTER_LINEAR INTER_AREA scaleTemp=cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale))) stempheight, stempwidth = scaleTemp.shape[:2] print("縮放后模板圖寬高:"+str(stempwidth)+"-"+str(stempheight)) # 匹配圖片 res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED) mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) if(max_val>=0.9): # 計算出中心點 top_left = max_loc bottom_right = (top_left[0] + twidth, top_left[1] + theight) tagHalfW=int(twidth/2) tagHalfH=int(theight/2) tagCenterX=top_left[0]+tagHalfW tagCenterY=top_left[1]+tagHalfH #左鍵點擊屏幕上的這個位置 pyautogui.click(tagCenterX,tagCenterY,button='left') # 點擊 else: print ("沒找到")
補充:python 根據(jù)圖片特征識別點擊
python 根據(jù)圖片特征識別點擊
import cv2 import numpy as np import pyautogui import time class ImageClicker: def __init__(self, target_image_path, retry_count=3, retry_interval=1, match_threshold=0.75): self.target_image_path = target_image_path self.retry_count = retry_count self.retry_interval = retry_interval self.match_threshold = match_threshold # 加載目標圖片 self.target_image = cv2.imread(self.target_image_path) # 提取目標圖片的 SIFT 特征 self.sift = cv2.SIFT_create() self.kp1, self.des1 = self.sift.detectAndCompute(self.target_image, None) def click_image(self): for i in range(self.retry_count): try: # 獲取瀏覽器窗口截圖 screenshot = pyautogui.screenshot() screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR) # 提取截圖的 SIFT 特征 kp2, des2 = self.sift.detectAndCompute(screenshot, None) # 進行特征匹配 bf = cv2.BFMatcher() matches = bf.knnMatch(self.des1, des2, k=2) # 使用 Lowe's Ratio Test 篩選匹配結(jié)果 good = [] for m, n in matches: if m.distance < self.match_threshold * n.distance: # 使用 match_threshold 閾值 good.append([m]) # 計算目標元素的位置 if len(good) > 0: src_pts = np.float32([self.kp1[m[0].queryIdx].pt for m in good]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m[0].trainIdx].pt for m in good]).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) h, w = self.target_image.shape[:2] pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, M) # 計算點擊坐標 x = int((dst[0][0][0] + dst[2][0][0]) / 2) # 計算水平方向的中間位置 y = int((dst[0][0][1] + dst[2][0][1]) / 2) # 計算垂直方向的中間位置 # 點擊目標元素 pyautogui.click(x, y) return True # 點擊成功 except Exception as e: print(f"點擊失?。簕e}") time.sleep(self.retry_interval) return False # 點擊失敗 # 使用示例 image_clicker = ImageClicker('4.png', retry_count=5, retry_interval=2, match_threshold=0.8) # 設置 match_threshold 為 0.8 if image_clicker.click_image(): print("點擊成功!") else: print("點擊失??!")
代碼結(jié)構(gòu):
1.導入庫:
cv2
(OpenCV):用于圖像處理、特征提取和匹配的庫。numpy
:用于處理圖像數(shù)據(jù)所需的數(shù)值運算。pyautogui
:用于控制鼠標和鍵盤,模擬點擊操作。time
:用于控制代碼執(zhí)行的暫停時間。
2.ImageClicker
類:
__init__(self, target_image_path, retry_count=3, retry_interval=1, match_threshold=0.75)
:
初始化類,設置一些參數(shù):
target_image_path
:目標圖像的路徑。retry_count
:如果點擊失敗,重試的次數(shù)。retry_interval
:兩次重試之間的間隔時間(秒)。match_threshold
:匹配閾值,用于判斷目標圖像與屏幕截圖的匹配程度。值越高,匹配要求越嚴格。
加載目標圖像 self.target_image
。
創(chuàng)建 SIFT (尺度不變特征變換) 對象 self.sift
,用于提取圖像特征。
計算目標圖像的 SIFT 特征 self.kp1, self.des1
。
2.click_image(self)
:
1.循環(huán)嘗試 retry_count
次:
- 獲取屏幕截圖
screenshot
。將截圖轉(zhuǎn)換為 OpenCV 格式。提取截圖的 SIFT 特征kp2, des2
。 - 使用
cv2.BFMatcher
進行特征匹配,得到匹配結(jié)果matches
。使用 Lowe's Ratio Test 篩選匹配結(jié)果,得到good
匹配列表。 - 如果找到匹配結(jié)果:
- 計算目標元素的位置(點擊坐標)。
- 使用
pyautogui.click()
模擬點擊操作。 - 返回
True
,表示點擊成功。
如果沒有找到匹配結(jié)果,則等待 retry_interval
秒后繼續(xù)嘗試。
如果所有嘗試都失敗,則返回 False
,表示點擊失敗。
使用方法:
- 創(chuàng)建
ImageClicker
對象,傳入目標圖像路徑和其他參數(shù)。 - 調(diào)用
click_image()
方法嘗試點擊目標圖像。
代碼示例:
image_clicker = ImageClicker('4.png', retry_count=5, retry_interval=2, match_threshold=0.8) if image_clicker.click_image(): print("點擊成功!") else: print("點擊失?。?)
代碼主要流程:
- 加載目標圖像并提取其 SIFT 特征。
- 獲取屏幕截圖并提取其 SIFT 特征。
- 將目標圖像的特征與截圖的特征進行匹配。
- 使用 Lowe's Ratio Test 篩選匹配結(jié)果。
- 計算目標元素的位置(點擊坐標)。
- 模擬點擊目標元素。
注意:
- 為了使代碼正常運行,需要安裝必要的庫:
opencv-python
,pyautogui
。 - 確保目標圖像
4.png
存在于代碼所在的目錄中。 - 調(diào)整
match_threshold
值可以改變匹配的嚴格程度。 - 為了避免誤點擊,可以根據(jù)實際情況調(diào)整
retry_count
和retry_interval
。
參考資料:
python OpenCV 庫中的 cv2.Canny() 函數(shù)來對圖像進行邊緣檢測,并顯示檢測到的邊緣特征
到此這篇關于python識別圖標并點擊的文章就介紹到這了,更多相關python識別圖標內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python之生成多層json結(jié)構(gòu)的實現(xiàn)
今天小編就為大家分享一篇python之生成多層json結(jié)構(gòu)的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02在jupyter notebook 添加 conda 環(huán)境的操作詳解
這篇文章主要介紹了在jupyter notebook 添加 conda 環(huán)境的操作詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04python如何修改PYTHONPATH環(huán)境變量
這篇文章主要介紹了python如何修改PYTHONPATH環(huán)境變量問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Python中Cryptography庫實現(xiàn)加密解密
Python中Cryptography庫給你的文件加把安全鎖,本文主要介紹了Python中Cryptography庫實現(xiàn)加密解密,具有一定的參考價值,感興趣的可以了解一下2024-02-02