Spaces:
Sleeping
Sleeping
File size: 14,819 Bytes
df1d7ff e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d 8773d3c e18493d df1d7ff e18493d df1d7ff e18493d df1d7ff 76c62bb 9f80c53 76c62bb e18493d 9f80c53 df1d7ff 9f80c53 df1d7ff 9f80c53 e18493d 2205388 bd891ff e18493d 83eb0c6 2205388 83eb0c6 2205388 83eb0c6 2205388 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d 83eb0c6 e18493d bd891ff a10b03b 83eb0c6 |
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# import streamlit as st
# # Set title of the app
# st.title("Simple Streamlit App")
# # Add text input
# user_input = st.text_input("Enter your name:")
# # Display the input value
# if user_input:
# st.write(f"Hello, {user_input}!")
# import streamlit as st
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# import numpy as np
# from PIL import Image
# # Load the pre-trained models
# @st.cache_resource
# def load_models():
# model1 = load_model('name_model_inception.h5') # Update with your Hugging Face model path
# model2 = load_model('type_model_inception.h5') # Update with your Hugging Face model path
# return model1, model2
# model1, model2 = load_models()
# # Label mappings
# label_map1 = {
# 0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
# 5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", 10: "Tomato"
# }
# label_map2 = {
# 0: "Good", 1: "Mild", 2: "Rotten"
# }
# # Streamlit app layout
# st.title("Fruit Classifier")
# # Upload image
# uploaded_file = st.file_uploader("Choose an image of a fruit", type=["jpg", "jpeg", "png"])
# if uploaded_file is not None:
# # Display the uploaded image
# img = Image.open(uploaded_file)
# st.image(img, caption="Uploaded Image", use_column_width=True)
# # Preprocess the image
# img = img.resize((224, 224)) # Resize image to match the model input
# img_array = image.img_to_array(img)
# img_array = np.expand_dims(img_array, axis=0)
# img_array = img_array / 255.0 # Normalize the image
# # Make predictions
# pred1 = model1.predict(img_array)
# pred2 = model2.predict(img_array)
# predicted_class1 = np.argmax(pred1, axis=1)
# predicted_class2 = np.argmax(pred2, axis=1)
# # Display results
# st.write(f"**Type Detection**: {label_map1[predicted_class1[0]]}")
# st.write(f"**Condition Detection**: {label_map2[predicted_class2[0]]}")
# !git clone 'https://github.com/facebookresearch/detectron2'
# dist = distutils.core.run_setup("./detectron2/setup.py")
# !python -m pip install {' '.join([f"'{x}'" for x in dist.install_requires])}
# sys.path.insert(0, os.path.abspath('./detectron2'))
# import streamlit as st
# import numpy as np
# import cv2
# import warnings
# # Suppress warnings
# warnings.filterwarnings("ignore", category=FutureWarning)
# warnings.filterwarnings("ignore", category=UserWarning)
# # Try importing TensorFlow
# try:
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# except ImportError:
# st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")
# # Try importing PyTorch and Detectron2
# try:
# import torch
# from detectron2.engine import DefaultPredictor
# from detectron2.config import get_cfg
# from detectron2.utils.visualizer import Visualizer
# from detectron2.data import MetadataCatalog
# except ImportError:
# st.error("Failed to import PyTorch or Detectron2. Please make sure they're installed correctly.")
# # Load the trained models
# try:
# model_path_name = 'name_model_inception.h5'
# model_path_quality = 'type_model_inception.h5'
# detectron_config_path = 'watermelon.yaml'
# detectron_weights_path = 'Watermelon_model.pth'
# model_name = load_model(model_path_name)
# model_quality = load_model(model_path_quality)
# except Exception as e:
# st.error(f"Failed to load models: {str(e)}")
# # Streamlit app title
# st.title("Watermelon Quality and Damage Detection")
# # Upload image
# uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])
# if uploaded_file is not None:
# try:
# # Load the image
# img = image.load_img(uploaded_file, target_size=(224, 224))
# img_array = image.img_to_array(img)
# img_array = np.expand_dims(img_array, axis=0)
# img_array /= 255.0
# # Display uploaded image
# st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
# # Predict watermelon name
# pred_name = model_name.predict(img_array)
# predicted_name = 'Watermelon'
# # Predict watermelon quality
# pred_quality = model_quality.predict(img_array)
# predicted_class_quality = np.argmax(pred_quality, axis=1)
# # Define labels for watermelon quality
# label_map_quality = {
# 0: "Good",
# 1: "Mild",
# 2: "Rotten"
# }
# predicted_quality = label_map_quality[predicted_class_quality[0]]
# # Display predictions
# st.write(f"Fruit Type Detection: {predicted_name}")
# st.write(f"Fruit Quality Classification: {predicted_quality}")
# # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
# if predicted_quality in ["Mild", "Rotten"]:
# st.write("Passing the image to the mask detection model for damage detection...")
# # Load the image again for the mask detection (Detectron2 requires the original image)
# im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)
# # Setup Detectron2 configuration for watermelon
# cfg = get_cfg()
# cfg.merge_from_file(detectron_config_path)
# cfg.MODEL.WEIGHTS = detectron_weights_path
# cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
# cfg.MODEL.DEVICE = 'cpu' # Use CPU for inference
# predictor = DefaultPredictor(cfg)
# predictor.model.load_state_dict(torch.load(detectron_weights_path, map_location=torch.device('cpu')))
# # Run prediction on the image
# outputs = predictor(im)
# # Visualize the predictions
# v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
# out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# # Display the output
# st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)
# except Exception as e:
# st.error(f"An error occurred during processing: {str(e)}")
# import streamlit as st
# import numpy as np
# import cv2
# import warnings
# import os
# # Suppress warnings
# warnings.filterwarnings("ignore", category=FutureWarning)
# warnings.filterwarnings("ignore", category=UserWarning)
# # Try importing TensorFlow
# try:
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# except ImportError:
# st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")
# # Try importing PyTorch and Detectron2
# try:
# import torch
# import detectron2
# except ImportError:
# with st.spinner("Installing PyTorch and Detectron2..."):
# os.system("pip install torch torchvision")
# os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git'")
# import torch
# import detectron2
# from detectron2.engine import DefaultPredictor
# from detectron2.config import get_cfg
# from detectron2.utils.visualizer import Visualizer
# from detectron2.data import MetadataCatalog
# # Load the trained models
# @st.cache_resource
# def load_models():
# try:
# model_path_name = 'name_model_inception.h5'
# model_path_quality = 'type_model_inception.h5'
# model_name = load_model(model_path_name)
# model_quality = load_model(model_path_quality)
# return model_name, model_quality
# except Exception as e:
# st.error(f"Failed to load models: {str(e)}")
# return None, None
# model_name, model_quality = load_models()
# # Streamlit app title
# st.title("Watermelon Quality and Damage Detection")
# # Upload image
# uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])
# if uploaded_file is not None:
# try:
# # Load the image
# img = image.load_img(uploaded_file, target_size=(224, 224))
# img_array = image.img_to_array(img)
# img_array = np.expand_dims(img_array, axis=0)
# img_array /= 255.0
# # Display uploaded image
# st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
# # Predict watermelon name
# pred_name = model_name.predict(img_array)
# predicted_name = 'Watermelon'
# # Predict watermelon quality
# pred_quality = model_quality.predict(img_array)
# predicted_class_quality = np.argmax(pred_quality, axis=1)
# # Define labels for watermelon quality
# label_map_quality = {
# 0: "Good",
# 1: "Mild",
# 2: "Rotten"
# }
# predicted_quality = label_map_quality[predicted_class_quality[0]]
# # Display predictions
# st.write(f"Fruit Type Detection: {predicted_name}")
# st.write(f"Fruit Quality Classification: {predicted_quality}")
# # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
# if predicted_quality in ["Mild", "Rotten"]:
# st.write("Passing the image to the mask detection model for damage detection...")
# # Load the image again for the mask detection (Detectron2 requires the original image)
# im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)
# # Setup Detectron2 configuration for watermelon
# @st.cache_resource
# def load_detectron_model():
# cfg = get_cfg()
# cfg.merge_from_file("watermelon.yaml")
# cfg.MODEL.WEIGHTS = "Watermelon_model.pth"
# cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
# cfg.MODEL.DEVICE = 'cpu' # Use CPU for inference
# predictor = DefaultPredictor(cfg)
# return predictor
# predictor = load_detectron_model()
# # Run prediction on the image
# outputs = predictor(im)
# # Visualize the predictions
# v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
# out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# # Display the output
# st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)
# except Exception as e:
# st.error(f"An error occurred during processing: {str(e)}")
# ///////////////////////////////////Working
import streamlit as st
import numpy as np
import cv2
import warnings
import os
# Suppress warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
# Try importing TensorFlow
try:
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
except ImportError:
st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")
# Try importing PyTorch and Detectron2
try:
import torch
import detectron2
except ImportError:
with st.spinner("Installing PyTorch and Detectron2..."):
os.system("pip install torch torchvision")
os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git'")
import torch
import detectron2
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog
# Load the trained models
@st.cache_resource
def load_models():
try:
model_path_name = 'name_model_inception.h5'
model_path_quality = 'type_model_inception.h5'
model_name = load_model(model_path_name)
model_quality = load_model(model_path_quality)
return model_name, model_quality
except Exception as e:
st.error(f"Failed to load models: {str(e)}")
return None, None
model_name, model_quality = load_models()
# Setup Detectron2 configuration for watermelon
@st.cache_resource
def load_detectron_model():
cfg = get_cfg()
cfg.merge_from_file("watermelon.yaml")
cfg.MODEL.WEIGHTS = "Watermelon_model.pth"
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
cfg.MODEL.DEVICE = 'cpu' # Use CPU for inference
predictor = DefaultPredictor(cfg)
return predictor, cfg
predictor, cfg = load_detectron_model()
# Streamlit app title
st.title("Watermelon Quality and Damage Detection")
# Upload image
uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
try:
# Load the image
img = image.load_img(uploaded_file, target_size=(224, 224))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0
# Display uploaded image
st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
# Predict watermelon name
pred_name = model_name.predict(img_array)
predicted_name = 'Watermelon'
# Predict watermelon quality
pred_quality = model_quality.predict(img_array)
predicted_class_quality = np.argmax(pred_quality, axis=1)
# Define labels for watermelon quality
label_map_quality = {
0: "Good",
1: "Mild",
2: "Rotten"
}
predicted_quality = label_map_quality[predicted_class_quality[0]]
# Display predictions
st.write(f"Fruit Type Detection: {predicted_name}")
st.write(f"Fruit Quality Classification: {predicted_quality}")
# If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
if predicted_quality in ["Mild", "Rotten"]:
st.write("Passing the image to the mask detection model for damage detection...")
# Load the image again for the mask detection (Detectron2 requires the original image)
im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)
# Run prediction on the image
outputs = predictor(im)
# Visualize the predictions
v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# Display the output
st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)
except Exception as e:
st.error(f"An error occurred during processing: {str(e)}")
|