python識別圖標并點擊功能實現
python識別圖標并點擊
首相片帖子已經重復的太多了,我試一下感覺還是很好用的,我就是記錄一下 這篇帖子可以直接制作出很多自動點擊的工具,甚至是游戲物理輔助工具(因為我就在用)! 視頻展示

| 庫 | 安裝 | 作用 |
|---|---|---|
| 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
# 屏幕縮放系數 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 根據圖片特征識別點擊
python 根據圖片特征識別點擊
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 篩選匹配結果
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("點擊失敗!")代碼結構:
1.導入庫:
cv2(OpenCV):用于圖像處理、特征提取和匹配的庫。numpy:用于處理圖像數據所需的數值運算。pyautogui:用于控制鼠標和鍵盤,模擬點擊操作。time:用于控制代碼執(zhí)行的暫停時間。
2.ImageClicker 類:
__init__(self, target_image_path, retry_count=3, retry_interval=1, match_threshold=0.75):
初始化類,設置一些參數:
target_image_path:目標圖像的路徑。retry_count:如果點擊失敗,重試的次數。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。將截圖轉換為 OpenCV 格式。提取截圖的 SIFT 特征kp2, des2。 - 使用
cv2.BFMatcher進行特征匹配,得到匹配結果matches。使用 Lowe's Ratio Test 篩選匹配結果,得到good匹配列表。 - 如果找到匹配結果:
- 計算目標元素的位置(點擊坐標)。
- 使用
pyautogui.click()模擬點擊操作。 - 返回
True,表示點擊成功。
如果沒有找到匹配結果,則等待 retry_interval 秒后繼續(xù)嘗試。
如果所有嘗試都失敗,則返回 False,表示點擊失敗。
使用方法:
- 創(chuàng)建
ImageClicker對象,傳入目標圖像路徑和其他參數。 - 調用
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 篩選匹配結果。
- 計算目標元素的位置(點擊坐標)。
- 模擬點擊目標元素。
注意:
- 為了使代碼正常運行,需要安裝必要的庫:
opencv-python,pyautogui。 - 確保目標圖像
4.png存在于代碼所在的目錄中。 - 調整
match_threshold值可以改變匹配的嚴格程度。 - 為了避免誤點擊,可以根據實際情況調整
retry_count和retry_interval。
參考資料:
python OpenCV 庫中的 cv2.Canny() 函數來對圖像進行邊緣檢測,并顯示檢測到的邊緣特征
到此這篇關于python識別圖標并點擊的文章就介紹到這了,更多相關python識別圖標內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django框架設置cookies與獲取cookies操作詳解
這篇文章主要介紹了Django框架設置cookies與獲取cookies操作,結合實例形式詳細分析了Django框架針對cookie操作的各種常見技巧與操作注意事項,需要的朋友可以參考下2019-05-05
Python使用Dijkstra算法實現求解圖中最短路徑距離問題詳解
這篇文章主要介紹了Python使用Dijkstra算法實現求解圖中最短路徑距離問題,簡單描述了Dijkstra算法的原理并結合具體實例形式分析了Python使用Dijkstra算法實現求解圖中最短路徑距離的相關步驟與操作技巧,需要的朋友可以參考下2018-05-05
python?matplotlib用面積填充實現lmplot的代碼示例
這篇文章主要介紹了python?matplotlib如何用面積填充實現lmplot,文章通過代碼示例介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴可以參考閱讀2023-07-07

