之前写过有C#版本的功能,此为python版本参考:
import cv2 as cv import numpy as np from matplotlib import pyplot as plt from PIL import ImageGrab import os import sys imtest = ImageGrab.grab((0,0,1000,1000)) #可以添加一个坐标元组进去 imtest.save('test.png') img_rgb = cv.imread('test.png') img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY) template = cv.imread('5.png', 0) h, w = template.shape[:2] res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED) threshold = 0.9 # 取匹配程度大于90%的坐标 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): # *号表示可选参数 bottom_right = (pt[0] + w, pt[1] + h) cv.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2) if os.path.exists('test.png'): os.remove('test.png') cv.imshow('img_rgb', img_rgb) cv.waitKey(0) cv.destroyAllWindows()
文章评论