Update app.py
Browse files
app.py
CHANGED
|
@@ -1,70 +1,99 @@
|
|
| 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 |
try:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
except Exception as e:
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
end_time = time.time()
|
| 45 |
-
logger.debug(f"Execution time: {end_time - start_time:.4f} seconds")
|
| 46 |
-
return wrapper
|
| 47 |
-
|
| 48 |
-
class DicomAnalyzer:
|
| 49 |
-
def __init__(self):
|
| 50 |
-
self.results = []
|
| 51 |
-
self.circle_diameter = 9.0 # Changed to float for precise calculations
|
| 52 |
self.zoom_factor = 1.0
|
| 53 |
-
self.current_image = None
|
| 54 |
-
self.dicom_data = None
|
| 55 |
-
self.display_image = None
|
| 56 |
-
self.marks = [] # Store (x, y, diameter) for each mark
|
| 57 |
-
self.original_image = None
|
| 58 |
-
self.original_display = None
|
| 59 |
-
# Pan position
|
| 60 |
self.pan_x = 0
|
| 61 |
self.pan_y = 0
|
| 62 |
-
self.
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
self.CIRCLE_COLOR = (0, 255, 255) # BGR Yellow
|
| 66 |
-
print("DicomAnalyzer initialized...")
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def load_dicom(self, file):
|
| 69 |
try:
|
| 70 |
if file is None:
|
|
@@ -294,79 +323,68 @@ class DicomAnalyzer:
|
|
| 294 |
columns_order = ['Area (mm²)', 'Mean', 'StdDev', 'Min', 'Max', 'Point']
|
| 295 |
df = df[columns_order]
|
| 296 |
return df.to_string(index=False)
|
| 297 |
-
|
| 298 |
-
def save_results(self):
|
| 299 |
try:
|
| 300 |
if not self.results:
|
| 301 |
return None, "No results to save"
|
| 302 |
|
| 303 |
-
#
|
| 304 |
-
wb = openpyxl.
|
| 305 |
ws = wb.active
|
| 306 |
|
| 307 |
-
# Define
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
# Define
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
-
#
|
| 321 |
-
|
| 322 |
-
for i, size in enumerate(phantom_sizes):
|
| 323 |
-
row_index = row_groups[i][0] - 1
|
| 324 |
-
ws.cell(row=row_index, column=1, value=size)
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
if pair_idx >= len(equation_slots) * len(row_groups):
|
| 331 |
-
break
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
# Write row number
|
| 348 |
-
ws.cell(row=dest_row, column=1, value=row_idx + 1)
|
| 349 |
-
|
| 350 |
-
# Write values in correct columns
|
| 351 |
-
ws.cell(row=dest_row, column=openpyxl.utils.column_index_from_string(start_col),
|
| 352 |
-
value=float(result['Area (mm²)']))
|
| 353 |
-
ws.cell(row=dest_row, column=openpyxl.utils.column_index_from_string(start_col) + 1,
|
| 354 |
-
value=float(result['Mean']))
|
| 355 |
-
ws.cell(row=dest_row, column=openpyxl.utils.column_index_from_string(start_col) + 2,
|
| 356 |
-
value=float(result['StdDev']))
|
| 357 |
-
ws.cell(row=dest_row, column=openpyxl.utils.column_index_from_string(start_col) + 3,
|
| 358 |
-
value=float(result['Min']))
|
| 359 |
-
ws.cell(row=dest_row, column=openpyxl.utils.column_index_from_string(start_col) + 4,
|
| 360 |
-
value=float(result['Max']))
|
| 361 |
|
| 362 |
# Save the workbook
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
except Exception as e:
|
| 368 |
-
print(f"Error saving results: {str(e)}")
|
| 369 |
-
return None, f"Error saving results: {str(e)}"
|
| 370 |
|
| 371 |
def add_blank_row(self, image):
|
| 372 |
self.results.append({
|
|
@@ -397,7 +415,6 @@ class DicomAnalyzer:
|
|
| 397 |
self.marks.pop()
|
| 398 |
return self.update_display(), self.format_results()
|
| 399 |
|
| 400 |
-
# ... (rest of the code with create_interface and main remains the same)
|
| 401 |
def create_interface():
|
| 402 |
print("Creating interface...")
|
| 403 |
analyzer = DicomAnalyzer()
|
|
@@ -408,6 +425,7 @@ def create_interface():
|
|
| 408 |
with gr.Row():
|
| 409 |
with gr.Column():
|
| 410 |
file_input = gr.File(label="Upload DICOM file")
|
|
|
|
| 411 |
diameter_slider = gr.Slider(
|
| 412 |
minimum=1,
|
| 413 |
maximum=20,
|
|
@@ -433,6 +451,7 @@ def create_interface():
|
|
| 433 |
zero_btn = gr.Button("Add Zero Row")
|
| 434 |
undo_btn = gr.Button("Undo Last")
|
| 435 |
save_btn = gr.Button("Save Results")
|
|
|
|
| 436 |
|
| 437 |
results_display = gr.Textbox(label="Results", interactive=False)
|
| 438 |
file_output = gr.File(label="Download Results")
|
|
@@ -443,14 +462,21 @@ def create_interface():
|
|
| 443 |
- Use arrow keys to pan when zoomed in
|
| 444 |
- Click points to measure
|
| 445 |
- Use Zoom In/Out buttons or Reset View to adjust zoom level
|
| 446 |
-
-
|
| 447 |
""")
|
| 448 |
|
| 449 |
def update_diameter(x):
|
| 450 |
-
analyzer.circle_diameter = float(x)
|
| 451 |
print(f"Diameter updated to: {x}")
|
| 452 |
return f"Diameter set to {x} pixels"
|
| 453 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
# Event handlers
|
| 455 |
file_input.change(
|
| 456 |
fn=analyzer.load_dicom,
|
|
@@ -473,14 +499,14 @@ def create_interface():
|
|
| 473 |
fn=analyzer.zoom_in,
|
| 474 |
inputs=image_display,
|
| 475 |
outputs=image_display,
|
| 476 |
-
queue=False
|
| 477 |
)
|
| 478 |
|
| 479 |
zoom_out_btn.click(
|
| 480 |
fn=analyzer.zoom_out,
|
| 481 |
inputs=image_display,
|
| 482 |
outputs=image_display,
|
| 483 |
-
queue=False
|
| 484 |
)
|
| 485 |
|
| 486 |
reset_btn.click(
|
|
@@ -517,6 +543,12 @@ def create_interface():
|
|
| 517 |
outputs=[file_output, results_display]
|
| 518 |
)
|
| 519 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
js = """
|
| 521 |
<script>
|
| 522 |
document.addEventListener('keydown', function(e) {
|
|
|
|
| 1 |
+
def load_dicom(self, file):
|
| 2 |
+
try:
|
| 3 |
+
if file is None:
|
| 4 |
+
return None, "No file uploaded"
|
| 5 |
+
|
| 6 |
+
if hasattr(file, 'name'):
|
| 7 |
+
dicom_data = pydicom.dcmread(file.name)
|
| 8 |
+
else:
|
| 9 |
+
dicom_data = pydicom.dcmread(file)
|
| 10 |
+
|
| 11 |
+
image = dicom_data.pixel_array.astype(np.float32)
|
| 12 |
+
|
| 13 |
+
# Store original pixel values before any scaling
|
| 14 |
+
self.original_image = image.copy()
|
| 15 |
+
|
| 16 |
+
# Apply DICOM scaling for display
|
| 17 |
+
rescale_slope = getattr(dicom_data, 'RescaleSlope', 1)
|
| 18 |
+
rescale_intercept = getattr(dicom_data, 'RescaleIntercept', 0)
|
| 19 |
+
image = (image * rescale_slope) + rescale_intercept
|
| 20 |
+
|
| 21 |
+
self.current_image = image
|
| 22 |
+
self.dicom_data = dicom_data
|
| 23 |
+
|
| 24 |
+
self.display_image = self.normalize_image(image)
|
| 25 |
+
self.original_display = self.display_image.copy()
|
| 26 |
+
|
| 27 |
+
# Reset view on new image
|
| 28 |
+
self.reset_view()
|
| 29 |
+
print("DICOM file loaded successfully")
|
| 30 |
+
|
| 31 |
+
return self.display_image, "DICOM file loaded successfully"
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Error loading DICOM file: {str(e)}")
|
| 34 |
+
return None, f"Error loading DICOM file: {str(e)}"
|
| 35 |
+
|
| 36 |
+
def normalize_image(self, image):
|
| 37 |
try:
|
| 38 |
+
normalized = cv2.normalize(
|
| 39 |
+
image,
|
| 40 |
+
None,
|
| 41 |
+
alpha=0,
|
| 42 |
+
beta=255,
|
| 43 |
+
norm_type=cv2.NORM_MINMAX,
|
| 44 |
+
dtype=cv2.CV_8U
|
| 45 |
+
)
|
| 46 |
+
if len(normalized.shape) == 2:
|
| 47 |
+
normalized = cv2.cvtColor(normalized, cv2.COLOR_GRAY2BGR)
|
| 48 |
+
return normalized
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"Error normalizing image: {str(e)}")
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
def reset_view(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
self.zoom_factor = 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
self.pan_x = 0
|
| 56 |
self.pan_y = 0
|
| 57 |
+
if self.original_display is not None:
|
| 58 |
+
return self.update_display()
|
| 59 |
+
return None
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
def zoom_in(self, image):
|
| 62 |
+
print("Zooming in...")
|
| 63 |
+
self.zoom_factor = min(20.0, self.zoom_factor + 0.5)
|
| 64 |
+
return self.update_display()
|
| 65 |
+
|
| 66 |
+
def zoom_out(self, image):
|
| 67 |
+
print("Zooming out...")
|
| 68 |
+
self.zoom_factor = max(1.0, self.zoom_factor - 0.5)
|
| 69 |
+
return self.update_display()
|
| 70 |
+
|
| 71 |
+
def handle_keyboard(self, key):
|
| 72 |
+
try:
|
| 73 |
+
print(f"Handling key press: {key}")
|
| 74 |
+
pan_amount = int(5 * self.zoom_factor)
|
| 75 |
+
|
| 76 |
+
original_pan_x = self.pan_x
|
| 77 |
+
original_pan_y = self.pan_y
|
| 78 |
+
|
| 79 |
+
if key == 'ArrowLeft':
|
| 80 |
+
self.pan_x = max(0, self.pan_x - pan_amount)
|
| 81 |
+
elif key == 'ArrowRight':
|
| 82 |
+
self.pan_x = min(self.max_pan_x, self.pan_x + pan_amount)
|
| 83 |
+
elif key == 'ArrowUp':
|
| 84 |
+
self.pan_y = max(0, self.pan_y - pan_amount)
|
| 85 |
+
elif key == 'ArrowDown':
|
| 86 |
+
self.pan_y = min(self.max_pan_y, self.pan_y + pan_amount)
|
| 87 |
+
|
| 88 |
+
print(f"Pan X: {self.pan_x} (was {original_pan_x})")
|
| 89 |
+
print(f"Pan Y: {self.pan_y} (was {original_pan_y})")
|
| 90 |
+
print(f"Max Pan X: {self.max_pan_x}")
|
| 91 |
+
print(f"Max Pan Y: {self.max_pan_y}")
|
| 92 |
+
|
| 93 |
+
return self.update_display()
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error handling keyboard input: {str(e)}")
|
| 96 |
+
return self.display_image
|
| 97 |
def load_dicom(self, file):
|
| 98 |
try:
|
| 99 |
if file is None:
|
|
|
|
| 323 |
columns_order = ['Area (mm²)', 'Mean', 'StdDev', 'Min', 'Max', 'Point']
|
| 324 |
df = df[columns_order]
|
| 325 |
return df.to_string(index=False)
|
| 326 |
+
def save_results_to_template(self, template_path, output_path):
|
|
|
|
| 327 |
try:
|
| 328 |
if not self.results:
|
| 329 |
return None, "No results to save"
|
| 330 |
|
| 331 |
+
# Load the Excel template
|
| 332 |
+
wb = openpyxl.load_workbook(template_path)
|
| 333 |
ws = wb.active
|
| 334 |
|
| 335 |
+
# Define row groups and phantom sizes
|
| 336 |
+
row_groups = {
|
| 337 |
+
"7mm": [41, 42],
|
| 338 |
+
"6.5mm": [67, 68],
|
| 339 |
+
"6mm": [93, 94],
|
| 340 |
+
"5.5mm": [119, 120],
|
| 341 |
+
"5mm": [145, 146],
|
| 342 |
+
"4.5mm": [171, 172],
|
| 343 |
+
"4mm": [197, 198],
|
| 344 |
+
"3.5mm": [223, 224],
|
| 345 |
+
"3mm": [249, 250],
|
| 346 |
+
"2.5mm": [275, 276]
|
| 347 |
+
}
|
| 348 |
|
| 349 |
+
# Define columns for measurements
|
| 350 |
+
columns = {
|
| 351 |
+
'Area (mm²)': "B",
|
| 352 |
+
'Mean': "C",
|
| 353 |
+
'StdDev': "D",
|
| 354 |
+
'Min': "E",
|
| 355 |
+
'Max': "F"
|
| 356 |
+
}
|
| 357 |
|
| 358 |
+
# Map results to phantom sizes (assuming results are ordered for each size)
|
| 359 |
+
result_idx = 0
|
|
|
|
|
|
|
|
|
|
| 360 |
|
| 361 |
+
for size, rows in row_groups.items():
|
| 362 |
+
for row in rows:
|
| 363 |
+
if result_idx >= len(self.results):
|
| 364 |
+
break
|
|
|
|
|
|
|
| 365 |
|
| 366 |
+
result = self.results[result_idx]
|
| 367 |
+
|
| 368 |
+
# Write each metric to the appropriate cell
|
| 369 |
+
for metric, col in columns.items():
|
| 370 |
+
cell = f"{col}{row}"
|
| 371 |
+
value = result.get(metric, '')
|
| 372 |
+
if value:
|
| 373 |
+
try:
|
| 374 |
+
ws[cell] = float(value)
|
| 375 |
+
except ValueError:
|
| 376 |
+
ws[cell] = value
|
| 377 |
+
|
| 378 |
+
result_idx += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
# Save the workbook
|
| 381 |
+
wb.save(output_path)
|
| 382 |
+
|
| 383 |
+
return output_path, "Results saved successfully in the template format"
|
| 384 |
+
|
| 385 |
except Exception as e:
|
| 386 |
+
print(f"Error saving results to template: {str(e)}")
|
| 387 |
+
return None, f"Error saving results to template: {str(e)}"
|
| 388 |
|
| 389 |
def add_blank_row(self, image):
|
| 390 |
self.results.append({
|
|
|
|
| 415 |
self.marks.pop()
|
| 416 |
return self.update_display(), self.format_results()
|
| 417 |
|
|
|
|
| 418 |
def create_interface():
|
| 419 |
print("Creating interface...")
|
| 420 |
analyzer = DicomAnalyzer()
|
|
|
|
| 425 |
with gr.Row():
|
| 426 |
with gr.Column():
|
| 427 |
file_input = gr.File(label="Upload DICOM file")
|
| 428 |
+
template_input = gr.File(label="Upload Excel Template")
|
| 429 |
diameter_slider = gr.Slider(
|
| 430 |
minimum=1,
|
| 431 |
maximum=20,
|
|
|
|
| 451 |
zero_btn = gr.Button("Add Zero Row")
|
| 452 |
undo_btn = gr.Button("Undo Last")
|
| 453 |
save_btn = gr.Button("Save Results")
|
| 454 |
+
save_template_btn = gr.Button("Save to Template")
|
| 455 |
|
| 456 |
results_display = gr.Textbox(label="Results", interactive=False)
|
| 457 |
file_output = gr.File(label="Download Results")
|
|
|
|
| 462 |
- Use arrow keys to pan when zoomed in
|
| 463 |
- Click points to measure
|
| 464 |
- Use Zoom In/Out buttons or Reset View to adjust zoom level
|
| 465 |
+
- Upload template and use Save to Template for formatted results
|
| 466 |
""")
|
| 467 |
|
| 468 |
def update_diameter(x):
|
| 469 |
+
analyzer.circle_diameter = float(x)
|
| 470 |
print(f"Diameter updated to: {x}")
|
| 471 |
return f"Diameter set to {x} pixels"
|
| 472 |
|
| 473 |
+
def save_to_template(template_file):
|
| 474 |
+
if template_file is None:
|
| 475 |
+
return None, "No template file provided"
|
| 476 |
+
|
| 477 |
+
output_path = "analysis_results_from_template.xlsx"
|
| 478 |
+
return analyzer.save_results_to_template(template_file.name, output_path)
|
| 479 |
+
|
| 480 |
# Event handlers
|
| 481 |
file_input.change(
|
| 482 |
fn=analyzer.load_dicom,
|
|
|
|
| 499 |
fn=analyzer.zoom_in,
|
| 500 |
inputs=image_display,
|
| 501 |
outputs=image_display,
|
| 502 |
+
queue=False
|
| 503 |
)
|
| 504 |
|
| 505 |
zoom_out_btn.click(
|
| 506 |
fn=analyzer.zoom_out,
|
| 507 |
inputs=image_display,
|
| 508 |
outputs=image_display,
|
| 509 |
+
queue=False
|
| 510 |
)
|
| 511 |
|
| 512 |
reset_btn.click(
|
|
|
|
| 543 |
outputs=[file_output, results_display]
|
| 544 |
)
|
| 545 |
|
| 546 |
+
save_template_btn.click(
|
| 547 |
+
fn=save_to_template,
|
| 548 |
+
inputs=[template_input],
|
| 549 |
+
outputs=[file_output, results_display]
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
js = """
|
| 553 |
<script>
|
| 554 |
document.addEventListener('keydown', function(e) {
|