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

问题描述 投票:1回答:1
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()

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

opencv templates location coordinates detect
1个回答
0
投票

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

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对象

© www.soinside.com 2019 - 2024. All rights reserved.