I used a pre-trained model vgg19 to train it on my own data and make prediction on my 9 classes by using decode_predictions. I understood that decode_predictions works only for ImageNet (no. of classes = 1000). So I rewrite my own decode_prediction function. When I want to predict on my folder of image, I am facing this error:
---------------------------------------------------------------------------
error Traceback (most recent call last)
/tmp/ipykernel_17/3874189441.py in <module>
53 cv2.putText(original, "Label: {}, {:.2f}%".format(label, prob * 100), (10, 30),
54 cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
---> 55 cv2.imshow('frame',original)
56 cv2.waitKey(0)
error: OpenCV(4.5.4) /tmp/pip-req-build-jpmv6t9_/opencv/modules/highgui/src/window.cpp:1274: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'
Here my decode_prediction function:
def decode_prediction(preds, top=9, class_list_path='../input/new_classes.json'):
if len(preds.shape) != 2 or preds.shape[1] != 9: # your classes number
raise ValueError('`decode_predictions` expects '
'a batch of predictions '
'(i.e. a 2D array of shape (samples, 1000)). '
'Found array with shape: ' + str(preds.shape))
index_list = json.load(open(class_list_path))
results = []
for pred in preds:
top_indices = pred.argsort()[-top:][::-1]
result = [tuple(index_list[str(i)]) + (pred[i],) for i in top_indices]
result.sort(key=lambda x: x[2], reverse=True)
results.append(result)
return results
And here my code to predict on my image folder where I get the error:
import os
import json
import cv2
import argparse
import numpy as np
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image as image_utils
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
# Construct argument parser and parse the arguments
argument_parser = argparse.ArgumentParser()
# First two arguments specifies our only argument "image" with both short-/longhand versions where either
# can be used
# This is a required argument, noted by required=True, the help gives additional info in the terminal
# if needed
argument_parser.add_argument("-i", "--image", required=True, help="path to the input image")
# Set path to files
img_path = "../input/img_val"
files = os.listdir(img_path)
print("[INFO] loading and processing images...")
for filename in files:
# Passing the entire path of the image file
file= os.path.join(img_path, filename)
# Load original via OpenCV, so we can draw on it and display it on our screen
original = cv2.imread(file)
image = image_utils.load_img(file, target_size=(224, 224))
image = image_utils.img_to_array(image)
image = np.expand_dims(image, axis=0)
image = preprocess_input(image)
print("[INFO] loading network...")
m=load_model('/kaggle/working/model_hemato.h5')
print("[INFO] classifying image...")
predictions = m.predict(image) # Classify the image (NumPy array with 1000 entries)
P = decode_prediction(predictions) # Get the ImageNet Unique ID of the label, along with human-readable label
print(P)
# Loop over the predictions and display the rank-5 (5 epochs) predictions + probabilities to our terminal
for (i, (imagenetID, label, prob)) in enumerate(P[0]):
print("{}. {}: {:.2f}%".format(i + 1, label, prob * 100))
original = cv2.imread(file)
(imagenetID, label, prob) = P[0][0]
cv2.putText(original, "Label: {}, {:.2f}%".format(label, prob * 100), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.imshow('frame',original)
cv2.waitKey(0)