-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage.py
More file actions
80 lines (60 loc) · 2.66 KB
/
image.py
File metadata and controls
80 lines (60 loc) · 2.66 KB
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
77
78
79
80
#import libraries
import streamlit as st
import numpy as np
import cv2
import tensorflow as tf
from PIL import Image
# Load the trained TensorFlow model
model_path = "keras_model.h5"
model = tf.keras.models.load_model(model_path)
# Load the labels
class_labels = open("labels.txt", "r").readlines()
st.title("Image Classification Web App")
# Add an option to choose between image upload and camera capture
option = st.sidebar.selectbox("Select an option", ("Upload Image", "Capture from Camera"))
if option == "Upload Image":
uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
if uploaded_image is not None:
image = Image.open(uploaded_image)
st.image(image, caption="Uploaded Image", use_column_width=True)
# Preprocess the image
image = np.array(image.resize((224, 224))) / 255.0
image = np.expand_dims(image, axis=0)
# Make predictions
prediction = model.predict(image)
predicted_class_index = np.argmax(prediction)
predicted_class = class_labels[predicted_class_index]
confidence = prediction[0][predicted_class_index]
st.write(f"Predicted Class: {predicted_class}")
st.write(f"Confidence: {confidence:.2f}") # Display confidence with 2 decimal places
elif option == "Capture from Camera":
st.write("Camera Capture Mode")
# Open the camera
cap = cv2.VideoCapture(0) # 0 indicates the default camera
if not cap.isOpened():
st.write("Error: Could not open camera.")
st.stop()
stop_camera_button_key = "stop_camera_button" # Unique key for the button
while True:
ret, frame = cap.read()
if not ret:
st.write("Error: Could not read frame from camera.")
break
# Display the captured frame
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
st.image(frame_rgb, channels="RGB", use_column_width=True, caption="Camera Capture")
# Preprocess the captured frame
resized_frame = cv2.resize(frame_rgb, (224, 224)) / 255.0
image = np.expand_dims(resized_frame, axis=0)
# Make predictions
prediction = model.predict(image)
predicted_class_index = np.argmax(prediction)
predicted_class = class_labels[predicted_class_index]
confidence = prediction[0][predicted_class_index]
st.write(f"Predicted Class: {predicted_class}")
st.write(f"Confidence: {confidence:.2f}") # Display confidence with 2 decimal places
# Check for user input to stop camera capture
if st.button("Stop Camera", key=stop_camera_button_key):
break
# Release the camera
cap.release()