Spaces:
Sleeping
Sleeping
Create util.py
Browse files
util.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
|
3 |
+
import streamlit as st
|
4 |
+
from PIL import ImageOps, Image
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
def set_background(image_file):
|
9 |
+
"""
|
10 |
+
This function sets the background of a Streamlit app to an image specified by the given image file.
|
11 |
+
|
12 |
+
Parameters:
|
13 |
+
image_file (str): The path to the image file to be used as the background.
|
14 |
+
|
15 |
+
Returns:
|
16 |
+
None
|
17 |
+
"""
|
18 |
+
with open(image_file, "rb") as f:
|
19 |
+
img_data = f.read()
|
20 |
+
b64_encoded = base64.b64encode(img_data).decode()
|
21 |
+
style = f"""
|
22 |
+
<style>
|
23 |
+
.stApp {{
|
24 |
+
background-image: url(data:image/png;base64,{b64_encoded});
|
25 |
+
background-size: cover;
|
26 |
+
}}
|
27 |
+
</style>
|
28 |
+
"""
|
29 |
+
st.markdown(style, unsafe_allow_html=True)
|
30 |
+
|
31 |
+
|
32 |
+
def classify(image, model, class_names):
|
33 |
+
"""
|
34 |
+
This function takes an image, a model, and a list of class names and returns the predicted class and confidence
|
35 |
+
score of the image.
|
36 |
+
|
37 |
+
Parameters:
|
38 |
+
image (PIL.Image.Image): An image to be classified.
|
39 |
+
model (tensorflow.keras.Model): A trained machine learning model for image classification.
|
40 |
+
class_names (list): A list of class names corresponding to the classes that the model can predict.
|
41 |
+
|
42 |
+
Returns:
|
43 |
+
A tuple of the predicted class name and the confidence score for that prediction.
|
44 |
+
"""
|
45 |
+
# convert image to (224, 224)
|
46 |
+
image = ImageOps.fit(image, (224, 224), Image.Resampling.LANCZOS)
|
47 |
+
|
48 |
+
# convert image to numpy array
|
49 |
+
image_array = np.asarray(image)
|
50 |
+
|
51 |
+
# normalize image
|
52 |
+
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
|
53 |
+
|
54 |
+
# set model input
|
55 |
+
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
|
56 |
+
data[0] = normalized_image_array
|
57 |
+
|
58 |
+
# make prediction
|
59 |
+
prediction = model.predict(data)
|
60 |
+
# index = np.argmax(prediction)
|
61 |
+
index = 0 if prediction[0][0] > 0.95 else 1
|
62 |
+
class_name = class_names[index]
|
63 |
+
confidence_score = prediction[0][index]
|
64 |
+
|
65 |
+
return class_name, confidence_score
|