# 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)}") # import streamlit as st # import numpy as np # import cv2 # import torch # from PIL import Image # from tensorflow.keras.models import load_model # from tensorflow.keras.preprocessing import image # from detectron2.engine import DefaultPredictor # from detectron2.config import get_cfg # from detectron2.utils.visualizer import Visualizer # from detectron2.data import MetadataCatalog # # Suppress warnings # import warnings # import tensorflow as tf # warnings.filterwarnings("ignore") # tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # @st.cache_resource # def load_models(): # model_name = load_model('name_model_inception.h5') # model_quality = load_model('type_model_inception.h5') # return model_name, model_quality # model_name, model_quality = load_models() # # Detectron2 setup # @st.cache_resource # def load_detectron_model(fruit_name): # cfg = get_cfg() # cfg.merge_from_file(f"{fruit_name.lower()}.yaml") # cfg.MODEL.WEIGHTS = f"{fruit_name.lower()}_model.pth" # cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # cfg.MODEL.DEVICE = 'cpu' # predictor = DefaultPredictor(cfg) # return predictor, cfg # # Labels # label_map_name = { # 0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya", # 5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", # 10: "Tomato" # } # label_map_quality = {0: "Good", 1: "Mild", 2: "Rotten"} # def predict_fruit(img): # # Preprocess image # img = Image.fromarray(img.astype('uint8'), 'RGB') # img = img.resize((224, 224)) # x = image.img_to_array(img) # x = np.expand_dims(x, axis=0) # x = x / 255.0 # # Predict # pred_name = model_name.predict(x) # pred_quality = model_quality.predict(x) # predicted_name = label_map_name[np.argmax(pred_name, axis=1)[0]] # predicted_quality = label_map_quality[np.argmax(pred_quality, axis=1)[0]] # return predicted_name, predicted_quality, img # def main(): # st.title("Fruit Quality and Damage Detection") # st.write("Upload an image of a fruit to detect its type, quality, and potential damage.") # uploaded_file = st.file_uploader("Choose a fruit image...", type=["jpg", "jpeg", "png"]) # if uploaded_file is not None: # image = Image.open(uploaded_file) # st.image(image, caption="Uploaded Image", use_column_width=True) # if st.button("Analyze"): # predicted_name, predicted_quality, img = predict_fruit(np.array(image)) # st.write(f"Fruit Type: {predicted_name}") # st.write(f"Fruit Quality: {predicted_quality}") # if predicted_name.lower() in ["kaki", "tomato", "strawberry", "pepper", "pear", "peach", "papaya", "watermelon", "grape", "banana", "cucumber"] and predicted_quality in ["Mild", "Rotten"]: # st.write("Detecting damage...") # predictor, cfg = load_detectron_model(predicted_name) # outputs = predictor(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)) # v = Visualizer(np.array(img), MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8) # out = v.draw_instance_predictions(outputs["instances"].to("cpu")) # st.image(out.get_image(), caption="Damage Detection Result", use_column_width=True) # else: # st.write("No damage detection performed for this fruit or quality level.") # if __name__ == "__main__": # main() import streamlit as st import numpy as np import cv2 import torch import os from PIL import Image from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog # Suppress warnings import warnings import tensorflow as tf warnings.filterwarnings("ignore") tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) @st.cache_resource def load_models(): model_name = load_model('name_model_inception.h5') model_quality = load_model('type_model_inception.h5') return model_name, model_quality model_name, model_quality = load_models() # Detectron2 setup @st.cache_resource def load_detectron_model(fruit_name): cfg = get_cfg() config_path = os.path.join('utils', f"{fruit_name.lower()}_config.yaml") cfg.merge_from_file(config_path) model_path = os.path.join('models', f"{fruit_name.lower()}_model.pth") cfg.MODEL.WEIGHTS = model_path cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 cfg.MODEL.DEVICE = 'cpu' predictor = DefaultPredictor(cfg) return predictor, cfg # Labels label_map_name = { 0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya", 5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", 10: "Tomato" } label_map_quality = {0: "Good", 1: "Mild", 2: "Rotten"} def predict_fruit(img): # Preprocess image img = Image.fromarray(img.astype('uint8'), 'RGB') img = img.resize((224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = x / 255.0 # Predict pred_name = model_name.predict(x) pred_quality = model_quality.predict(x) predicted_name = label_map_name[np.argmax(pred_name, axis=1)[0]] predicted_quality = label_map_quality[np.argmax(pred_quality, axis=1)[0]] return predicted_name, predicted_quality, img def main(): st.title("Fruit Quality and Damage Detection") st.write("Upload an image of a fruit to detect its type, quality, and potential damage.") uploaded_file = st.file_uploader("Choose a fruit image...", type=["jpg", "jpeg", "png"]) if uploaded_file is not None: image = Image.open(uploaded_file) st.image(image, caption="Uploaded Image", use_column_width=True) if st.button("Analyze"): predicted_name, predicted_quality, img = predict_fruit(np.array(image)) st.write(f"Fruit Type: {predicted_name}") st.write(f"Fruit Quality: {predicted_quality}") if predicted_name.lower() in ["kaki", "tomato", "strawberry", "pepper", "pear", "peach", "papaya", "watermelon", "grape", "banana", "cucumber"] and predicted_quality in ["Mild", "Rotten"]: st.write("Detecting damage...") try: predictor, cfg = load_detectron_model(predicted_name) outputs = predictor(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)) v = Visualizer(np.array(img), MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8) out = v.draw_instance_predictions(outputs["instances"].to("cpu")) st.image(out.get_image(), caption="Damage Detection Result", use_column_width=True) except Exception as e: st.error(f"Error in damage detection: {str(e)}") else: st.write("No damage detection performed for this fruit or quality level.") if __name__ == "__main__": main()