File size: 1,655 Bytes
cbb3697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

## create streamlit app

# import required libraries and modules
import json
import numpy as np
import matplotlib.pyplot as plt

import torch
from PIL import Image
from torchvision import transforms
from torchvision.models import densenet121

import streamlit as st

# define prediction function
def predict(image):
    # load DL model
    model = densenet121(pretrained=True)

    model.eval()

    # load classes
    with open('imagenet_class_index.json', 'r') as f:
        classes = json.load(f)

    # preprocess image
    preprocess = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
    input_tensor = preprocess(input_image)
    input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model

    # get prediction
    with torch.no_grad():
        output = model(input_batch)

    pred = torch.nn.functional.softmax(output[0], dim=0).cpu().numpy()

    # return confidence and label
    confidence = round(max(pred)*100, 2)
    label = classes[str(np.argmax(pred))][1]

    return confidence, label

# define image file uploader
image = st.file_uploader("Upload image here")

# define button for getting prediction
if image is not None and st.button("Get prediction"):
    # load image using PIL
    input_image = Image.open(image)

    # show image
    st.image(input_image, use_column_width=True)

    # get prediction
    confidence, label = predict(input_image)

    # print results
    "Model is", confidence, "% confident that this image is of a", label