def predict(image_response): image_response = base64.b64decode(image_response) t = time.time() img = image.load_img(BytesIO(image_response), target_size=(224, 224)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = preprocess_input(img) with graph.as_default(): preds = model.predict(img) print(time.time() - t) # decode the results into a list of tuples (class, description, probability) # (one such list for each sample in the batch) print(decode_predictions(preds)) return decode_predictions(preds,top=3)[0]
def predict(self, uploaded_image: TemporaryUploadedFile) -> (List, Image): """ Read image and predict category """ # convert the image pixels to a numpy array image = img_to_array(Image.open(uploaded_image)) # resize (crop) to vgg16 size (331, 331, 3) image = smart_resize(image, (331, 331)) # grab a RGB preview for frontend rgb_preview = Image.fromarray(np.uint8(image)).convert('RGB') # reshape data for the model, add new axis (1, 224, 224, 3) image = np.expand_dims(image, axis=0) # prepare the image for the VGG model (subtracts the mean RGB channels) image = preprocess_input(image) # predict the probability across all output classes what = self.model.predict(image) # convert the probabilities to class labels labels = decode_predictions(what, top=3) # make it readable labels = self.labels_to_percents(labels) return labels, rgb_preview
def predict(image): model = NASNetLarge() pred = model.predict(image) decoded_predictions = decode_predictions(pred, top=10) response = 'NASNetLarge predictions: ' + str(decoded_predictions[0][0:5]) print(response) np.argmax(pred[0]) return response
def upload(): if request.method == 'POST': # Get the file from post request f = request.files['file'] # Save the file to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) # Make prediction preds = model_predict(file_path, model) pred_class = decode_predictions(preds, top=5) # ImageNet Decode result = str(pred_class[0][0][1]) # Convert to string return 'The model NASNetLarge predicts this image as : ' + result return None
def upload(): if request.method == 'POST': # Get the file from post request f = request.files['file'] # Save the file to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) # Make prediction preds = model_predict(file_path, model) # Process your result for human # pred_class = preds.argmax(axis=-1) # Simple argmax pred_class = decode_predictions(preds, top=5) # ImageNet Decode result = str(pred_class[0][0][1]) # Convert to string return result return None
from keras.preprocessing import image from keras.applications.nasnet import preprocess_input, decode_predictions import numpy as np import pandas as pd model = pd.read_pickle("nasnetmobile.model") img_path = 'tshirt.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode the results into a list of tuples (class, description, probability) # (one such list for each sample in the batch) print('Predicted:', decode_predictions(preds, top=3)) # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), #(u'n01871265', u'tusker', 0.1122357), #(u'n02504458', u'African_elephant', 0.061040461)]
from keras.applications.nasnet import preprocess_input from keras.applications.nasnet import decode_predictions from keras.applications.nasnet import NASNetLarge model = NASNetLarge(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000) for i in range(0, 5): print('-----------------------------------------------') # load an image from file image = load_img('../resources/wolf_' + str(i + 1) + '.jpg', target_size=(331, 331)) # convert the image pixels to a numpy array image = img_to_array(image) # reshape data for the model image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2])) # prepare the image for the VGG model image = preprocess_input(image) # predict the probability across all output classes yhat = model.predict(image) # convert the probabilities to class labels label = decode_predictions(yhat) for i in range(0, len(label[0])): # retrieve the most likely result, e.g. highest probability labelTemp = label[0][i] # print the classification print('%s (%.2f%%)\n' % (labelTemp[1], labelTemp[2] * 100))
# ResNet, MobileNet or other # ################################################################################ #See available models at https://keras.io/applications/#documentation-for-individual-models model_nasnet = nasnet.NASNetMobile(weights="imagenet", input_shape=(img_width, img_height, 3)) test_generator = ImageDataGenerator( preprocessing_function=nasnet.preprocess_input).flow_from_directory( test_data_dir, target_size=(img_width, img_height), batch_size=batch_size, shuffle=False, ) predicted = model_nasnet.predict_generator(test_generator, steps=nb_test_samples // batch_size) y_pred = nasnet.decode_predictions(predicted, top=1) results = pd.DataFrame(np.concatenate(y_pred), columns=['imagenet_id', 'predict_class', 'percent']) results["filename"] = test_generator.filenames print(results) results.to_csv("predicted.csv", sep=";") ################################################################################ # TO DO # ################################################################################ # # 1. Train for the apples # 2. Test other models
from keras.applications.nasnet import NASNetLarge from keras.preprocessing import image from keras.applications.nasnet import preprocess_input, decode_predictions from PIL import Image import numpy as np import os import time model = NASNetLarge(weights='imagenet') images = os.listdir('resources') times = [] for img_path in images: img = image.load_img('resources/' + img_path, target_size=(331, 331)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) start_time = time.time() preds = model.predict(x) times.append(time.time() - start_time) # decode the results into a list of tuples (class, description, probability) # (one such list for each sample in the batch) print('Predicted for ' + img_path + ": ", decode_predictions(preds, top=3)[0]) print("Average prediction time: %s seconds" % np.mean(times))