簡體   English   中英

為什么我在 object 檢測中遇到錯誤?

[英]Why am I facing error in object detection?

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()

問題是使用沒有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

您可以在np.unravel_index()的結果上使用numpy.argmax()來獲取最大元素的正確索引:

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

在您的代碼中,您得到 172 作為np.argmax(scores)的結果,但由於scores軸零的大小僅為 5,因此您會得到一個IndexError 如上所示使用np.unravel_index()並使用返回的索引來索引scores

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM