我正在用Python3为计算机游戏CSGO编写一个基于像素的瞄准机器人。
使用OpenCV模块,我正在尝试: 1.截取屏幕截图并将其保存在内存中 2.使用开放式简历扫描屏幕截图,并使用模板图像查找敌方玩家的头像。
from PIL import ImageGrab
from matplotlib import pyplot
import cv2
import numpy
#-Take screenshot of screen
#img = ImageGrab.grab().tobytes()
#-scan for pixel in that range (opencv).
img = cv2.imread("img//frame_2.png", 0) #using test frame at the moment, not sure how to get the ImageGrab to be read by OpenCV.
img2 = img.copy()
template = cv2.imread("img//source_1.png", 0)
w, h = template.shape[::-1]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
# match template
res = cv2.matchTemplate(img, template, eval(meth))
v_min, v_max, l_min, l_max = cv2.minMaxLoc(res)
#
if eval(meth) in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
TopLeft = l_min
else:
TopLeft = l_max
BottomRight = (TopLeft[0] + w, TopLeft[1] + h)
cv2.rectangle(img, TopLeft, BottomRight, 255, 2)
pyplot.subplot(121), pyplot.imshow(res, cmap = 'gray')
pyplot.title('Matching Result'), pyplot.xticks([]), pyplot.yticks([])
pyplot.subplot(122), pyplot.imshow(img, cmap = 'gray')
pyplot.title('Detected Point'), pyplot.xticks([]), pyplot.yticks([])
pyplot.suptitle(meth)
pyplot.show()
#-If match, get the x,y pos of that pixel.
#-Set mouse pos to that x,y pos.
#-Click
主图像:
模板:
找到匹配项:
该代码用于识别相同的模板图像。但是,如果在主图像中更改了1或2个像素,则模板将不再匹配。这对我没有用,因为在游戏中,敌方玩家不断移动,这意味着身体和头部在变小,变大,伸展,变色,这取决于游戏地图上当前位置的光线。>
因此永远不会有完全相同的比赛!如何在主图像中搜索与模板图像相似的匹配项,像素?
编辑: 我看了一下this Stackoverflow问题,并尝试使用直方图:
import cv2
img = cv2.imread("img//frame_1.png", 0)
template = cv2.imread("img//source_1.png", 0)
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
match = cv2.matchTemplate(img, template, eval(methods[0]))
当我运行代码时,我得到了大量的值(如下所示),我不知道它们的含义。不知道如何修改代码以达到我的目的:
array([[-1136278.9 , -1093150.1 , -1080569.5 , ..., -405979.28,
-414166.75, -425574.2 ],
[-1179708.5 , -1142968. , -1145978.2 , ..., -429809.44,
-445418.6 , -475716.44],
[-1210820.1 , -1179169.8 , -1200529.4 , ..., -459596.62,
-485254.97, -526792.56],
...,
[ -566501.75, -677895.25, -863794.2 , ..., 1482537.5 ,
1321293.1 , 1255024.8 ],
[ -602097.5 , -719123.2 , -926334.06, ..., 1590121. ,
1438965.9 , 1394004.4 ],
[ -646915.44, -765088.6 , -976994.44, ..., 1722158.9 ,
1561813.1 , 1471592.8 ]], dtype=float32)