Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444520 unmodified lines666768697071727374753 unmodified lines798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359import osimport streamlit as stfrom ultralytics import YOLOMODEL_REPO = "FERJI/DetectNano2"KF_API_KEY = os.getenv("KF_API_KEY")mod1_path = "DetectNano2/mod1.pt"mod2_path = "DetectNano2/mod2.pt"mod3_path = "DetectNano2/mod3.pt"if not (os.path.exists(mod1_path) and os.path.exists(mod2_path) and os.path.exists(mod3_path)):clone_status = os.system(f"git clone https://user:{KF_API_KEY}@huggingface.co/{MODEL_REPO}")if clone_status != 0:exit(1)@st.cache_resourcedef load_models():model_1 = YOLO(mod1_path)model_2 = YOLO(mod2_path)model_3 = YOLO(mod3_path)return model_1, model_2, model_3model_1, model_2, model_3 = load_models()import cv2from ensemble_boxes import soft_nmsimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom collections import Counterfrom PIL import Imageimport concurrent.futuresimport threadingimport timest.header('Polymersomes Detection from TEM Images')with st.sidebar.expander("ℹ️ About This App", expanded=False):st.markdown(20 unmodified lines**Zenodo DOI:** [https://doi.org/10.5281/zenodo.14995364](https://doi.org/10.5281/zenodo.14995364)""")uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "png", "jpeg", "tif"])button_container = st.sidebar.empty()run_button = button_container.button(3 unmodified linesdisabled=False)default_thresh = 0.5if 'thresh' not in st.session_state:st.session_state['thresh'] = default_threshthresh = st.sidebar.slider('Score Threshold', 0.1, 1.0, st.session_state['thresh'], key='thresh_slider')# Add an input for the user to specify the real length of the scale bar in nanometersscale_bar_length_nm = st.sidebar.number_input('Real length of the scale bar (in nm)', min_value=1, value=200)def extract_boxes_confidences_labels(results):boxes = []scores = []labels = []for r in results[0].boxes.data:x1, y1, x2, y2, conf, cls = r.tolist()if int(cls) in [3, 4]: # Only keep classes 3 and 4boxes.append([x1, y1, x2, y2])scores.append(conf)labels.append(int(cls))return boxes, scores, labelsdef normalize_boxes(boxes, width, height):return [[x1/width, y1/height, x2/width, y2/height] for x1, y1, x2, y2 in boxes]def denormalize_box(box, width, height):x1, y1, x2, y2 = boxreturn [int(x1 * width), int(y1 * height), int(x2 * width), int(y2 * height)]def infer_model(model, img_path):return model(img_path, save=True)if uploaded_file is not None:# Read the uploaded imageimage = np.array(Image.open(uploaded_file))# Extract the original image name without extensionimage_name = os.path.splitext(uploaded_file.name)[0]if run_button:try:# Read the imageimg = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)img_res = cv2.resize(img, (1024, 1024))# Save with the original nameoutput_folder = "output"os.makedirs(output_folder, exist_ok=True)img_path = os.path.join(output_folder, f"{image_name}.png")cv2.imwrite(img_path, img_res)# Parallel inference for modelswith concurrent.futures.ThreadPoolExecutor() as executor:future_1 = executor.submit(infer_model, model_1, img_path)future_2 = executor.submit(infer_model, model_2, img_path)future_3 = executor.submit(infer_model, model_3, img_path)results_1 = future_1.result()results_2 = future_2.result()results_3 = future_3.result()# Data extraction for each modelboxes_1, scores_1, labels_1 = extract_boxes_confidences_labels(results_1)boxes_2, scores_2, labels_2 = extract_boxes_confidences_labels(results_2)boxes_3, scores_3, labels_3 = extract_boxes_confidences_labels(results_3)# Load the imageimage = cv2.imread(img_path)height, width, channels = image.shape# Normalize bounding boxesboxes_1 = normalize_boxes(boxes_1, width, height)boxes_2 = normalize_boxes(boxes_2, width, height)boxes_3 = normalize_boxes(boxes_3, width, height)# Fusion of resultsboxes_list = [boxes_1, boxes_2, boxes_3]scores_list = [scores_1, scores_2, scores_3]labels_list = [labels_1, labels_2, labels_3]# Apply Soft-NMS with adjustable parametersboxes_fused, scores_fused, labels_fused = soft_nms(boxes_list, scores_list, labels_list, iou_thr=0.8, sigma=0.4, thresh=thresh)# Color dictionaryclass_colors = {3: (0, 0, 255),4: (255, 0, 0)}# Dictionaryclass_labels = {3: "V",4: "scal_bar"}# Read the imageimage = cv2.imread(img_path)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)# Get image dimensionsheight, width, _ = image.shape# Draw fused bounding boxesfor i in range(len(boxes_fused)):box = denormalize_box(boxes_fused[i], width, height)label = labels_fused[i]# Get the associated color and class namecolor = class_colors.get(label, (255, 255, 255)) # White if class is undefined# Draw the bounding boxcv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), color, 2)# Display the original and detection images side by sidecol1, col2 = st.columns(2)col1.image(img_res, caption='Uploaded TEM Image.', use_container_width=True)col2.image(image, caption='Analyzed image', use_container_width=True)# Function to display the distribution of detected vesicles (Class 3) and confidence scoresdef plot_vesicle_distribution_and_confidence(key, labels, scores, class_labels, save_path):"""Displays the distribution of detected vesicles (Class 3) and a separate histogram of confidence scores.Args:key (str): Model identifier (YOLOv8n, YOLOv8s, YOLOv8m).labels (list): List of detected classes.scores (list): List of confidence scores associated with detections.class_labels (dict): Dictionary mapping class indices to morphology names.save_path (str): Path to save the figure."""# Filter only vesicles (Class 3)vesicle_labels = [lbl for lbl in labels if lbl == 3]vesicle_scores = [score for lbl, score in zip(labels, scores) if lbl == 3]# Count occurrences of vesiclesvesicle_count = len(vesicle_labels)# Create a figure for only the second graphfig, ax = plt.subplots(figsize=(10, 6)) # Single subplot instead of (1,2)# Ensure there are detections before plottingif vesicle_scores:mean_score = np.mean(vesicle_scores)std_dev = np.std(vesicle_scores)ax.hist(vesicle_scores, bins=10, alpha=1, color='#0000FF', range=(0, 1))ax.set_xlabel("Confidence Score")ax.set_ylabel("Frequency")ax.set_title(f"{vesicle_count} vesicles detected\nConfidence Score Distribution: {mean_score:.2f} ± {std_dev:.2f}")ax.grid(axis='y', linestyle='--', alpha=0.1)ax.set_xlim(0, 1) # Fix X-axis range between 0 and 1ax.set_ylim(0, max(10, len(vesicle_scores) // 2)) # Dynamic Y-axis scaling# Adjust margins to avoid overlapsplt.tight_layout()# Save and display the figureplt.savefig(save_path, dpi=300, bbox_inches='tight')st.pyplot(fig) # Use Streamlit's method to display the figure# Display the distribution of detected classes and confidenceplot_vesicle_distribution_and_confidence("mod", labels_fused, scores_fused, class_labels, "confidence_distribution.png")# Calculate the length of the scale bar in pixelsscale_bar_pixels = Nonefor i, label in enumerate(labels_fused):if label == 4: # Class 'scal_bar'x1, _, x2, _ = denormalize_box(boxes_fused[i], width, height)scale_bar_pixels = x2 - x1 # Length of the scale bar in pixelsbreak # Only take one scale bar# Check if the scale bar was foundif scale_bar_pixels:pixel_to_nm = scale_bar_length_nm / scale_bar_pixels # Conversion pixel to nm# Calculate the size of detected objects in nmobject_sizes_nm = {cls: [] for cls in set(labels_fused) if cls != 4} # Exclude the scale barfor i, label in enumerate(labels_fused):if label != 4: # Ignore the scale barx1, y1, x2, y2 = denormalize_box(boxes_fused[i], width, height)length_nm = (x2 - x1) * pixel_to_nm # Length converted to nmwidth_nm = (y2 - y1) * pixel_to_nm # Width converted to nmdimension_nm = (length_nm+ width_nm)/2object_sizes_nm[label].append(dimension_nm)# Calculate the mean and standard deviation of the maximum sizes in nmsummary_sizes_nm = []for cls, values in object_sizes_nm.items():if values:mean_size_nm = np.mean(values)std_dev_size_nm = np.std(values)summary_sizes_nm.append([class_labels.get(cls, f"Class {cls}"), mean_size_nm, std_dev_size_nm])# Plot a histogram of the sizes in nmfig2, ax2 = plt.subplots(figsize=(10, 6))for cls, values in object_sizes_nm.items():ax2.hist(values, bins=10, alpha=1, width=4, color=np.array(class_colors.get(cls, (0, 0, 255))) / 255.0, label=class_labels.get(cls, f"Class {cls}"))ax2.set_xlabel("Diameter (nm)")ax2.set_ylabel("Number of Detections")ax2.set_title(f"Diameter: {mean_size_nm:.1f} ± {std_dev_size_nm:.1f} nm")ax2.legend()ax2.grid(axis='y', linestyle='--', alpha=0.1)plt.tight_layout()plt.savefig('distribution.png', dpi=300, bbox_inches='tight', pad_inches=0) # Path and parametersst.pyplot(fig2) # Use Streamlit's method to display the figureelse:col1, col2 = st.columns([2, 3]) # Adjust ratio as needed# Warning message in the left columnwith col1:st.markdown("""<div style="display: flex;justify-content: center;align-items: center;height: 100%;text-align: center;"><div style="background-color: #FFF3CD;color: #856404;padding: 15px;border-radius: 8px;border: 1px solid #FFEEBA;font-size: 16px;width: 90%;"><strong>Warning:</strong><br>Scale bar not found.<br>For optimal detection, please use a black scale bar on a white background as per the model's requirements.<br>See the example below for reference.</div></div>""",unsafe_allow_html=True)# Image in the right columnwith col2:st.markdown("""<div style="display: flex;justify-content: center;align-items: center;height: 100%;">""",unsafe_allow_html=True)proimage_path = "DetectNano2/proper_scale_bar.png" # Replace with actual image pathst.image(proimage_path, caption="Example of a proper scale bar", width=300)st.markdown("</div>", unsafe_allow_html=True) # Close the div tagexcept Exception as e:st.error(f"❌ Invalid image, {str(e)}")123456789101112131415161718192021222324252620 unmodified lines4748495051525354555657583 unmodified lines62636465666768697071727374757677import osimport sysimport streamlit as stimport numpy as npfrom PIL import ImageMODEL_REPO = "FERJI/DetectNano2"KF_API_KEY = os.getenv("KF_API_KEY")if not os.path.exists("DetectNano2"):os.system(f"git clone https://user:{KF_API_KEY}@huggingface.co/{MODEL_REPO}")if os.path.exists("DetectNano2/detectnano_code.py"):sys.path.append("DetectNano2")from detectnano_code import DetectNanoAppelse:st.error("⚠️ Erreur : `detectnano_code.py` introuvable dans le repository cloné !")sys.exit(1)class_colors = {3: (0, 0, 255), 4: (255, 0, 0)}class_labels = {3: "V", 4: "scal_bar"}app = DetectNanoApp(class_colors, class_labels)with st.sidebar.expander("ℹ️ About This App", expanded=False):st.markdown(20 unmodified lines**Zenodo DOI:** [https://doi.org/10.5281/zenodo.14995364](https://doi.org/10.5281/zenodo.14995364)""")st.header('Polymersomes Detection from TEM Images')uploaded_file = st.sidebar.file_uploader("📂 Upload an image...", type=["jpg", "png", "jpeg", "tif"])scale_bar_length_nm = st.sidebar.number_input('Real scale bar length (nm)', min_value=1, value=200)thresh = st.sidebar.slider('Detection Confidence Threshold', 0.1, 1.0, 0.5)button_container = st.sidebar.empty()run_button = button_container.button(3 unmodified linesdisabled=False)if uploaded_file is not None:image = np.array(Image.open(uploaded_file))image_name = os.path.splitext(uploaded_file.name)[0]if run_button:boxes, scores, labels, message = app.process(image, image_name, scale_bar_length_nm, thresh)if message:st.warning(message)else:app.visualize_and_analyze(image, f"output/{image_name}.png", boxes, scores, labels, scale_bar_length_nm)
app.py+27-309