Spaces:
Sleeping
Sleeping
File size: 9,663 Bytes
a71afbe eefdadb a71afbe 07dd5b0 a71afbe f2deb22 0e955d7 4efb348 f2deb22 07dd5b0 6b9227e 07dd5b0 485c4fe 6b9227e e58811e 1ab67a4 4dfbd92 6b9227e 4dfbd92 1ab67a4 4dfbd92 4efb348 0e955d7 6b9227e 0e955d7 6b9227e 07dd5b0 eefdadb e58811e 485c4fe eefdadb 485c4fe e58811e 485c4fe e58811e 485c4fe 07dd5b0 485c4fe 6b9227e e58811e eefdadb 386797d 4efb348 eefdadb 4efb348 eefdadb d450846 6b9227e d450846 6b9227e d450846 386797d d450846 eefdadb a71afbe 4efb348 07dd5b0 6b9227e 0e955d7 07dd5b0 0e955d7 07dd5b0 0e955d7 07dd5b0 6b9227e 0e955d7 6b9227e 0e955d7 07dd5b0 6b9227e 0e955d7 6b9227e 0e955d7 |
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 |
'''
This is the originall CLL Explorer application that allows users to upload, process, and save images.
The application provides the following functionalities:
- Upload microscope images.
- Adjust image view with zoom and enhancement controls.
- Detect and measure cells automatically.
- Save analysis results and annotations.
The application is divided into the following sections:
1. **Upload Images**: Users can upload microscope images in JPG or PNG format.
2. **Select Image**: Users can select an image from the uploaded files.
3. **Processed Image**: Displays the processed image with zoom and enhancement controls.
4. **Image Controls**: Allows users to adjust the image view with sliders for X and Y coordinates, zoom, contrast, brightness, and sharpness.
5. **Save Options**: Provides options to save the processed image, image description, and image parameters.
To run the application:
1. Save the script in a Python file (e.g., app.py).
2. Run the script using the Streamlit command:
```bash
streamlit run app.py
'''
import streamlit as st
from PIL import Image, ImageEnhance
import pandas as pd
import numpy as np
import io
import os
import tempfile
import zipfile
import cv2
import numpy as np
def zoom_at(img, x, y, zoom):
'''
Zoom into an image at a specific location.
Parameters:
----------
img : PIL.Image
Input image.
x : int
X-coordinate of the zoom center.
y : int
Y-coordinate of the zoom center.
zoom : float
Zoom factor.
Returns:
-------
PIL.Image
Zoomed image resized to 500x500 pixels.
'''
w, h = img.size
zoom_half = zoom / 2
left = max(x - w * zoom_half, 0)
upper = max(y - h * zoom_half, 0)
right = min(x + w * zoom_half, w)
lower = min(y + h * zoom_half, h)
img_cropped = img.crop((left, upper, right, lower))
return img_cropped.resize((500, 500), Image.LANCZOS)
@st.cache_data
def apply_enhancements(img, x, y, zoom, contrast, brightness, sharpness):
'''
Apply zoom and image enhancements to the input image.
Parameters:
----------
img : PIL.Image
Input image.
x : int
X-coordinate of the zoom center.
y : int
Y-coordinate of the zoom center.
zoom : float
Zoom factor.
contrast : float
Contrast adjustment factor.
brightness : float
Brightness adjustment factor.
sharpness : float
Sharpness adjustment factor.
Returns:
-------
PIL.Image
Enhanced image resized to 500x500 pixels.
'''
zoomed = zoom_at(img, x, y, zoom)
enhanced_contrast = ImageEnhance.Contrast(zoomed).enhance(contrast)
enhanced_brightness = ImageEnhance.Brightness(enhanced_contrast).enhance(brightness)
enhanced_sharpness = ImageEnhance.Sharpness(enhanced_brightness).enhance(sharpness)
return enhanced_sharpness
def apply_enhancements_cv(img, x, y, zoom, contrast, brightness, sharpness):
"""
Use OpenCV for zoom and enhancements.
"""
# Convert PIL to OpenCV format
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
h, w = img_cv.shape[:2]
# Zoom
zoom_half = int(zoom / 2)
left = max(x - w * zoom_half, 0)
top = max(y - h * zoom_half, 0)
right = min(x + w * zoom_half, w)
bottom = min(y + h * zoom_half, h)
cropped = img_cv[int(top):int(bottom), int(left):int(right)]
resized = cv2.resize(cropped, (500, 500), interpolation=cv2.INTER_LANCZOS4)
# Convert back to PIL for other enhancements
pil_img = Image.fromarray(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB))
enhanced_contrast = ImageEnhance.Contrast(pil_img).enhance(contrast)
enhanced_brightness = ImageEnhance.Brightness(enhanced_contrast).enhance(brightness)
enhanced_sharpness = ImageEnhance.Sharpness(enhanced_brightness).enhance(sharpness)
return enhanced_sharpness
def create_zip(processed_img, description, params):
'''
Create a zip archive containing the processed image and annotations.
Parameters:
----------
processed_img : PIL.Image
The processed image.
description : str
Description of the image.
params : dict
Image parameters.
Returns:
-------
bytes
Byte content of the zip file.
'''
with tempfile.TemporaryDirectory() as tmpdirname:
img_path = os.path.join(tmpdirname, "processed_image.jpg")
desc_path = os.path.join(tmpdirname, "description.txt")
params_path = os.path.join(tmpdirname, "parameters.json")
# Save processed image
processed_img.save(img_path)
# Save description
with open(desc_path, "w") as f:
f.write(description)
# Save parameters
pd.DataFrame([params]).to_json(params_path, orient="records")
# Create zip
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zipf:
zipf.write(img_path, arcname="processed_image.jpg")
zipf.write(desc_path, arcname="description.txt")
zipf.write(params_path, arcname="parameters.json")
zip_buffer.seek(0)
return zip_buffer
# Streamlit App Configuration
st.set_page_config(page_title="CLL Explorer", layout="wide")
st.title("CLL Explorer: Cell Image Analysis Prep Tool")
st.markdown("""
### About This Application
This tool assists researchers in analyzing microscope images of any cell type.
- **Upload** microscope images.
- **Adjust** image view with zoom and enhancement controls.
- **Detect** and measure cells automatically.
- **Save** analysis results and annotations.
""")
uploaded_files = st.file_uploader("Upload Images", accept_multiple_files=True, type=["jpg", "png"])
if uploaded_files:
img_index = st.selectbox(
"Select Image",
range(len(uploaded_files)),
format_func=lambda x: uploaded_files[x].name
)
img_data = uploaded_files[img_index].read()
img = Image.open(io.BytesIO(img_data)).convert("RGB").resize((500, 500))
# Create columns with image on the left and controls on the right
image_col, controls_col = st.columns([3, 1])
with image_col:
st.subheader("Processed Image")
if 'processed_img' in st.session_state:
st.image(st.session_state.processed_img, use_column_width=True, caption="Processed Image")
else:
st.image(img, use_column_width=True, caption="Processed Image")
with controls_col:
st.subheader("Image Controls")
x = st.slider("X Coordinate", 0, 500, 250)
y = st.slider("Y Coordinate", 0, 500, 250)
zoom = st.slider("Zoom", 1.0, 10.0, 5.0, step=0.1)
with st.expander("Enhancement Settings", expanded=True):
contrast = st.slider("Contrast", 0.0, 5.0, 1.0, step=0.1)
brightness = st.slider("Brightness", 0.0, 5.0, 1.0, step=0.1)
sharpness = st.slider("Sharpness", 0.0, 2.0, 1.0, step=0.1)
if st.button("Apply Adjustments"):
processed_img = apply_enhancements(img, x, y, zoom, contrast, brightness, sharpness)
st.session_state.processed_img = processed_img
# Display Original Image Below
st.subheader("Original Image")
st.image(img, use_column_width=True, caption="Original Image")
# Save and Export Options
st.markdown("---")
st.subheader("Save and Export Options")
with st.expander("Add Annotations", expanded=True):
description = st.text_area("Describe the image", "")
params = {
"coordinates_x": x,
"coordinates_y": y,
"zoom": zoom,
"contrast": contrast,
"brightness": brightness,
"sharpness": sharpness
}
if st.button("Prepare Download"):
if 'processed_img' in st.session_state and description:
zip_buffer = create_zip(st.session_state.processed_img, description, params)
st.download_button(
label="Download Zip",
data=zip_buffer,
file_name="processed_image_and_annotations.zip",
mime="application/zip"
)
st.success("Zip file is ready for download.")
else:
st.warning("Ensure that the processed image is available and description is provided.")
# Optional: Save Processed Image Locally
save_image = st.checkbox("Save Processed Image Locally")
if save_image:
if 'processed_img' in st.session_state:
processed_img_path = os.path.join("processed_image_500x500.jpg")
st.session_state.processed_img.save(processed_img_path)
st.success(f"Image saved as `{processed_img_path}`")
else:
st.warning("No processed image to save.")
# Optional: Rename Files
if st.button("Rename Files"):
if 'processed_img' in st.session_state:
file_ext = str(np.random.randint(100))
new_img_name = f"img_processed_{file_ext}.jpg"
processed_img_path = "processed_image_500x500.jpg"
if os.path.exists(processed_img_path):
os.rename(processed_img_path, new_img_name)
# Save parameters and description
params_path = f"parameters_{file_ext}.json"
description_path = f"description_{file_ext}.txt"
pd.DataFrame([params]).to_json(params_path, orient="records")
with open(description_path, "w") as f:
f.write(description)
st.success(f"Files renamed to `{new_img_name}`, `{params_path}`, and `{description_path}`")
else:
st.warning("No processed image to rename.") |