added batch mode and corrected force scale
Browse filesFiles changed (4)
15 unmodified lines161718192021227 unmodified lines3031323334353614 unmodified lines515253525455565765 unmodified lines123124125126127128129130131106 unmodified lines2382392402362412422432442452462472382392402482492502422512522532546 unmodified lines2612622632552642652662582592672682692612622702712722732749 unmodified lines2842852862872882892902802812822832842852862872882892902912912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373382932942952962972982993003013393403413423433443453033043053063073083093103113123133463473483493503513523533543553563573583593603613623633643653663673683693703713723153733743753763 unmodified lines38038138238338438538638738838939039139239333033139439539639733439839940040140240310 unmodified lines41441541635141741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447577 unmodified lines55355455543555655755855956056156215 unmodified lines sys.path.insert(0, S2F_ROOT)
from config.constants import ( BATCH_MAX_IMAGES, COLORMAPS, DEFAULT_SUBSTRATE, MODEL_TYPE_LABELS,7 unmodified linesfrom ui.components import ( build_original_vals, build_cell_vals, render_batch_results, render_result_display, render_region_canvas, render_system_status,14 unmodified lines if raw_heatmap is None: st.warning("No prediction available to measure.") return display_mode = st.session_state.get("measure_display_mode", "Full") display_mode = st.session_state.get("measure_display_mode", "Default") display_heatmap = apply_display_scale( raw_heatmap, display_mode, min_percentile=st.session_state.get("measure_min_percentile", 0),65 unmodified linesst.markdown("""<style>section[data-testid="stSidebar"] { width: 380px !important; }@media (max-width: 768px) { section[data-testid="stSidebar"] { width: 100% !important; max-width: 100% !important; }}section[data-testid="stSidebar"] h2 { font-size: 1.25rem !important; font-weight: 600 !important;106 unmodified lines help="When on: estimate cell region from force map and use it for metrics (red contour). When off: use entire map.", )
st.markdown('<p style="font-size: 0.95rem; font-weight: 500; margin-bottom: 0.5rem;">Heatmap display</p>', unsafe_allow_html=True) batch_mode = st.toggle( "Batch mode", value=False, help=f"Process up to {BATCH_MAX_IMAGES} images at once. Upload multiple files or select multiple examples.", )
display_mode = st.radio( "Mode", ["Full", "Percentile", "Rescale", "Clip", "Filter"], help="Full: 0–1 as-is. Percentile: min/max percentiles. Rescale: stretch range to colors. Clip: clip, keep scale. Filter: show only in range.", "Heatmap display", ["Default", "Percentile", "Range"], horizontal=True, label_visibility="collapsed", help="Default: full 0–1 range. Percentile: map a percentile range to improve contrast when few bright pixels dominate. Range: show only values in [min, max]; others hidden (black).", ) min_percentile, max_percentile = 0, 100 clip_min, clip_max = 0.0, 1.06 unmodified lines if min_percentile >= max_percentile: st.warning("Min percentile must be less than max. Using min=0, max=100.") min_percentile, max_percentile = 0, 100 elif display_mode in ("Rescale", "Clip", "Filter"): elif display_mode == "Range": col_cmin, col_cmax = st.columns(2) with col_cmin: clip_min = st.number_input("Min", value=0.0, min_value=None, max_value=None, step=0.01, format="%.3f", help="Rescale: below → black. Clip: clamp to min. Filter: below → discarded.") clip_min = st.number_input("Min", value=0.0, min_value=0.0, max_value=1.0, step=0.01, format="%.3f", help="Values below this range → hidden (black)") with col_cmax: clip_max = st.number_input("Max", value=1.0, min_value=None, max_value=None, step=0.01, format="%.3f", help="Rescale: above → white. Clip: clamp to max. Filter: above → discarded.") clip_max = st.number_input("Max", value=1.0, min_value=0.0, max_value=1.0, step=0.01, format="%.3f", help="Values above this range → hidden (black)") if clip_min >= clip_max: st.warning("Min must be less than max. Using min=0, max=1.") clip_min, clip_max = 0.0, 1.09 unmodified lines# Main area: image inputimg_source = st.radio("Image source", ["Upload", "Example"], horizontal=True, label_visibility="collapsed")img = Noneimgs_batch = [] # list of (img, key_img) for batch modeuploaded = Noneuploaded_list = []selected_sample = None
if img_source == "Upload": uploaded = st.file_uploader( "Upload bright-field image", type=["tif", "tiff", "png", "jpg", "jpeg"], help="Bright-field microscopy image of a cell or spheroid on a substrate (grayscale or RGB).", ) if uploaded: bytes_data = uploaded.read() nparr = np.frombuffer(bytes_data, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE) uploaded.seek(0)selected_samples = []
if batch_mode: # Batch mode: multiple images (max BATCH_MAX_IMAGES) if img_source == "Upload": uploaded_list = st.file_uploader( "Upload bright-field images", type=["tif", "tiff", "png", "jpg", "jpeg"], accept_multiple_files=True, help=f"Select up to {BATCH_MAX_IMAGES} images. Bright-field microscopy (grayscale or RGB).", ) if uploaded_list: uploaded_list = uploaded_list[:BATCH_MAX_IMAGES] for u in uploaded_list: bytes_data = u.read() nparr = np.frombuffer(bytes_data, np.uint8) decoded = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE) if decoded is not None: imgs_batch.append((decoded, u.name)) u.seek(0) else: sample_folder = get_sample_folder(S2F_ROOT, model_type) sample_files = list_files_in_folder(sample_folder, SAMPLE_EXTENSIONS) sample_subfolder_name = model_subfolder(model_type) if sample_files: selected_samples = st.multiselect( f"Select example images (max {BATCH_MAX_IMAGES})", sample_files, default=None, max_selections=BATCH_MAX_IMAGES, key=f"sample_batch_{model_type}", ) if selected_samples: for fname in selected_samples[:BATCH_MAX_IMAGES]: sample_path = os.path.join(sample_folder, fname) loaded = cv2.imread(sample_path, cv2.IMREAD_GRAYSCALE) if loaded is not None: imgs_batch.append((loaded, fname)) thumbnails = get_cached_sample_thumbnails(model_type, sample_folder, sample_files) n_cols = min(5, len(thumbnails)) cols = st.columns(n_cols) for i, (fname, sample_img) in enumerate(thumbnails): if sample_img is not None: with cols[i % n_cols]: st.image(sample_img, caption=fname, width=120) else: st.info(f"No example images in samples/{sample_subfolder_name}/. Add images or use Upload.")else: sample_folder = get_sample_folder(S2F_ROOT, model_type) sample_files = list_files_in_folder(sample_folder, SAMPLE_EXTENSIONS) sample_subfolder_name = model_subfolder(model_type) if sample_files: selected_sample = st.selectbox( f"Select example image (from `samples/{sample_subfolder_name}/`)", sample_files, format_func=lambda x: x, key=f"sample_{model_type}", # Single image mode if img_source == "Upload": uploaded = st.file_uploader( "Upload bright-field image", type=["tif", "tiff", "png", "jpg", "jpeg"], help="Bright-field microscopy image of a cell or spheroid on a substrate (grayscale or RGB).", ) if selected_sample: sample_path = os.path.join(sample_folder, selected_sample) img = cv2.imread(sample_path, cv2.IMREAD_GRAYSCALE) # Cached thumbnails thumbnails = get_cached_sample_thumbnails(model_type, sample_folder, sample_files) n_cols = min(5, len(thumbnails)) cols = st.columns(n_cols) for i, (fname, sample_img) in enumerate(thumbnails): if sample_img is not None: with cols[i % n_cols]: st.image(sample_img, caption=fname, width=120) if uploaded: bytes_data = uploaded.read() nparr = np.frombuffer(bytes_data, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE) uploaded.seek(0) else: sample_folder = get_sample_folder(S2F_ROOT, model_type) sample_files = list_files_in_folder(sample_folder, SAMPLE_EXTENSIONS) sample_subfolder_name = model_subfolder(model_type) if sample_files: selected_sample = st.selectbox( f"Select example image (from `samples/{sample_subfolder_name}/`)", sample_files, format_func=lambda x: x, key=f"sample_{model_type}", ) if selected_sample: sample_path = os.path.join(sample_folder, selected_sample) img = cv2.imread(sample_path, cv2.IMREAD_GRAYSCALE) thumbnails = get_cached_sample_thumbnails(model_type, sample_folder, sample_files) n_cols = min(5, len(thumbnails)) cols = st.columns(n_cols) for i, (fname, sample_img) in enumerate(thumbnails): if sample_img is not None: with cols[i % n_cols]: st.image(sample_img, caption=fname, width=120) else: st.info(f"No example images in samples/{sample_subfolder_name}/. Add images or use Upload.") st.info(f"No example images in samples/{sample_subfolder_name}/. Add images or use Upload.")
col_btn, col_model, col_path = st.columns([1, 1, 3])with col_btn:3 unmodified lineswith col_path: ckp_path = f"ckp/{ckp_subfolder_name}/{checkpoint}" if checkpoint else f"ckp/{ckp_subfolder_name}/" st.markdown(f"<span style='display: inline-flex; align-items: center; height: 38px;'>Checkpoint: <code>{ckp_path}</code></span>", unsafe_allow_html=True)
has_image = img is not Nonehas_batch = len(imgs_batch) > 0
if "prediction_result" not in st.session_state: st.session_state["prediction_result"] = Noneif "batch_results" not in st.session_state: st.session_state["batch_results"] = Noneif not batch_mode: st.session_state["batch_results"] = None # Clear when switching to single mode
just_ran = run and checkpoint and has_imagecached = st.session_state["prediction_result"]# Single-image keys (for non-batch)key_img = (uploaded.name if uploaded else None) if img_source == "Upload" else selected_samplecurrent_key = (model_type, checkpoint, key_img)cached = st.session_state["prediction_result"]has_cached = cached is not None and cached.get("cache_key") == current_keyhas_cached = cached is not None and cached.get("cache_key") == current_key and not batch_modejust_ran = run and checkpoint and has_image and not batch_modejust_ran_batch = run and checkpoint and has_batch and batch_mode
def get_or_create_predictor(model_type, checkpoint, ckp_folder):10 unmodified lines return st.session_state["predictor"]
if just_ran:if just_ran_batch: st.session_state["prediction_result"] = None st.session_state["batch_results"] = None with st.spinner("Loading model and predicting..."): try: predictor = get_or_create_predictor(model_type, checkpoint, ckp_folder) sub_val = substrate_val if model_type == "single_cell" and not use_manual else DEFAULT_SUBSTRATE batch_results = [] progress_bar = st.progress(0, text="Processing images...") for idx, (img_b, key_b) in enumerate(imgs_batch): progress_bar.progress((idx + 1) / len(imgs_batch), text=f"Processing {key_b}...") heatmap, force, pixel_sum = predictor.predict( image_array=img_b, substrate=sub_val, substrate_config=substrate_config if model_type == "single_cell" else None, ) cell_mask = estimate_cell_mask(heatmap) if auto_cell_boundary else None batch_results.append({ "img": img_b.copy(), "heatmap": heatmap.copy(), "force": force, "pixel_sum": pixel_sum, "key_img": key_b, "cell_mask": cell_mask, }) progress_bar.empty() st.session_state["batch_results"] = batch_results st.success(f"Prediction complete for {len(batch_results)} image(s)!") render_batch_results( batch_results, colormap_name=colormap_name, display_mode=display_mode, min_percentile=min_percentile, max_percentile=max_percentile, clip_min=clip_min, clip_max=clip_max, auto_cell_boundary=auto_cell_boundary, ) except Exception as e: st.error(f"Prediction failed: {e}") st.code(traceback.format_exc())
elif batch_mode and st.session_state.get("batch_results"): st.success("Prediction complete!") render_batch_results( st.session_state["batch_results"], colormap_name=colormap_name, display_mode=display_mode, min_percentile=min_percentile, max_percentile=max_percentile, clip_min=clip_min, clip_max=clip_max, auto_cell_boundary=auto_cell_boundary, )
elif just_ran: st.session_state["prediction_result"] = None with st.spinner("Loading model and predicting..."): try:77 unmodified lines
elif run and not checkpoint: st.warning("Please add checkpoint files to the ckp/ folder and select one.")elif run and not has_image:elif run and not has_image and not has_batch: st.warning("Please upload an image or select an example.")elif run and batch_mode and not has_batch: st.warning(f"Please upload or select 1–{BATCH_MAX_IMAGES} images for batch processing.")
st.sidebar.divider()render_system_status()11 unmodified lines1213141516171811 unmodified lines# UICANVAS_SIZE = 320SAMPLE_THUMBNAIL_LIMIT = 8BATCH_MAX_IMAGES = 5COLORMAP_N_SAMPLES = 64
# Model type labels2 unmodified lines3456789106 unmodified lines116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250387 unmodified lines63863964051164164264364468 unmodified lines7137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457462 unmodified linesimport htmlimport ioimport osimport zipfile
import cv2import numpy as np106 unmodified lines pass
def render_batch_results(batch_results, colormap_name="Jet", display_mode="Default", min_percentile=0, max_percentile=100, clip_min=0, clip_max=1, auto_cell_boundary=False): """ Render batch prediction results: summary table, bright-field row, heatmap row, and bulk download. batch_results: list of dicts with img, heatmap, force, pixel_sum, key_img, cell_mask. cell_mask is computed on-the-fly when auto_cell_boundary is True and not stored. """ if not batch_results: return st.markdown("### Batch results") # Resolve cell_mask for each result (compute if needed when auto_cell_boundary toggled on) for r in batch_results: if auto_cell_boundary and (r.get("cell_mask") is None or not np.any(r.get("cell_mask", 0) > 0)): r["_cell_mask"] = estimate_cell_mask(r["heatmap"]) else: r["_cell_mask"] = r.get("cell_mask") if auto_cell_boundary else None # Build table rows - consistent column names for both modes headers = ["Image", "Force", "Sum", "Max", "Mean"] rows = [] csv_rows = [["image"] + headers[1:]] for r in batch_results: heatmap = r["heatmap"] cell_mask = r.get("_cell_mask") key = r["key_img"] or "image" if auto_cell_boundary and cell_mask is not None and np.any(cell_mask > 0): vals = heatmap[cell_mask > 0] cell_pixel_sum = float(np.sum(vals)) cell_force = cell_pixel_sum * (r["force"] / r["pixel_sum"]) if r["pixel_sum"] > 0 else cell_pixel_sum cell_mean = cell_pixel_sum / np.sum(cell_mask) if np.sum(cell_mask) > 0 else 0 row = [key, f"{cell_force:.2f}", f"{cell_pixel_sum:.2f}", f"{np.max(heatmap):.4f}", f"{cell_mean:.4f}"] else: row = [key, f"{r['force']:.2f}", f"{r['pixel_sum']:.2f}", f"{np.max(heatmap):.4f}", f"{np.mean(heatmap):.4f}"] rows.append(row) csv_rows.append([os.path.splitext(key)[0]] + row[1:]) # Bright-field row st.markdown("**Input: Bright-field images**") n_cols = min(5, len(batch_results)) bf_cols = st.columns(n_cols) for i, r in enumerate(batch_results): img = r["img"] if img.ndim == 2: img_rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) else: img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) with bf_cols[i % n_cols]: st.image(img_rgb, caption=r["key_img"], use_container_width=True) # Heatmap row st.markdown("**Output: Predicted force maps**") hm_cols = st.columns(n_cols) for i, r in enumerate(batch_results): display_heatmap = apply_display_scale( r["heatmap"], display_mode, min_percentile=min_percentile, max_percentile=max_percentile, clip_min=clip_min, clip_max=clip_max, ) hm_rgb = heatmap_to_rgb_with_contour( display_heatmap, colormap_name, r.get("_cell_mask") if auto_cell_boundary else None, ) with hm_cols[i % n_cols]: st.image(hm_rgb, caption=r["key_img"], use_container_width=True) # Table st.dataframe( {h: [r[i] for r in rows] for i, h in enumerate(headers)}, use_container_width=True, hide_index=True, ) # Histograms in accordion (one per row for visibility) with st.expander("Force distribution (histograms)", expanded=False): for i, r in enumerate(batch_results): heatmap = r["heatmap"] cell_mask = r.get("_cell_mask") vals = heatmap[cell_mask > 0] if (cell_mask is not None and np.any(cell_mask > 0) and auto_cell_boundary) else heatmap.flatten() vals = vals[vals > 0] if np.any(vals > 0) else vals st.markdown(f"**{r['key_img']}**") if len(vals) > 0: fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color="#0d9488")]) fig.update_layout( height=220, margin=dict(l=40, r=20, t=10, b=40), xaxis_title="Force value", yaxis_title="Count", showlegend=False, ) st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False}) else: st.caption("No data") if i < len(batch_results) - 1: st.divider() # Bulk downloads: CSV and heatmaps (zip) buf_csv = io.StringIO() csv.writer(buf_csv).writerows(csv_rows) zip_buf = io.BytesIO() with zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_DEFLATED) as zf: for r in batch_results: display_heatmap = apply_display_scale( r["heatmap"], display_mode, min_percentile=min_percentile, max_percentile=max_percentile, clip_min=clip_min, clip_max=clip_max, ) hm_bytes = heatmap_to_png_bytes( display_heatmap, colormap_name, r.get("_cell_mask") if auto_cell_boundary else None, ) base = os.path.splitext(r["key_img"] or "image")[0] zf.writestr(f"{base}_heatmap.png", hm_bytes.getvalue()) zip_buf.seek(0) dl_col1, dl_col2 = st.columns(2) with dl_col1: st.download_button( "Download all as CSV", data=buf_csv.getvalue(), file_name="s2f_batch_results.csv", mime="text/csv", key="download_batch_csv", icon=":material/download:", ) with dl_col2: st.download_button( "Download all heatmaps", data=zip_buf.getvalue(), file_name="s2f_batch_heatmaps.zip", mime="application/zip", key="download_batch_heatmaps", icon=":material/image:", )
# Distinct colors for each region (RGB - heatmap_rgb is RGB)_REGION_COLORS = [ (255, 102, 0), # orange387 unmodified lines
def render_result_display(img, raw_heatmap, display_heatmap, pixel_sum, force, key_img, download_key_suffix="", colormap_name="Jet", display_mode="Auto", measure_region_dialog=None, auto_cell_boundary=True, colormap_name="Jet", display_mode="Default", measure_region_dialog=None, auto_cell_boundary=True, cell_mask=None): """ Render prediction result: plot, metrics, expander, and download/measure buttons.68 unmodified lines with col4: st.metric("Heatmap mean", f"{np.mean(raw_heatmap):.4f}", help="Average force intensity (full FOV)")
# Statistics panel (mean, std, percentiles, histogram) with st.expander("Statistics"): vals = raw_heatmap[cell_mask > 0] if (cell_mask is not None and np.any(cell_mask > 0) and use_cell_metrics) else raw_heatmap.flatten() if len(vals) > 0: st.markdown("**Summary**") stat_col1, stat_col2, stat_col3 = st.columns(3) with stat_col1: st.metric("Mean", f"{float(np.mean(vals)):.4f}") st.metric("Std", f"{float(np.std(vals)):.4f}") with stat_col2: p25, p50, p75 = float(np.percentile(vals, 25)), float(np.percentile(vals, 50)), float(np.percentile(vals, 75)) st.metric("P25", f"{p25:.4f}") st.metric("P50 (median)", f"{p50:.4f}") st.metric("P75", f"{p75:.4f}") with stat_col3: p90 = float(np.percentile(vals, 90)) st.metric("P90", f"{p90:.4f}") st.markdown("**Histogram**") hist_fig = go.Figure(data=[go.Histogram(x=vals, nbinsx=50, marker_color="#0d9488")]) hist_fig.update_layout( height=220, margin=dict(l=40, r=20, t=20, b=40), xaxis_title="Force value", yaxis_title="Count", showlegend=False, ) st.plotly_chart(hist_fig, use_container_width=True, config={"displayModeBar": False}) else: st.caption("No nonzero values to compute statistics.")
with st.expander("How to read the results"): if use_cell_metrics: st.markdown("""20 unmodified lines212223242526272829242526272831293031322 unmodified lines353637404142434445464748495051525354555657583839404120 unmodified lines
def apply_display_scale(heatmap, mode, min_percentile=0, max_percentile=100, clip_min=0, clip_max=1): """ Apply display scaling (Fiji ImageJ B&C style). Display only—does not change underlying values. - Full: use 0–1 range as-is (clip values outside) - Percentile: map data at min_percentile..max_percentile to 0..1 (values outside clipped). - Rescale: map [clip_min, clip_max] to [0, 1]; values outside → black/white. Stretches range for contrast. - Clip: clip values to [clip_min, clip_max], display with original data scale (no stretching). - Filter: discard values outside [clip_min, clip_max] (black); only values in range show color. Apply display scaling (Fiji/ImageJ style). Display only—does not change underlying values. - Default: full 0–1 range as-is. - Percentile: map min..max percentiles to 0..1. - Range: show only values in [clip_min, clip_max]; others hidden (black). """ if mode == "Full": if mode == "Default" or mode == "Auto" or mode == "Full": return np.clip(heatmap, 0, 1).astype(np.float32) if mode == "Percentile": pmin = float(np.percentile(heatmap, min_percentile))2 unmodified lines out = (heatmap.astype(np.float32) - pmin) / (pmax - pmin) return np.clip(out, 0, 1).astype(np.float32) return np.clip(heatmap, 0, 1).astype(np.float32) if mode == "Rescale": vmin, vmax = float(clip_min), float(clip_max) if vmax > vmin: out = (heatmap.astype(np.float32) - vmin) / (vmax - vmin) return np.clip(out, 0, 1).astype(np.float32) return np.clip(heatmap, 0, 1).astype(np.float32) if mode == "Clip": vmin, vmax = float(clip_min), float(clip_max) if vmax > vmin: h = np.clip(heatmap.astype(np.float32), vmin, vmax) dmin, dmax = float(np.min(heatmap)), float(np.max(heatmap)) if dmax > dmin: out = (h - dmin) / (dmax - dmin) return np.clip(out, 0, 1).astype(np.float32) return np.clip(h, 0, 1).astype(np.float32) return np.clip(heatmap, 0, 1).astype(np.float32) if mode == "Threshold": mode = "Filter" # backward compat if mode == "Filter": if mode == "Range" or mode == "Filter" or mode == "Threshold": vmin, vmax = float(clip_min), float(clip_max) if vmax > vmin: h = heatmap.astype(np.float32)S2FApp/app.py+172-49
S2FApp/config/constants.py+1
S2FApp/ui/components.py+159-1
S2FApp/utils/display.py+6-26