本文主要參考:http://www.51testing.com/html/01/n-3721401.html
為理解opencv函數,參考了http://woshicver.com/
意圖:准備一張小圖,在電腦屏幕上找到小圖坐標,並點擊。
1 安裝 opencv 和 numpy:
pip3 install opencv-python
上述命令將 opencv 和 numpy都安裝了,可以在類似D:\Python36\Lib\site-packages目錄下看到
2 准備小圖,用瀏覽器打開baidu.com,用截圖工具或PrtSc鍵截取百度首頁的那個“百度一下”button,另存為bd.png
3、用程序截屏,存為screen.png,導入兩張圖片,匹配,找到坐標,點擊。
由於還沒有PIL,先pip3 install PIL 結果提示:No matching distribution found for PIL
參考https://blog.csdn.net/weixin_34214500/article/details/85974177
先 pip3 install Pillow 提示已經安裝了... ...尷尬
為了進行鼠標點擊,安裝pyautogui
pip install -i https://pypi.douban.com/simple/ pyautogui
最終代碼:
# -*- coding: utf-8 -*- import pyautogui import cv2 import numpy as np from PIL import ImageGrab #截屏,同時提前准備一張屏幕上會出現的小圖bd.png im = ImageGrab.grab() im.save('screen.png','png') #加載原始RGB圖像 img_rgb = cv2.imread("screen.png") #創建一個原始圖像的灰度版本,所有操作在灰度版本中處理,然后在RGB圖像中使用相同坐標還原 img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) #加載將要搜索的圖像模板 template = cv2.imread('bd.png',0) #使用matchTemplate對原始灰度圖像和圖像模板進行匹配 res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) #設定閾值,0.7應該可以 threshold = 0.999 #res大於99.9% loc = np.where( res >= threshold) #得到原圖像中的坐標 for pt in zip(*loc[::-1]): print(pt[0],pt[1]) pyautogui.click(pt[0],pt[1]) break #cv2.destroyAllWindows() print("the end")
注意:測試時要把baidu首頁的按鈕顯示在屏幕上。
另外代碼好像還是寫復雜了,應該可以直接用minMaxLoc獲取坐標點。
另參考:https://www.cnblogs.com/mjk961/p/9129211.html
https://blog.csdn.net/weixin_42081389/article/details/87935735
https://www.jianshu.com/p/c20adfa72733
https://docs.opencv.org/master/
https://www.cnblogs.com/chjbbs/p/5077587.html
https://blog.csdn.net/weixin_34214500/article/details/85974177