【发布时间】:2019-06-06 21:23:54
【问题描述】:
(对不起我的英语不好) 我正在使用 OpenCv 和另一个小型库在 python 上编写程序,基本上我的程序需要根据模板在我的屏幕上找到一个图像。我对此使用了模板匹配。程序识别屏幕上的模板并将右左像素作为数组发送到输出。但是,有些数字我不想要,我只想获取数组的前 3 个数字。
import cv2
import numpy as np
from matplotlib import pyplot as plt
import pyscreenshot as ImageGrab
while True:
#Template Matching of the block
img_rgb = ImageGrab.grab(bbox=(448, 168, 1471, 935))
img_rgb = np.asarray(img_rgb)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread("Templates/rock.jpg",0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.9
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), 2)
#Template Matching of the Character
templatec = cv2.imread("Templates/char.jpg",0)
wc, hc = templatec.shape[::-1]
resc = cv2.matchTemplate(img_gray,templatec,cv2.TM_CCOEFF_NORMED)
thresholdc = 0.6
locc = np.where( resc >= thresholdc)
for pt in zip(*locc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,0), 2)
cv2.imwrite('res.png',img_rgb)
print(locc)
我屏幕上的对象的输出是:(array([367, 368, 368, 368, 369], dtype=int32), array([490, 489, 490, 491, 490], dtype=int32 ))。
但我只想要第一个数组的“367”和第二个数组的“490”
【问题讨论】:
-
你从
print(type(locc))得到什么?正如所发布的,它看起来像一个元组,但我不知道这是否是它的显示方式的怪癖。 -
如果是元组,
result = [item[0] for item in locc] -
如果我使用 locc[0] 它将返回:[367, 368, 368, 368, 369],但我只想要这部分的 367。
-
a) 没有解决我的第一个问题,b) 在这种情况下,我猜到了您的问题并在我的第二条评论中正确回答。与其重新陈述问题,不如阅读并采纳您收到的反馈意见?
标签: python arrays numpy opencv template-matching