ArunkumarCH commited on
Commit
2d42def
·
1 Parent(s): a5f5600

Upload app.py.py

Browse files
Files changed (1) hide show
  1. app.py.py +64 -0
app.py.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ## create streamlit app
3
+
4
+ # import required libraries and modules
5
+ import json
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+
9
+ import torch
10
+ from PIL import Image
11
+ from torchvision import transforms
12
+ from torchvision.models import densenet121
13
+
14
+ import streamlit as st
15
+
16
+ # define prediction function
17
+ def predict(image):
18
+ # load DL model
19
+ model = densenet121(pretrained=True)
20
+
21
+ model.eval()
22
+
23
+ # load classes
24
+ with open('imagenet_class_index.json', 'r') as f:
25
+ classes = json.load(f)
26
+
27
+ # preprocess image
28
+ preprocess = transforms.Compose([
29
+ transforms.Resize(256),
30
+ transforms.CenterCrop(224),
31
+ transforms.ToTensor(),
32
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
33
+ ])
34
+ input_tensor = preprocess(input_image)
35
+ input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
36
+
37
+ # get prediction
38
+ with torch.no_grad():
39
+ output = model(input_batch)
40
+
41
+ pred = torch.nn.functional.softmax(output[0], dim=0).cpu().numpy()
42
+
43
+ # return confidence and label
44
+ confidence = round(max(pred)*100, 2)
45
+ label = classes[str(np.argmax(pred))][1]
46
+
47
+ return confidence, label
48
+
49
+ # define image file uploader
50
+ image = st.file_uploader("Upload image here")
51
+
52
+ # define button for getting prediction
53
+ if image is not None and st.button("Get prediction"):
54
+ # load image using PIL
55
+ input_image = Image.open(image)
56
+
57
+ # show image
58
+ st.image(input_image, use_column_width=True)
59
+
60
+ # get prediction
61
+ confidence, label = predict(input_image)
62
+
63
+ # print results
64
+ "Model is", confidence, "% confident that this image is of a", label