Esempio n. 1
0
def decode_predictions(preds, top=5):
    """Decodes the prediction result from the model.
  Arguments
    preds: Numpy tensor encoding a batch of predictions.
    top: Integer, how many top-guesses to return.
  Returns
    A list of lists of top class prediction tuples
    `(class_name, class_description, score)`.
    One list of tuples per sample in batch input.
  Raises
    ValueError: In case of invalid shape of the `preds` array (must be 2D).
  """
    return imagenet_utils.decode_predictions(preds, top=top)
Esempio n. 2
0
def upload():
    if request.method == 'POST':
        # Get the file from post request
        f = request.files['image']

        # 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=1)  # ImageNet Decode
        result = str(pred_class[0][0][1])  # Convert to string
        return result
    return None
Esempio n. 3
0
def decode_predictions(preds, top=5):
    return imagenet_utils.decode_predictions(preds, top=top)
Esempio n. 4
0
def decode_predictions(preds, top=5):
    """Decodes the prediction result from the VGG16 model."""
    return imagenet_utils.decode_predictions(preds, top=top)
    # define the model
    model = vgg16.VGG16(include_top=True,
                        weights='imagenet',
                        input_tensor=None,
                        input_shape=None,
                        pooling=None,
                        classes=1000)

    layers_names = [
        layer.name for layer in model.layers
        if (layer.__class__.__name__ == 'Conv2D')
    ]

    prediction = model.predict(pImg)
    print(imagenet_utils.decode_predictions(prediction, top=3)[0])

    for layer_name in layers_names:
        layer_output = model.get_layer(layer_name).output
        model_name = model.name

        if K.image_data_format() == 'channels_first':
            n_features = layer_output.shape.as_list()[1]
        else:
            n_features = layer_output.shape.as_list()[-1]
        print("%s filter n_features %d" % (layer_name, n_features))

        heat_map = generate_heat_map(model, pImg, layer_name, n_features)

        plt.matshow(heat_map)
        plt.title(layer_name)
#
# model = mobilenet.MobileNet(input_shape=None, alpha=1.0, depth_multiplier=1, dropout=1e-3, include_top=True,
#                             weights='imagenet', input_tensor=None, pooling=None, classes=1000)
#
# model = mobilenet_v2.MobileNetV2(input_shape=None, alpha=1.0, include_top=True,
#                                  weights='imagenet', input_tensor=None, pooling=None, classes=1000)
#
# model = nasnet.NASNetMobile(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None,
#                             classes=1000)

model = vgg16.VGG16(include_top=True,
                    weights='imagenet',
                    input_tensor=None,
                    input_shape=None,
                    pooling=None,
                    classes=1000)

model.summary()

# record spend time
begin_time = time.clock()
prediction = model.predict(pImg)
end_time = time.clock()
print('Spend: %f ms' % (end_time - begin_time))

# obtain the top-3 predictions
results = imagenet_utils.decode_predictions(prediction, top=3)
print(results)

assert "Egyptian_cat" in [item[1] for item in results[0]]
Esempio n. 7
0
image = load_img(args["image"], target_size=inputShape)
image = img_to_array(image)

# our input image is now represented as a NumPy array of shape
# (inputShape[0], inputShape[1], 3) however we need to expand the
# dimension by making the shape (1, inputShape[0], inputShape[1], 3)
# so we can pass it through the network

image = np.expand_dims(image, axis=0)
# pre-process the image using the appropriate function based on the
# model that has been loaded (i.e., mean subtraction, scaling, etc.)
image = preprocess(image)

# classify the image
print("[INFO] classifying image with ’{}’...".format(args["model"]))
preds = model.predict(image)
P = imagenet_utils.decode_predictions(preds)

# loop over the predictions and display the rank-5 predictions  +
# probabilities to our terminal
for (i, (imagenetID, label, prob)) in enumerate(P[0]):
    print(f"{i+1}. {label}: {prob*100:.2f}%")

# load the image via OpenCV, draw the top prediction on the image,
# and display the image to our screen
orig = cv2.imread(args["image"])
(imagenetID, label, prob) = P[0][0]
cv2.putText(orig, f"Label: {label}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
            (0, 255, 0), 2)
cv2.imshow("Classification", orig)
cv2.waitKey(0)