【问题标题】:Why am I facing error in object detection?为什么我在对象检测中遇到错误?
【发布时间】:2020-11-01 06:15:37
【问题描述】:
confidence_score = scores[class1]

IndexError:索引 172 超出轴 0 的范围,大小为 5

import cv2
import numpy as np
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg.txt")
classes = []
img1 = cv2.imread('img1.jpg')
img1 = cv2.resize(img1,None, fx =0.4, fy =0.4)
height,width,chanels = img1.shape
with open("coco.names.txt", "r") as f:
     classes = [line.strip() for line in f.readlines()]
layer_name = net.getLayerNames()
output_layers = [layer_name[i[0] - 1] for i in net.getUnconnectedOutLayers()]
floaty =0.004
blob = cv2.dnn.blobFromImage(img1,floaty,(416,416),(0,0,0),True)
# true to convert RBG
for b in blob:
    for n,img_blog in enumerate(b):
        cv2.imshow(str(n), img_blog)
net.setInput(blob)
out = net.forward(output_layers)

#trying to show or detect
for show in out:
    for detection in out:
        scores = detection[:5]
        class1 = np.argmax(scores)
        confidence_score = scores[class1]
        if confidence_score > 0.6:
            center_x = int[detection[0] * width]
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            cv2.circle(img1,(center_x,center_y),12,(0,255,0),2)

cv2.imshow('image', img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 错误是 confidence_score = scores[class1] IndexError: index 172 is out of bounds for axis 0 with size 5
  • 你的问题是什么?
  • 这能回答你的问题吗? Argmax of numpy array returning non-flat indices
  • 我的问题是为什么我会收到错误“”
  • confidence_score = score[class1] IndexError: index 172 is out of bounds for axis 0 with size 5

标签: python


【解决方案1】:

问题是使用不带axis 参数的numpy.argmax 会返回索引,就像数组被展平一样:

a = np.arange(6).reshape(2,3) + 10
# array([[10, 11, 12],
#       [13, 14, 15]])

flat_max = np.argmax(a)
# 5 <=== "flattened" indices of max element (15)

a[flat_max]
# IndexError: index 5 is out of bounds for axis 0 with size 2

您可以在numpy.argmax() 的结果上使用np.unravel_index() 来获取最大元素的正确索引:

i, j = np.unravel_index(np.argmax(a), a.shape)
a[i][j]
# (1,2) <=== correct indices of max element (15)

在您的代码中,np.argmax(scores) 的结果为 172,但由于 scores 的轴零的大小仅为 5,因此您将获得 IndexError。如上所示使用np.unravel_index(),并使用返回的索引来索引scores

i, j = np.unravel_index(np.argmax(scores), scores.shape)
confidence_score = scores[i][j]

【讨论】:

  • 您能否根据我的问题提供代码,因为我正在学习教程并且我没有太多知识@adamgy
  • 分数的维度是什么? (您可以通过在代码中插入 print(scores.shape) 来检查)
  • 我应该在哪里打印错误只是被抛出
  • 好的,尝试用我刚刚添加到答案中的两行替换从 class1 = ... 开始的两行代码
  • 现在这个错误来了" TypeError: only size-1 arrays can be convert to Python scalars Line 25"
猜你喜欢
  • 2021-08-17
  • 1970-01-01
  • 2020-08-03
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多