0

This is sentiment analysis project and i am getting this error

Nudity-Detection-Model.h5
Traceback (most recent call last):
  File "c:\Users\kvidushi\Desktop\Mini_project\script\vapp.py", line 214, in <module> 
    main()
  File "c:\Users\kvidushi\Desktop\Mini_project\script\vapp.py", line 208, in main     
    model = load_model('Nudity-Detection-Model.h5')
  File "c:\Users\kvidushi\Desktop\Mini_project\script\vapp.py", line 59, in load_model
    raise ValueError("saved_model_path must be the valid directory of a saved model to load.")
ValueError: saved_model_path must be the valid directory of a saved model to load.

My script file is:

import json
import cv2
import os
import time
from os import listdir
from os.path import isfile, join, exists, isdir, abspath
from keras.models import load_model

import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow_hub as hub
import matplotlib.pyplot as plt

IMAGE_DIM = 224   # required/default image dimensionality

def load_images(image_paths, image_size, verbose=True):
    # Function for loading images into numpy arrays for passing to model.predict
    # inputs:
    #     image_paths: list of image paths to load
    #     image_size: size into which images should be resized
    #     verbose: show all of the image path and sizes loaded
    
    # outputs:
    #     loaded_images: loaded images on which keras model can run predictions
    #     loaded_image_indexes: paths of images which the function is able to process
    
    
    loaded_images = []
    loaded_image_paths = []

    if isdir(image_paths):
        parent = abspath(image_paths)
        image_paths = [join(parent, f) for f in listdir(image_paths) if isfile(join(parent, f))]
    elif isfile(image_paths):
        image_paths = [image_paths]

    for img_path in image_paths:
        try:
            if verbose:
                print(img_path, "size:", image_size)
            image = keras.preprocessing.image.load_img(img_path, target_size=image_size)
            image = keras.preprocessing.image.img_to_array(image)
            # print(image.dtype)
            # print(image.shape)
            # print(image)
            image /= 255
            loaded_images.append(image)
            loaded_image_paths.append(img_path)
        except Exception as ex:
            print("Image Load Failure: ", img_path, ex)
    
    return np.asarray(loaded_images), loaded_image_paths


def load_model(model_path):
    print(model_path)
    if model_path is None or not exists(model_path):
        raise ValueError("saved_model_path must be the valid directory of a saved model to load.")
    
    model = tf.keras.models.load_model(model_path)
    #model = tf.keras.models.load_model(model_path, custom_objects={'KerasLayer':hub.KerasLayer})
    # model.summary()
    print(model.summary())
    return model


def classify(model, input_paths, image_dim=IMAGE_DIM):
    """ Classify given a model, input paths (could be single string), and image dimensionality...."""
    images, image_paths = load_images(input_paths, (image_dim, image_dim))
    probs = classify_nd(model, images)
    # print(type(probs))
    return probs


def classify_nd(model, nd_images):
    """ Classify given a model, image array (numpy)...."""

    model_preds = model.predict(nd_images)
    # preds = np.argsort(model_preds, axis = 1).tolist()
    
    categories = ['drawings', 'hentai', 'neutral', 'porn', 'sexy']

    probs = []
    single_probs = {}
    cnt=0
    for i, single_preds in enumerate(model_preds):
        cnt=cnt+1
        
        for j, pred in enumerate(single_preds):
            if categories[j] in single_probs.keys():
                single_probs[categories[j]] = single_probs[categories[j]] + float(pred)
            else:
                single_probs[categories[j]]=float(pred)
        
    print(cnt)
    for i in single_probs.keys():
        # print(single_probs[i])
        single_probs[i]=single_probs[i]/cnt
    probs.append(single_probs)
    return probs
def predict(model,img_paths):
    # for img in img_paths:
    image_preds = classify(model, img_paths, IMAGE_DIM)
    data=image_preds[0]
    category= list(data.keys()) 
    values = list(data.values())
    fig = plt.figure(figsize = (10, 5)) 
  
    # creating the bar plot 
    plt.bar(category, values, color ='maroon',  
            width = 0.4) 
    
    plt.xlabel("Categories") 
    plt.ylabel("values") 
    plt.title("Nudity Detection Model") 
     
    print(json.dumps(image_preds, indent=2), '\n')
    plt.show()
def get_frames(inputFile,outputFolder,step,count):

  '''
  Input:
    inputFile - name of the input file with directoy
    outputFolder - name and path of the folder to save the results
    step - time lapse between each step (in seconds)
    count - number of screenshots
  Output:
    'count' number of screenshots that are 'step' seconds apart created from video 'inputFile' and stored in folder 'outputFolder'
  Function Call:
    get_frames("test.mp4", 'data', 10, 10)
  '''

  #initializing local variables
  step = step
  frames_count = count

  currentframe = 0
  frames_captured = 0

  #creating a folder
  try:  
      # creating a folder named data 
      if not os.path.exists(outputFolder): 
          os.makedirs(outputFolder) 
    
  #if not created then raise error 
  except OSError: 
      print ('Error! Could not create a directory') 
  
  #reading the video from specified path 
  cam = cv2.VideoCapture(inputFile) 

  #reading the number of frames at that particular second
  frame_per_second = cam.get(cv2.CAP_PROP_FPS)
  print( frame_per_second)

  while (True):
      ret, frame = cam.read()
      if ret:
          if currentframe > (step*frame_per_second):  
              currentframe = 0
              #saving the frames (screenshots)
              name = './data/frame' + str(frames_captured) + '.jpg'
              print ('Creating...' + name) 
              
              cv2.imwrite(name, frame)       
              frames_captured+=1
              
              #breaking the loop when count achieved
              if frames_captured > frames_count-1:
                ret = False
          currentframe += 1           
      if ret == False:
          break
  
  #Releasing all space and windows once done
  cam.release()
  cv2.destroyAllWindows()

        
    
def main():   

    # img_paths=[]
    # img_paths.append("1.jpg")
    # img_paths.append("2.jpg")
    # img_paths.append("3.jpg")
    # img_paths.append("4.jpg")
    # img_paths.append("5.jpg")
    # img_paths.append("6.jpg")
    # img_paths.append("7.jpg")
    # img_paths.append("8.jpg")
    # img_paths.append("9.jpg")
    # img_paths.append("10.jpg")
    # img_paths.append("11.jpg")
    # img_paths.append("12.jpg")
    # img_paths.append("13.jpg")
    # img_paths.append("14.jpg")
    # img_paths.append("15.jpg")
    
    
    
    
    
    
    get_frames("1.mp4","data",5,20)
    model = load_model('Nudity-Detection-Model.h5')
    predict(model,"data")
    


if __name__ == "__main__":
    main()

It is asking for this file: Nudity_detection_model.h5 I have put this file in same folder.Still it is not able to recognize it. I tried adding double quotes and single quotes and import load_model but still the error is same. can anyone help me

  • The error is not related to your script. Your cuda/environment is not set up properly. This could be helpful - https://stackoverflow.com/questions/59823283/could-not-load-dynamic-library-cudart64-101-dll-on-tensorflow-cpu-only-install – PermanentPon Jun 07 '21 at 17:03
  • @PermanentPon no, but that can be ignored, my main error message is value error. Can you look into that please – vidushi kothari Jun 07 '21 at 17:30
  • Remove this import `from keras.models import load_model`. – PermanentPon Jun 07 '21 at 17:54
  • Something is wrong with the path. Either the model doesn't exist or you typed something wrong. Notice `*Nudity-Detection-Model.h5*` in your output. You should see `*` character – PermanentPon Jun 07 '21 at 18:00
  • @PermanentPon hey that was because i want to make it bold. Here i was trying to print the value of model .model = load_model('Nudity-Detection-Model.h5') – vidushi kothari Jun 08 '21 at 06:41
  • to check if what value it prints – vidushi kothari Jun 08 '21 at 06:46
  • Anyway you see this error because python can't find this file. Make sure your path is correct – PermanentPon Jun 08 '21 at 06:51
  • One suggestion - use an absolute path for you model and not relative. So it should be `c:\Users\...\Nudity-Detection-Model.h5` – PermanentPon Jun 08 '21 at 06:55
  • Make sure that you're in the correct working directory before loading the model. You can try to put: `import os; print(os.getcwd())` before you load the model and see if it is what you expect – Ehab Ibrahim Jun 08 '21 at 08:28

0 Answers0