gpt4 book ai didi

opencv - 使用Python在OpenCV中检测模板的坐标

转载 作者:行者123 更新时间:2023-12-02 16:37:52 25 4
gpt4 key购买 nike

import cv2
import numpy as np
import pyautogui as pag

#getting a small region as a screenshot
region = (460, 400, 600, 400)
pag.screenshot('da2.png', region = region)

#using that screenshot to detect where a template might be and saving the image
img_rgb = cv2.imread('da2.png')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('player2.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.6335
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 25)

cv2.imshow('Detected',img_rgb)
cv2.waitKey(0)
cv2.imwrite('01.png',img_rgb)
cv2.destroyAllWindows()

我正在尝试使用屏幕截图和玩家模板来检测游戏中的其他玩家。问题是我不知道如何获取检测到模板的位置的坐标。

我还遇到了一个程序,该程序可以实时从屏幕上克隆出某个区域

import numpy as np
from PIL import ImageGrab
import cv2

def process_img(image):
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
return processed_img

def main():
while True:
screen = np.array(ImageGrab.grab(bbox=(460,400,1140,920)))
new_screen = process_img(screen)
cv2.imshow('window', new_screen)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
main()

我不知道如何使用此代码来检测可能出现在屏幕上的模板...

最佳答案

研究您的原始代码...特别是这一行:

for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 25)

如果您在阅读的图像中看到一个绘制的矩形,则 pt是此矩形的左上顶点,而 (pt[0] + w, pt[1] + h)是此矩形的右下顶点。

约定是(0,0)位于图像的左上角,而(img.cols,img.rows)位于右下角。

要获取点 pt的积分坐标,可以使用 pt.xpt.y对象

关于opencv - 使用Python在OpenCV中检测模板的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com