File size: 2,219 Bytes
b8e4c73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
# All imports
import streamlit as st
import tensorflow as tf
from tensorflow import keras
from PIL import Image
from tensorflow.keras.preprocessing import image
import io
from collections import Counter
import numpy as np

def load_image():
    uploaded_file = st.file_uploader(label='Pick an image to test')
    if uploaded_file is not None:
        image_data = uploaded_file.getvalue()
        st.image(image_data)

def load_models():
    model_name = 'Model/model.h5'
    model = tf.keras.models.load_model(model_name) 
    return model

def load_labels():
    with open('Oxford-102_Flower_dataset_labels.txt', 'r') as file:
        data = file.read().splitlines()
    flower_dict = dict(enumerate(data, 1))
    return flower_dict
    
def load_image():
     uploaded_file = st.file_uploader(label='Pick an image to test')
     if uploaded_file is not None:
         image_data = uploaded_file.getvalue()
         st.image(image_data)
         img = Image.open(io.BytesIO(image_data))
         img = img.resize((224,224))
         return img
     else:
         return None
    
def predict(model, categories, img):
    img_array = tf.keras.preprocessing.image.img_to_array(img)
    prediction = [img_array]
    prediction_test = [1]
    test_ds = tf.data.Dataset.from_tensor_slices((prediction, prediction_test))
    test_ds = test_ds.cache().batch(32).prefetch(buffer_size = tf.data.experimental.AUTOTUNE)

    prediction = model.predict(test_ds)
    prediction_dict = dict(enumerate(prediction.flatten(), 1))
    k = Counter(prediction_dict)
 
    # Finding 3 highest values
    high = k.most_common(3)

    percentages = []
    flowers = []
    for i in high:
        key, value = i
        flowers.append(categories[key])
        percentages.append(np.round(value*100, 2))
    return flowers, percentages

def main():
    st.title('Oxford 102 Flower CLassification Demo')
    model = load_models()
    categories = load_labels()
    image = load_image()
    result = st.button('Run on image')
    if result:
        st.write('Calculating results...')
        flowers, percentages = predict(model, categories, image)
        st.text(flowers)
        st.text(percentages)

if __name__ == '__main__':
    main()