Home > Net >  'method' object is not subscriptable erroor
'method' object is not subscriptable erroor

Time:04-25

i write this code in vscode :

from fileinput import filename
import imp
import cv2,time,os,tensorflow as tf
import numpy as np

from tensorflow.python.keras.utils.data_utils import get_file

np.random.seed(123)

class Detector:
    def __init__(self) -> None:
        pass


    def readClaassees(self,classesFilePath):
        with open(classesFilePath,'r') as f:
            self.classesList = f.read().splitlines()

            #colors list 
            self.colorList =np.random.uniform(low=0,high=255,size=(len(self.classesList),3))

            print(len(self.classesList),len(self.colorList))    
        

    def downloadModel(self,modelURL):

       fileName= os.path.basename(modelURL)
       self.modelName =fileName[:fileName.index('.')]

       self.cacheDir ="./pretrained_model"
       os.makedirs(self.cacheDir,exist_ok=True)

       get_file(fname=fileName,origin=modelURL,cache_dir=self.cacheDir,cache_subdir="checkpoints",extract=True)  
        
       
    def loadModel(self):
        print("Loading Model " self.modelName)
        #tf.keras.backend.clear_session()
        self.model = tf.saved_model.load(os.path.join(self.cacheDir,"checkpoints",self.modelName,"saved_model"))

        print("Model" self.modelName "loaded successfully...")

    
    def createBoundinBox(self,image):
        inputTensor = cv2.cvtColor(image.copy(),cv2.COLOR_BGR2RGB)
        inputTensor = tf.convert_to_tensor(inputTensor,dtype=tf.uint8)
        inputTensor = inputTensor[tf.newaxis,...]

        detections = self.model(inputTensor)

        bboxs = detections['detection_boxes'][0].numpy()
        classIndexes = detections['detection_classes'][0].numpy().astype(np.int32)
        classScores = detections['detection_scores'][0].numpy

        imH,imW,imC =image.shape

        if len(bboxs) != 0 :
            for i in range(0,len(bboxs)):
                bbox = tuple(bboxs[i].tolist())
                classConfidence = classScores[i]
                classIndex = classIndexes[i]

                classLblelText = self.classesList[classIndex]
                classColor = self.colorList[classIndex]


                displayText ='{}: {}%'.format(classLblelText,classConfidence)

                ymin, xmin, ymax, xmax = bbox

                print(ymin,xmin,ymax,xmax)
                break

    def pedictImage(self,imagePath):
        image = cv2.imread(imagePath)

        self.createBoundinBox(image)


        cv2.imshow("result",image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

and i got this error after run the method self.createBoundinBox(image) in the main:

File "d:\TensorflowObjectDetection\Detector.py", line 60, in createBoundinBox
    classConfidence = classScores[i]
TypeError: 'method' object is not subscriptable.

does anyone know how to solve it ,please help .

CodePudding user response:

I think its because you forgot the brackets in this line

classScores = detections['detection_scores'][0].numpy

I think it should be:

classScores = detections['detection_scores'][0].numpy()

When you call it without the brackets you are calling a method or a function which you cannot subscript like this method[]. That is what the error is telling you.

CodePudding user response:

I'm going to take a wild guess here, and say that the line that declares classScores, which is currently this:

classScores = detections['detection_scores'][0].numpy

should be this:

classScores = detections['detection_scores'][0].numpy().astype(np.int32)

in this context, the .numpy is a method that you call, which itself is not subscriptable, meaning that you can't use index notation on it. This makes sense because again, it's a method, and not an array or list or whatever.

  • Related