【问题标题】:How get just some elements in an array如何获取数组中的一些元素
【发布时间】: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


【解决方案1】:

如果您有一个一维 Numpy 数组并且只想获取其中的一部分,那么您可以像使用 Python 列表一样使用“:”运算符。

>>> import numpy as np
>>> a = np.array((1,2,3,4))
>>> a
array([1, 2, 3, 4])
>>> a[0:2]
array([1, 2])
>>> a[1:2]
array([2])
>>> print(a[:3])
[1 2 3]
>>> b = a[0:3]
>>> print(b)
[1 2 3]
>>> type(b)
<type 'numpy.ndarray'>
>>> print(a[0])
1
>>> type(a[0])
<type 'numpy.int32'>

编辑:如果locc[0] 给你返回 [367, 368, 368, 368, 369] 而你只想要 367,那么试试loc[0][0]。如果您想要 [367] 以便仍然可以将数据视为列表,请尝试 [loc[0][0]]

【讨论】:

  • 我真的很困惑这与 OP 的问题有什么关系
  • OP 说他有一些 numpy 数组,只想抓取其中的一部分。
  • 它们(似乎是)是元组中的数组。这使得这里的所有切片演示都无关紧要,其他帖子和资源中对它们进行了详细介绍。 OP 没有就我的问题回复我以进行澄清。
  • 如果我使用 locc[0] 它将返回:[367, 368, 368, 368, 369],但我只想要这部分的 367。
  • 非常感谢,当我使用 locc[0][0] 时,输出只有 367,非常感谢!
【解决方案2】:

您可以使用locc[0] 获取数组的第一个元素。

(我假设您发布的两个数组对象来自while 循环的两个循环,因此locc 的每次迭代都是一维数组。)

【讨论】:

  • 如果我使用 locc[0] 它将返回:[367, 368, 368, 368, 369],但我只想要这部分的 367。
  • 你可以通过附加[0]来获取那个数组的第一个元素,即locc[0][0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多