TypeError: only integer scalar arrays can be converted to a scalar index (python)

Viewed 204

i tried to create a python script for detect the object in a picture and return the similar images, but it return always an error:

TypeError: only integer scalar arrays can be converted to a scalar index

the ids : is the matrix returned after the detection; and it returned perfectly but the problem is only in the last line: scores = [img_paths[id] for id in ids].

My code :

from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
#from feature_extractor import FeatureExtractor
from datetime import datetime
from flask import Flask, request, render_template
from pathlib import Path
from keras.optimizers import Adam
from tensorflow.keras.layers import Dropout, Dense, Activation, Flatten


class FeatureExtractor:
   def __init__(self):
       input_shape = (224, 224, 3)
       base_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)
       
       for layer in base_model.layers:
           layer.trainable = False
       last = base_model.layers[-1].output
       x = Flatten()(last)
       x = Dense(1000, activation='relu', name='fc1')(x)
       x = Dropout(0.3)(x)
       x = Dense(10, activation='softmax', name='predictions')(x)
       model = Model(base_model.input, x)
       model.compile(optimizer=Adam(lr=0.001),
       loss = 'categorical_crossentropy',metrics=['accuracy'])
       self.model = Model(inputs=base_model.input, outputs=base_model.layers[-1].output)

   def extract(self, img):
       """
       Extract a deep feature from an input image
       Args:
     img: from PIL.Image.open(path) or tensorflow.keras.preprocessing.image.load_img(path)

       Returns:
           feature (np.ndarray): deep feature with the shape=(4096, )
       """
       img = img.resize((224, 224))  # VGG must take a 224x224 img as an input
       img = img.convert('RGB')  # Make sure img is color
       x = image.img_to_array(img)  # To np.array. Height x Width x Channel. dtype=float32
       x = np.expand_dims(x, axis=0)  # (H, W, C)->(1, H, W, C), where the first elem is the number of img
       x = preprocess_input(x)  # Subtracting avg values for each pixel
       feature = self.model.predict(x)[0]  # (1, 4096) -> (4096, )
       return feature / np.linalg.norm(feature)  # Normalize


path = "/home/virtuag/www/storage/searchSCB.jpg"


img =  Image.open(path) 
app = Flask(__name__)

fe = FeatureExtractor()
features = []
img_paths = []
for feature_path in Path("/home/virtuag/www/storage/images_article").glob("*.npy"):
   features.append(np.load(feature_path))
   img_paths.append(Path("/home/virtuag/www/storage/images_article") / (feature_path.stem + ".jpg"))
features = np.array(features)
query = fe.extract(img)
dists = np.linalg.norm(features-query, axis=1)  
ids = np.argsort(dists)[:30]  
scores = [img_paths[id] for id in ids]  
0 Answers
Related