5

I have error related to simple object detection .

output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
IndexError: invalid index to scalar variable.

import cv2.cv2 as cv
import numpy as np

# Load Yolo

net = cv.dnn.readNet('yolov3.weights','yolov3.cfg')
classes = []
with open ("coco.names","r") as f:
 classes = [line.strip() for line in f.readlines()]

layer_names = net.getLayerNames()
otputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

 #Loading image

 img = cv.imread("room_ser.jpg")

cv.imshow("Image",img)
cv.waitKey(0)
cv.destroyAllWindows()
tlentali
  • 3,407
  • 2
  • 14
  • 21
Farzin
  • 71
  • 1
  • 1
  • 2
  • 1
    The reason is explained in https://stackoverflow.com/questions/69834335/loading-yolo-invalid-index-to-scalar-variable/69881065 – PhilKo Dec 10 '21 at 08:04

2 Answers2

18

getUnconnectedOutLayers() returns an integer, not an iterable. Instead, use

outputlayers = [layer_names[i-1] for i in net.getUnconnectedOutLayers()]

The examples shown here are incorrect. More information on the method can be found on the cv2 docs here.

The error itself (IndexError) tells you that you are trying to index something that is a scalar.

halfer
  • 19,824
  • 17
  • 99
  • 186
adam.hendry
  • 4,458
  • 5
  • 24
  • 51
  • 1
    It's best just to let people upvote material organically. If you want to get to the 50 mark, try to write one good answer per day for a week, and by the end of the week you should be there. Rep is fun, but don't make it the sole reason you are here - satisfaction can be had in helping people. – halfer Nov 28 '21 at 20:11
0

That index issue because it can not iterate

unconnected_indices = neural_network.getUnconnectedOutLayers() output_names = [layer_names[index - 1] for index in unconnected_indice

bounding_box = all_bounding_boxes[index]

if class_ids[index] == 0: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) class_with_confidence = 'PERSON' + str(int(confidence_values[index] * 100)) + '%' cv2.putText(img, class_with_confidence, (x, y-10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.5, (255, 0, 0), 1)

tpd
  • 11
  • 4
  • 1
    Can you post traceback? – toyota Supra Aug 25 '23 at 11:10
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/34896903) – doneforaiur Aug 28 '23 at 04:59