def test_decode_predictions(): x = np.zeros((2, 1000)) x[0, 372] = 1.0 x[1, 549] = 1.0 outs = utils.decode_predictions(x, top=1) scores = [out[0][2] for out in outs] assert scores[0] == scores[1] # the numbers of columns and ImageNet classes are not identical. with pytest.raises(ValueError): utils.decode_predictions(np.ones((2, 100)))
def predict(): data = { "success": False } if request.method == "POST": if request.files.get("image"): file = request.files['image'] # image = request.files["image"].read() image = file.read() image = Image.open(io.BytesIO(image)) image = prepare_image(image, target=(224, 224)) with graph.as_default(): preds = model.predict(image) results = imagenet_utils.decode_predictions(preds) data["predictions"] = [] for (imagenetID, label, prob) in results[0]: r = {"label": label, "probability": float(prob)} data["predictions"].append(r) data["success"] = True f = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(f) return jsonify(data)
def get_preds(model): size = model.input_shape[1] filename = os.path.join(os.path.dirname(__file__), 'data', 'cat.jpg') batch = KE.preprocess_input( img_to_array(load_img(filename, target_size=(size, size)))) batch = np.expand_dims(batch, 0) pred = decode_predictions(model.predict(batch), backend=K, utils=utils) return pred
def _test_application(name, input_shape=(224, 224, 3), last_dim=1000, label='bull_mastiff'): classifier, preprocess_input = Classifiers.get(name) model = classifier(input_shape=input_shape, weights='imagenet') output_shape, preds = _get_output_shape(model, preprocess_input) assert output_shape == (None, last_dim) names = [p[1] for p in decode_predictions(preds, **KWARGS)[0]] assert label in names[:3]
maxpool = model.get_layer(name='block5_pool') shape = maxpool.output_shape[1:] dense = model.get_layer(name='fc1') layer_utils.convert_dense_weights_data_format( dense, shape, 'channels_first') if K.backend() == 'tensorflow': warnings.warn('You are using the TensorFlow backend, yet you ' 'are using the Theano ' 'image data format convention ' '(`image_data_format="channels_first"`). ' 'For best performance, set ' '`image_data_format="channels_last"` in ' 'your Keras config ' 'at ~/.keras/keras.json.') return model if __name__ == '__main__': model = VGG19(include_top=True, weights='imagenet') img_path = 'cat.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) print('Input image shape:', x.shape) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
def decode_predictions(*args, **kwargs): return imagenet_utils.decode_predictions(*args, **kwargs)
# Load pre-trained models # ------------------------------------- resnet50 = resnet.ResNet50(weights='imagenet') resnet101 = resnet.ResNet101(weights='imagenet') resnet152 = resnet.ResNet152(weights='imagenet') # ------------------------------------- # Helper functions # ------------------------------------- def path_to_tensor(image_path, target_size): image = load_img(image_path, target_size=target_size) tensor = img_to_array(image) tensor = np.expand_dims(tensor, axis=0) return tensor # ------------------------------------- # Make predictions # ------------------------------------- image_path = 'images/dog.jpeg' image_tensor = path_to_tensor(image_path, (224, 224)) pred_resnet50 = resnet50.predict(image_tensor) print("Resnet50: {}".format(decode_predictions(pred_resnet50, top=1))) pred_resnet101 = resnet101.predict(image_tensor) print("Resnet101: {}".format(decode_predictions(pred_resnet101, top=1))) pred_resnet152 = resnet152.predict(image_tensor) print("Resnet152: {}".format(decode_predictions(pred_resnet152, top=1)))
model.load_weights(weights_path) if K.backend() == 'theano': convert_all_kernels_in_model(model) return model def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': model = InceptionV1(include_top=True, weights='imagenet') img_path = 'elephant.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) # Extra shift to remove 'background' as entry0 preds_1000 = preds[:, 1:] print('Predicted:', decode_predictions(preds_1000))
def decode_predictions(*args, **kwargs): return imagenet_utils.decode_predictions( *args, **kwargs)
def decode_predictions(*args, **kwargs): kwargs['backend'] = backend kwargs['utils'] = keras_utils return utils.decode_predictions(*args, **kwargs)