Update app.py
Browse files
app.py
CHANGED
|
@@ -4,27 +4,72 @@ import numpy as np
|
|
| 4 |
import pandas as pd
|
| 5 |
import pydicom
|
| 6 |
from PIL import Image
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
class DicomAnalyzer:
|
| 11 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
self.results = []
|
| 13 |
self.circle_diameter = 9
|
| 14 |
self.zoom_factor = 1.0
|
| 15 |
self.current_image = None
|
| 16 |
self.dicom_data = None
|
| 17 |
self.display_image = None
|
| 18 |
-
self.marks = []
|
| 19 |
self.original_image = None
|
| 20 |
self.original_display = None
|
| 21 |
-
# Pan position
|
| 22 |
self.pan_x = 0
|
| 23 |
self.pan_y = 0
|
| 24 |
self.max_pan_x = 0
|
| 25 |
self.max_pan_y = 0
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def load_dicom(self, file):
|
| 29 |
try:
|
| 30 |
if file is None:
|
|
@@ -34,9 +79,10 @@ class DicomAnalyzer:
|
|
| 34 |
dicom_data = pydicom.dcmread(file.name)
|
| 35 |
else:
|
| 36 |
dicom_data = pydicom.dcmread(file)
|
| 37 |
-
|
| 38 |
-
image = dicom_data.pixel_array.astype(np.float32)
|
| 39 |
|
|
|
|
|
|
|
|
|
|
| 40 |
rescale_slope = getattr(dicom_data, 'RescaleSlope', 1)
|
| 41 |
rescale_intercept = getattr(dicom_data, 'RescaleIntercept', 0)
|
| 42 |
image = (image * rescale_slope) + rescale_intercept
|
|
@@ -45,35 +91,28 @@ class DicomAnalyzer:
|
|
| 45 |
self.original_image = image.copy()
|
| 46 |
self.dicom_data = dicom_data
|
| 47 |
|
|
|
|
| 48 |
self.display_image = self.normalize_image(image)
|
| 49 |
self.original_display = self.display_image.copy()
|
| 50 |
|
| 51 |
-
# Reset view on new image
|
| 52 |
self.reset_view()
|
| 53 |
-
print("DICOM file loaded successfully")
|
| 54 |
-
|
| 55 |
return self.display_image, "DICOM file loaded successfully"
|
| 56 |
except Exception as e:
|
| 57 |
-
|
| 58 |
-
return None, f"Error loading DICOM
|
| 59 |
|
|
|
|
| 60 |
def normalize_image(self, image):
|
| 61 |
try:
|
| 62 |
-
normalized = cv2.normalize(
|
| 63 |
-
image,
|
| 64 |
-
None,
|
| 65 |
-
alpha=0,
|
| 66 |
-
beta=255,
|
| 67 |
-
norm_type=cv2.NORM_MINMAX,
|
| 68 |
-
dtype=cv2.CV_8U
|
| 69 |
-
)
|
| 70 |
if len(normalized.shape) == 2:
|
| 71 |
normalized = cv2.cvtColor(normalized, cv2.COLOR_GRAY2BGR)
|
| 72 |
return normalized
|
| 73 |
except Exception as e:
|
| 74 |
-
|
| 75 |
return None
|
| 76 |
|
|
|
|
| 77 |
def reset_view(self):
|
| 78 |
self.zoom_factor = 1.0
|
| 79 |
self.pan_x = 0
|
|
@@ -82,196 +121,152 @@ class DicomAnalyzer:
|
|
| 82 |
return self.update_display()
|
| 83 |
return None
|
| 84 |
|
|
|
|
| 85 |
def zoom_in(self, image):
|
| 86 |
-
|
| 87 |
-
self.
|
| 88 |
return self.update_display()
|
| 89 |
|
|
|
|
| 90 |
def zoom_out(self, image):
|
| 91 |
-
|
| 92 |
-
self.
|
| 93 |
return self.update_display()
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
print(f"Handling key press: {key}")
|
| 98 |
-
pan_amount = int(5 * self.zoom_factor)
|
| 99 |
-
|
| 100 |
-
original_pan_x = self.pan_x
|
| 101 |
-
original_pan_y = self.pan_y
|
| 102 |
-
|
| 103 |
-
if key == 'ArrowLeft':
|
| 104 |
-
self.pan_x = max(0, self.pan_x - pan_amount)
|
| 105 |
-
elif key == 'ArrowRight':
|
| 106 |
-
self.pan_x = min(self.max_pan_x, self.pan_x + pan_amount)
|
| 107 |
-
elif key == 'ArrowUp':
|
| 108 |
-
self.pan_y = max(0, self.pan_y - pan_amount)
|
| 109 |
-
elif key == 'ArrowDown':
|
| 110 |
-
self.pan_y = min(self.max_pan_y, self.pan_y + pan_amount)
|
| 111 |
-
|
| 112 |
-
print(f"Pan X: {self.pan_x} (was {original_pan_x})")
|
| 113 |
-
print(f"Pan Y: {self.pan_y} (was {original_pan_y})")
|
| 114 |
-
print(f"Max Pan X: {self.max_pan_x}")
|
| 115 |
-
print(f"Max Pan Y: {self.max_pan_y}")
|
| 116 |
-
|
| 117 |
-
return self.update_display()
|
| 118 |
-
except Exception as e:
|
| 119 |
-
print(f"Error handling keyboard input: {str(e)}")
|
| 120 |
-
return self.display_image
|
| 121 |
-
|
| 122 |
-
def analyze_roi(self, evt: gr.SelectData, scaling_factor=0.3):
|
| 123 |
try:
|
| 124 |
if self.current_image is None:
|
| 125 |
return None, "No image loaded"
|
| 126 |
|
| 127 |
-
# Get
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
#
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
x += 1
|
| 143 |
-
y += 1
|
| 144 |
-
|
| 145 |
-
# Apply Pixel Spacing correction if available
|
| 146 |
-
if hasattr(self.dicom_data, 'PixelSpacing'):
|
| 147 |
-
pixel_spacing = float(self.dicom_data.PixelSpacing[0])
|
| 148 |
-
x_corrected = x * pixel_spacing
|
| 149 |
-
y_corrected = y * pixel_spacing
|
| 150 |
-
else:
|
| 151 |
-
x_corrected = x
|
| 152 |
-
y_corrected = y
|
| 153 |
-
|
| 154 |
-
# Ensure coordinates are within bounds
|
| 155 |
-
x_corrected = max(1, min(x_corrected, width))
|
| 156 |
-
y_corrected = max(1, min(y_corrected, height))
|
| 157 |
-
|
| 158 |
-
# Create circular mask with adjusted coordinates
|
| 159 |
-
mask = np.zeros_like(raw_image, dtype=np.uint8)
|
| 160 |
-
y_indices, x_indices = np.ogrid[:height, :width]
|
| 161 |
-
radius = self.circle_diameter / 2
|
| 162 |
-
distance_from_center = np.sqrt((x_indices - x_corrected)**2 + (y_indices - y_corrected)**2)
|
| 163 |
-
mask[distance_from_center <= radius] = 1
|
| 164 |
-
|
| 165 |
-
# Get ROI pixels using corrected coordinates
|
| 166 |
-
roi_pixels = raw_image[mask == 1]
|
| 167 |
|
| 168 |
# Calculate statistics
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
# Store results
|
| 175 |
result = {
|
| 176 |
-
'Area (mm²)': f"{
|
| 177 |
-
'Mean': f"{mean:.3f}",
|
| 178 |
-
'StdDev': f"{
|
| 179 |
-
'Min': f"{
|
| 180 |
-
'Max': f"{
|
| 181 |
-
'Point': f"({
|
| 182 |
}
|
|
|
|
| 183 |
self.results.append(result)
|
| 184 |
-
self.marks.append((
|
| 185 |
|
| 186 |
return self.update_display(), self.format_results()
|
| 187 |
except Exception as e:
|
| 188 |
-
|
| 189 |
-
return self.display_image, f"Error
|
| 190 |
|
|
|
|
| 191 |
def update_display(self):
|
| 192 |
try:
|
| 193 |
if self.original_display is None:
|
| 194 |
return None
|
| 195 |
|
| 196 |
height, width = self.original_display.shape[:2]
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
# Create zoomed image
|
| 201 |
-
zoomed = cv2.resize(self.original_display, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
|
| 202 |
-
|
| 203 |
-
# Convert to BGR for drawing
|
| 204 |
-
zoomed_bgr = cv2.cvtColor(zoomed, cv2.COLOR_RGB2BGR)
|
| 205 |
|
| 206 |
-
# Draw marks
|
| 207 |
for x, y, diameter in self.marks:
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
#
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
# Calculate pan limits
|
| 217 |
-
self.max_pan_x = max(0,
|
| 218 |
-
self.max_pan_y = max(0,
|
|
|
|
|
|
|
| 219 |
self.pan_x = min(max(0, self.pan_x), self.max_pan_x)
|
| 220 |
self.pan_y = min(max(0, self.pan_y), self.max_pan_y)
|
| 221 |
|
| 222 |
# Extract visible portion
|
| 223 |
-
visible =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
return visible
|
| 225 |
except Exception as e:
|
| 226 |
-
|
| 227 |
return self.original_display
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
def format_results(self):
|
| 230 |
if not self.results:
|
| 231 |
return "No measurements yet"
|
| 232 |
df = pd.DataFrame(self.results)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
return df.to_string(index=False)
|
| 236 |
-
|
| 237 |
-
def add_blank_row(self, image):
|
| 238 |
-
self.results.append({
|
| 239 |
-
'Area (mm²)': '',
|
| 240 |
-
'Mean': '',
|
| 241 |
-
'StdDev': '',
|
| 242 |
-
'Min': '',
|
| 243 |
-
'Max': '',
|
| 244 |
-
'Point': ''
|
| 245 |
-
})
|
| 246 |
-
return image, self.format_results()
|
| 247 |
-
|
| 248 |
-
def add_zero_row(self, image):
|
| 249 |
-
self.results.append({
|
| 250 |
-
'Area (mm²)': '0.000',
|
| 251 |
-
'Mean': '0.000',
|
| 252 |
-
'StdDev': '0.000',
|
| 253 |
-
'Min': '0.000',
|
| 254 |
-
'Max': '0.000',
|
| 255 |
-
'Point': '(0, 0)'
|
| 256 |
-
})
|
| 257 |
-
return image, self.format_results()
|
| 258 |
-
|
| 259 |
-
def undo_last(self, image):
|
| 260 |
-
if self.results:
|
| 261 |
-
self.results.pop()
|
| 262 |
-
if self.marks:
|
| 263 |
-
self.marks.pop()
|
| 264 |
-
return self.update_display(), self.format_results()
|
| 265 |
|
|
|
|
| 266 |
def save_results(self):
|
| 267 |
try:
|
| 268 |
if not self.results:
|
| 269 |
return None, "No results to save"
|
| 270 |
|
| 271 |
df = pd.DataFrame(self.results)
|
| 272 |
-
columns_order = ['Area (mm²)', 'Mean', 'StdDev', 'Min', 'Max', 'Point']
|
| 273 |
-
df = df[columns_order]
|
| 274 |
-
|
| 275 |
temp_file = "analysis_results.xlsx"
|
| 276 |
df.to_excel(temp_file, index=False)
|
| 277 |
|
|
@@ -280,10 +275,9 @@ class DicomAnalyzer:
|
|
| 280 |
return None, f"Error saving results: {str(e)}"
|
| 281 |
|
| 282 |
def create_interface():
|
| 283 |
-
print("Creating interface...")
|
| 284 |
analyzer = DicomAnalyzer()
|
| 285 |
|
| 286 |
-
with gr.Blocks(
|
| 287 |
gr.Markdown("# DICOM Image Analyzer")
|
| 288 |
|
| 289 |
with gr.Row():
|
|
@@ -303,30 +297,20 @@ def create_interface():
|
|
| 303 |
reset_btn = gr.Button("Reset View")
|
| 304 |
|
| 305 |
with gr.Column():
|
| 306 |
-
image_display = gr.Image(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
with gr.Row():
|
| 309 |
-
blank_btn = gr.Button("Add Blank Row")
|
| 310 |
-
zero_btn = gr.Button("Add Zero Row")
|
| 311 |
-
undo_btn = gr.Button("Undo Last")
|
| 312 |
save_btn = gr.Button("Save Results")
|
|
|
|
| 313 |
|
| 314 |
results_display = gr.Textbox(label="Results", interactive=False)
|
| 315 |
file_output = gr.File(label="Download Results")
|
| 316 |
key_press = gr.Textbox(visible=False, elem_id="key_press")
|
| 317 |
|
| 318 |
-
gr.Markdown("""
|
| 319 |
-
### Controls:
|
| 320 |
-
- Use arrow keys to pan when zoomed in
|
| 321 |
-
- Click points to measure
|
| 322 |
-
- Use Zoom In/Out buttons or Reset View to adjust zoom level
|
| 323 |
-
""")
|
| 324 |
-
|
| 325 |
-
def update_diameter(x):
|
| 326 |
-
analyzer.circle_diameter = x
|
| 327 |
-
print(f"Diameter updated to: {x}")
|
| 328 |
-
return f"Diameter set to {x} pixels"
|
| 329 |
-
|
| 330 |
# Event handlers
|
| 331 |
file_input.change(
|
| 332 |
fn=analyzer.load_dicom,
|
|
@@ -340,9 +324,9 @@ def create_interface():
|
|
| 340 |
)
|
| 341 |
|
| 342 |
diameter_slider.change(
|
| 343 |
-
fn=
|
| 344 |
inputs=diameter_slider,
|
| 345 |
-
outputs=
|
| 346 |
)
|
| 347 |
|
| 348 |
zoom_in_btn.click(
|
|
@@ -368,30 +352,17 @@ def create_interface():
|
|
| 368 |
outputs=image_display
|
| 369 |
)
|
| 370 |
|
| 371 |
-
blank_btn.click(
|
| 372 |
-
fn=analyzer.add_blank_row,
|
| 373 |
-
inputs=image_display,
|
| 374 |
-
outputs=[image_display, results_display]
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
zero_btn.click(
|
| 378 |
-
fn=analyzer.add_zero_row,
|
| 379 |
-
inputs=image_display,
|
| 380 |
-
outputs=[image_display, results_display]
|
| 381 |
-
)
|
| 382 |
-
|
| 383 |
-
undo_btn.click(
|
| 384 |
-
fn=analyzer.undo_last,
|
| 385 |
-
inputs=image_display,
|
| 386 |
-
outputs=[image_display, results_display]
|
| 387 |
-
)
|
| 388 |
-
|
| 389 |
save_btn.click(
|
| 390 |
fn=analyzer.save_results,
|
| 391 |
outputs=[file_output, results_display]
|
| 392 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
|
| 394 |
-
|
|
|
|
| 395 |
<script>
|
| 396 |
document.addEventListener('keydown', function(e) {
|
| 397 |
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
|
|
@@ -404,17 +375,14 @@ def create_interface():
|
|
| 404 |
}
|
| 405 |
});
|
| 406 |
</script>
|
| 407 |
-
"""
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
print("Interface created successfully")
|
| 411 |
return interface
|
| 412 |
|
| 413 |
if __name__ == "__main__":
|
| 414 |
try:
|
| 415 |
-
|
| 416 |
interface = create_interface()
|
| 417 |
-
print("Launching interface...")
|
| 418 |
interface.launch(
|
| 419 |
server_name="0.0.0.0",
|
| 420 |
server_port=7860,
|
|
@@ -422,5 +390,6 @@ if __name__ == "__main__":
|
|
| 422 |
debug=True
|
| 423 |
)
|
| 424 |
except Exception as e:
|
| 425 |
-
|
|
|
|
| 426 |
raise e
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
import pydicom
|
| 6 |
from PIL import Image
|
| 7 |
+
import logging
|
| 8 |
+
import time
|
| 9 |
+
import traceback
|
| 10 |
+
from functools import wraps
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
# Set up logging
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
level=logging.DEBUG,
|
| 16 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 17 |
+
handlers=[
|
| 18 |
+
logging.FileHandler('dicom_analyzer_debug.log'),
|
| 19 |
+
logging.StreamHandler(sys.stdout)
|
| 20 |
+
]
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
def debug_decorator(func):
|
| 26 |
+
@wraps(func)
|
| 27 |
+
def wrapper(*args, **kwargs):
|
| 28 |
+
logger.debug(f"Entering {func.__name__}")
|
| 29 |
+
logger.debug(f"Arguments: args={args}, kwargs={kwargs}")
|
| 30 |
+
start_time = time.time()
|
| 31 |
+
try:
|
| 32 |
+
result = func(*args, **kwargs)
|
| 33 |
+
logger.debug(f"Function {func.__name__} completed successfully")
|
| 34 |
+
return result
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.error(f"Error in {func.__name__}: {str(e)}")
|
| 37 |
+
logger.error(traceback.format_exc())
|
| 38 |
+
raise
|
| 39 |
+
finally:
|
| 40 |
+
end_time = time.time()
|
| 41 |
+
logger.debug(f"Exiting {func.__name__}. Execution time: {end_time - start_time:.4f} seconds")
|
| 42 |
+
return wrapper
|
| 43 |
|
| 44 |
class DicomAnalyzer:
|
| 45 |
def __init__(self):
|
| 46 |
+
self.logger = logging.getLogger(__name__)
|
| 47 |
+
self.logger.debug("Initializing DicomAnalyzer")
|
| 48 |
+
|
| 49 |
+
# Initialize state variables
|
| 50 |
self.results = []
|
| 51 |
self.circle_diameter = 9
|
| 52 |
self.zoom_factor = 1.0
|
| 53 |
self.current_image = None
|
| 54 |
self.dicom_data = None
|
| 55 |
self.display_image = None
|
| 56 |
+
self.marks = []
|
| 57 |
self.original_image = None
|
| 58 |
self.original_display = None
|
|
|
|
| 59 |
self.pan_x = 0
|
| 60 |
self.pan_y = 0
|
| 61 |
self.max_pan_x = 0
|
| 62 |
self.max_pan_y = 0
|
| 63 |
+
|
| 64 |
+
# Debug state
|
| 65 |
+
self.debug_info = {
|
| 66 |
+
'last_click': None,
|
| 67 |
+
'last_transformed_coords': None,
|
| 68 |
+
'zoom_history': [],
|
| 69 |
+
'pan_history': []
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
@debug_decorator
|
| 73 |
def load_dicom(self, file):
|
| 74 |
try:
|
| 75 |
if file is None:
|
|
|
|
| 79 |
dicom_data = pydicom.dcmread(file.name)
|
| 80 |
else:
|
| 81 |
dicom_data = pydicom.dcmread(file)
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
image = dicom_data.pixel_array.astype(float)
|
| 84 |
+
|
| 85 |
+
# Apply rescale parameters if available
|
| 86 |
rescale_slope = getattr(dicom_data, 'RescaleSlope', 1)
|
| 87 |
rescale_intercept = getattr(dicom_data, 'RescaleIntercept', 0)
|
| 88 |
image = (image * rescale_slope) + rescale_intercept
|
|
|
|
| 91 |
self.original_image = image.copy()
|
| 92 |
self.dicom_data = dicom_data
|
| 93 |
|
| 94 |
+
# Normalize and prepare display image
|
| 95 |
self.display_image = self.normalize_image(image)
|
| 96 |
self.original_display = self.display_image.copy()
|
| 97 |
|
|
|
|
| 98 |
self.reset_view()
|
|
|
|
|
|
|
| 99 |
return self.display_image, "DICOM file loaded successfully"
|
| 100 |
except Exception as e:
|
| 101 |
+
logger.error(f"Error loading DICOM: {str(e)}")
|
| 102 |
+
return None, f"Error loading DICOM: {str(e)}"
|
| 103 |
|
| 104 |
+
@debug_decorator
|
| 105 |
def normalize_image(self, image):
|
| 106 |
try:
|
| 107 |
+
normalized = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
if len(normalized.shape) == 2:
|
| 109 |
normalized = cv2.cvtColor(normalized, cv2.COLOR_GRAY2BGR)
|
| 110 |
return normalized
|
| 111 |
except Exception as e:
|
| 112 |
+
logger.error(f"Error normalizing image: {str(e)}")
|
| 113 |
return None
|
| 114 |
|
| 115 |
+
@debug_decorator
|
| 116 |
def reset_view(self):
|
| 117 |
self.zoom_factor = 1.0
|
| 118 |
self.pan_x = 0
|
|
|
|
| 121 |
return self.update_display()
|
| 122 |
return None
|
| 123 |
|
| 124 |
+
@debug_decorator
|
| 125 |
def zoom_in(self, image):
|
| 126 |
+
self.zoom_factor = min(20.0, self.zoom_factor * 1.2)
|
| 127 |
+
self.debug_info['zoom_history'].append(('in', self.zoom_factor))
|
| 128 |
return self.update_display()
|
| 129 |
|
| 130 |
+
@debug_decorator
|
| 131 |
def zoom_out(self, image):
|
| 132 |
+
self.zoom_factor = max(1.0, self.zoom_factor / 1.2)
|
| 133 |
+
self.debug_info['zoom_history'].append(('out', self.zoom_factor))
|
| 134 |
return self.update_display()
|
| 135 |
|
| 136 |
+
@debug_decorator
|
| 137 |
+
def analyze_roi(self, evt: gr.SelectData):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
try:
|
| 139 |
if self.current_image is None:
|
| 140 |
return None, "No image loaded"
|
| 141 |
|
| 142 |
+
# Get click coordinates and transform them
|
| 143 |
+
clicked_x, clicked_y = evt.index[0], evt.index[1]
|
| 144 |
+
self.debug_info['last_click'] = (clicked_x, clicked_y)
|
| 145 |
+
|
| 146 |
+
# Transform coordinates
|
| 147 |
+
image_x = (clicked_x + self.pan_x) / self.zoom_factor
|
| 148 |
+
image_y = (clicked_y + self.pan_y) / self.zoom_factor
|
| 149 |
+
|
| 150 |
+
self.debug_info['last_transformed_coords'] = (image_x, image_y)
|
| 151 |
+
|
| 152 |
+
# Create mask for ROI
|
| 153 |
+
height, width = self.current_image.shape[:2]
|
| 154 |
+
mask = np.zeros((height, width), dtype=np.uint8)
|
| 155 |
+
cv2.circle(mask, (int(image_x), int(image_y)),
|
| 156 |
+
self.circle_diameter // 2, 1, -1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
# Calculate statistics
|
| 159 |
+
roi_pixels = self.current_image[mask == 1]
|
| 160 |
+
|
| 161 |
+
if len(roi_pixels) == 0:
|
| 162 |
+
return self.display_image, "Error: No pixels selected"
|
| 163 |
+
|
| 164 |
+
# Get pixel spacing
|
| 165 |
+
pixel_spacing = getattr(self.dicom_data, 'PixelSpacing', [1.0, 1.0])[0]
|
| 166 |
|
| 167 |
# Store results
|
| 168 |
result = {
|
| 169 |
+
'Area (mm²)': f"{len(roi_pixels) * (pixel_spacing ** 2):.3f}",
|
| 170 |
+
'Mean': f"{np.mean(roi_pixels):.3f}",
|
| 171 |
+
'StdDev': f"{np.std(roi_pixels):.3f}",
|
| 172 |
+
'Min': f"{np.min(roi_pixels):.3f}",
|
| 173 |
+
'Max': f"{np.max(roi_pixels):.3f}",
|
| 174 |
+
'Point': f"({image_x:.1f}, {image_y:.1f})"
|
| 175 |
}
|
| 176 |
+
|
| 177 |
self.results.append(result)
|
| 178 |
+
self.marks.append((image_x, image_y, self.circle_diameter))
|
| 179 |
|
| 180 |
return self.update_display(), self.format_results()
|
| 181 |
except Exception as e:
|
| 182 |
+
logger.error(f"Error in ROI analysis: {str(e)}")
|
| 183 |
+
return self.display_image, f"Error in ROI analysis: {str(e)}"
|
| 184 |
|
| 185 |
+
@debug_decorator
|
| 186 |
def update_display(self):
|
| 187 |
try:
|
| 188 |
if self.original_display is None:
|
| 189 |
return None
|
| 190 |
|
| 191 |
height, width = self.original_display.shape[:2]
|
| 192 |
+
|
| 193 |
+
# Create working copy
|
| 194 |
+
display_image = self.original_display.copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
# Draw all marks
|
| 197 |
for x, y, diameter in self.marks:
|
| 198 |
+
cv2.circle(
|
| 199 |
+
display_image,
|
| 200 |
+
(int(x), int(y)),
|
| 201 |
+
diameter // 2,
|
| 202 |
+
(0, 255, 255),
|
| 203 |
+
1,
|
| 204 |
+
lineType=cv2.LINE_AA
|
| 205 |
+
)
|
| 206 |
|
| 207 |
+
# Apply zoom
|
| 208 |
+
if self.zoom_factor != 1.0:
|
| 209 |
+
new_width = int(width * self.zoom_factor)
|
| 210 |
+
new_height = int(height * self.zoom_factor)
|
| 211 |
+
display_image = cv2.resize(
|
| 212 |
+
display_image,
|
| 213 |
+
(new_width, new_height),
|
| 214 |
+
interpolation=cv2.INTER_LINEAR
|
| 215 |
+
)
|
| 216 |
|
| 217 |
# Calculate pan limits
|
| 218 |
+
self.max_pan_x = max(0, display_image.shape[1] - width)
|
| 219 |
+
self.max_pan_y = max(0, display_image.shape[0] - height)
|
| 220 |
+
|
| 221 |
+
# Apply panning
|
| 222 |
self.pan_x = min(max(0, self.pan_x), self.max_pan_x)
|
| 223 |
self.pan_y = min(max(0, self.pan_y), self.max_pan_y)
|
| 224 |
|
| 225 |
# Extract visible portion
|
| 226 |
+
visible = display_image[
|
| 227 |
+
int(self.pan_y):int(self.pan_y + height),
|
| 228 |
+
int(self.pan_x):int(self.pan_x + width)
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
return visible
|
| 232 |
except Exception as e:
|
| 233 |
+
logger.error(f"Error updating display: {str(e)}")
|
| 234 |
return self.original_display
|
| 235 |
|
| 236 |
+
@debug_decorator
|
| 237 |
+
def handle_keyboard(self, key):
|
| 238 |
+
try:
|
| 239 |
+
pan_amount = int(20 * self.zoom_factor)
|
| 240 |
+
|
| 241 |
+
if key == 'ArrowLeft':
|
| 242 |
+
self.pan_x = max(0, self.pan_x - pan_amount)
|
| 243 |
+
elif key == 'ArrowRight':
|
| 244 |
+
self.pan_x = min(self.max_pan_x, self.pan_x + pan_amount)
|
| 245 |
+
elif key == 'ArrowUp':
|
| 246 |
+
self.pan_y = max(0, self.pan_y - pan_amount)
|
| 247 |
+
elif key == 'ArrowDown':
|
| 248 |
+
self.pan_y = min(self.max_pan_y, self.pan_y + pan_amount)
|
| 249 |
+
|
| 250 |
+
self.debug_info['pan_history'].append((self.pan_x, self.pan_y))
|
| 251 |
+
return self.update_display()
|
| 252 |
+
except Exception as e:
|
| 253 |
+
logger.error(f"Error handling keyboard input: {str(e)}")
|
| 254 |
+
return self.display_image
|
| 255 |
+
|
| 256 |
def format_results(self):
|
| 257 |
if not self.results:
|
| 258 |
return "No measurements yet"
|
| 259 |
df = pd.DataFrame(self.results)
|
| 260 |
+
columns = ['Area (mm²)', 'Mean', 'StdDev', 'Min', 'Max', 'Point']
|
| 261 |
+
return df[columns].to_string(index=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
+
@debug_decorator
|
| 264 |
def save_results(self):
|
| 265 |
try:
|
| 266 |
if not self.results:
|
| 267 |
return None, "No results to save"
|
| 268 |
|
| 269 |
df = pd.DataFrame(self.results)
|
|
|
|
|
|
|
|
|
|
| 270 |
temp_file = "analysis_results.xlsx"
|
| 271 |
df.to_excel(temp_file, index=False)
|
| 272 |
|
|
|
|
| 275 |
return None, f"Error saving results: {str(e)}"
|
| 276 |
|
| 277 |
def create_interface():
|
|
|
|
| 278 |
analyzer = DicomAnalyzer()
|
| 279 |
|
| 280 |
+
with gr.Blocks() as interface:
|
| 281 |
gr.Markdown("# DICOM Image Analyzer")
|
| 282 |
|
| 283 |
with gr.Row():
|
|
|
|
| 297 |
reset_btn = gr.Button("Reset View")
|
| 298 |
|
| 299 |
with gr.Column():
|
| 300 |
+
image_display = gr.Image(
|
| 301 |
+
label="DICOM Image",
|
| 302 |
+
interactive=True,
|
| 303 |
+
elem_id="image_display"
|
| 304 |
+
)
|
| 305 |
|
| 306 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
| 307 |
save_btn = gr.Button("Save Results")
|
| 308 |
+
debug_btn = gr.Button("Print Debug Info")
|
| 309 |
|
| 310 |
results_display = gr.Textbox(label="Results", interactive=False)
|
| 311 |
file_output = gr.File(label="Download Results")
|
| 312 |
key_press = gr.Textbox(visible=False, elem_id="key_press")
|
| 313 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
# Event handlers
|
| 315 |
file_input.change(
|
| 316 |
fn=analyzer.load_dicom,
|
|
|
|
| 324 |
)
|
| 325 |
|
| 326 |
diameter_slider.change(
|
| 327 |
+
fn=lambda x: setattr(analyzer, 'circle_diameter', x),
|
| 328 |
inputs=diameter_slider,
|
| 329 |
+
outputs=None
|
| 330 |
)
|
| 331 |
|
| 332 |
zoom_in_btn.click(
|
|
|
|
| 352 |
outputs=image_display
|
| 353 |
)
|
| 354 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
save_btn.click(
|
| 356 |
fn=analyzer.save_results,
|
| 357 |
outputs=[file_output, results_display]
|
| 358 |
)
|
| 359 |
+
|
| 360 |
+
debug_btn.click(
|
| 361 |
+
fn=lambda: logger.debug(f"Debug Info: {analyzer.debug_info}")
|
| 362 |
+
)
|
| 363 |
|
| 364 |
+
# Add keyboard handling JavaScript
|
| 365 |
+
gr.HTML("""
|
| 366 |
<script>
|
| 367 |
document.addEventListener('keydown', function(e) {
|
| 368 |
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
|
|
|
|
| 375 |
}
|
| 376 |
});
|
| 377 |
</script>
|
| 378 |
+
""")
|
| 379 |
+
|
|
|
|
|
|
|
| 380 |
return interface
|
| 381 |
|
| 382 |
if __name__ == "__main__":
|
| 383 |
try:
|
| 384 |
+
logger.info("Starting DICOM Analyzer application")
|
| 385 |
interface = create_interface()
|
|
|
|
| 386 |
interface.launch(
|
| 387 |
server_name="0.0.0.0",
|
| 388 |
server_port=7860,
|
|
|
|
| 390 |
debug=True
|
| 391 |
)
|
| 392 |
except Exception as e:
|
| 393 |
+
logger.error(f"Error launching application: {str(e)}")
|
| 394 |
+
logger.error(traceback.format_exc())
|
| 395 |
raise e
|