Spaces:
Build error
Build error
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+289
- requirements.txtAdded+9
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289import gradio as gr
import cv2
import numpy as np
import pandas as pd
import pydicom
import os
from PIL import Image
class DicomAnalyzer:
def __init__(self):
self.results = []
self.circle_diameter = 9
self.zoom_factor = 1.0
self.current_image1 = None
self.current_image2 = None
self.dicom_data1 = None
self.dicom_data2 = None
self.image_display1 = None
self.image_display2 = None
self.marks1 = [] # Store marks for image 1
self.marks2 = [] # Store marks for image 2
def load_dicom(self, file):
try:
if file is None:
return None, None, None
dicom_data = pydicom.dcmread(file.name)
image = dicom_data.pixel_array.astype(np.float32)
# Apply rescale slope and intercept
rescale_slope = getattr(dicom_data, 'RescaleSlope', 1)
rescale_intercept = getattr(dicom_data, 'RescaleIntercept', 0)
image = (image * rescale_slope) + rescale_intercept
# Store original image for analysis
original_image = image.copy()
# Normalize for display
image_display = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
# Convert to BGR for visualization
if len(image_display.shape) == 2:
image_display = cv2.cvtColor(image_display, cv2.COLOR_GRAY2BGR)
print(f"DICOM image loaded. Shape: {image.shape}, Data type: {image.dtype}")
print(f"Pixel spacing: {dicom_data.PixelSpacing}")
return original_image, image_display, dicom_data
except Exception as e:
print(f"Error loading DICOM file: {str(e)}")
return None, None, None
def analyze_point(self, image, dicom_data, x, y):
try:
# Create a circular mask
mask = np.zeros_like(image, dtype=np.uint8)
y_indices, x_indices = np.ogrid[:image.shape[0], :image.shape[1]]
distance_from_center = np.sqrt((x_indices - x)**2 + (y_indices - y)**2)
mask[distance_from_center <= self.circle_diameter / 2] = 1
# Extract pixel values within the circle
pixels = image[mask == 1]
# Calculate metrics
area_pixels = np.sum(mask)
pixel_spacing = float(dicom_data.PixelSpacing[0])
area_mm2 = area_pixels * (pixel_spacing**2)
mean = np.mean(pixels)
stddev = np.std(pixels)
min_val = np.min(pixels)
max_val = np.max(pixels)
print(f"Analysis results - Area: {area_mm2:.3f}, Mean: {mean:.3f}, StdDev: {stddev:.3f}")
return {
'Area (mm²)': f"{area_mm2:.3f}",
'Mean': f"{mean:.3f}",
'StdDev': f"{stddev:.3f}",
'Min': f"{min_val:.3f}",
'Max': f"{max_val:.3f}"
}
except Exception as e:
print(f"Error analyzing point: {str(e)}")
return None
def draw_circle(self, image, x, y, is_image1=True):
try:
image_copy = image.copy()
# Draw all previous marks
marks = self.marks1 if is_image1 else self.marks2
for mark_x, mark_y in marks:
cv2.circle(image_copy,
(int(mark_x), int(mark_y)),
int(self.circle_diameter/2),
(0, 255, 255),
1,
lineType=cv2.LINE_AA)
# Draw new mark
cv2.circle(image_copy,
(int(x), int(y)),
int(self.circle_diameter/2),
(0, 255, 255),
1,
lineType=cv2.LINE_AA)
# Store new mark
if is_image1:
self.marks1.append((x, y))
else:
self.marks2.append((x, y))
return image_copy
except Exception as e:
print(f"Error drawing circle: {str(e)}")
return image
def process_image1(self, file):
image, image_display, dicom_data = self.load_dicom(file)
self.current_image1 = image
self.image_display1 = image_display
self.dicom_data1 = dicom_data
return image_display
def process_image2(self, file):
image, image_display, dicom_data = self.load_dicom(file)
self.current_image2 = image
self.image_display2 = image_display
self.dicom_data2 = dicom_data
return image_display
def handle_click1(self, evt: gr.SelectData):
if self.current_image1 is None:
return self.image_display1, "Please load Image 1 first"
try:
x, y = evt.index
print(f"Clicked at ({x}, {y}) on Image 1")
# Draw circle with is_image1=True
marked_image = self.draw_circle(self.image_display1, x, y, is_image1=True)
# Analyze point
results = self.analyze_point(self.current_image1, self.dicom_data1, x, y)
if results:
results['Image'] = "Image 1"
results['Point'] = f"({x}, {y})"
self.results.append(results)
print(f"Added results for Image 1: {results}")
return marked_image, self.format_results()
except Exception as e:
print(f"Error in handle_click1: {str(e)}")
return self.image_display1, f"Error: {str(e)}"
def handle_click2(self, evt: gr.SelectData):
if self.current_image2 is None:
return self.image_display2, "Please load Image 2 first"
try:
x, y = evt.index
print(f"Clicked at ({x}, {y}) on Image 2")
# Draw circle with is_image1=False
marked_image = self.draw_circle(self.image_display2, x, y, is_image1=False)
# Analyze point
results = self.analyze_point(self.current_image2, self.dicom_data2, x, y)
if results:
results['Image'] = "Image 2"
results['Point'] = f"({x}, {y})"
self.results.append(results)
print(f"Added results for Image 2: {results}")
return marked_image, self.format_results()
except Exception as e:
print(f"Error in handle_click2: {str(e)}")
return self.image_display2, f"Error: {str(e)}"
def format_results(self):
if not self.results:
return "No results yet"
df = pd.DataFrame(self.results)
return df.to_string()
def clear_results(self):
self.results = []
self.marks1 = [] # Clear marks for image 1
self.marks2 = [] # Clear marks for image 2
# Reset displayed images to original state
if self.image_display1 is not None:
self.image_display1 = cv2.cvtColor(
cv2.normalize(self.current_image1, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8),
cv2.COLOR_GRAY2BGR
)
if self.image_display2 is not None:
self.image_display2 = cv2.cvtColor(
cv2.normalize(self.current_image2, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8),
cv2.COLOR_GRAY2BGR
)
return "Results cleared"
def add_blank_row(self):
self.results.append({
'Image': '',
'Point': '',
'Area (mm²)': '',
'Mean': '',
'StdDev': '',
'Min': '',
'Max': ''
})
return self.format_results()
def update_circle_diameter(self, value):
self.circle_diameter = value
print(f"Circle diameter updated to: {value}")
return f"Circle diameter set to {value}"
def save_results(self):
try:
if not self.results:
return "No results to save"
df = pd.DataFrame(self.results)
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
output_file = os.path.join(desktop_path, "analysis_results.xlsx")
# Save only Excel file
df.to_excel(output_file, index=False, engine='openpyxl')
print(f"Results saved to: {output_file}")
return f"Results saved to Desktop: analysis_results.xlsx"
except Exception as e:
print(f"Error saving results: {str(e)}")
return f"Error saving results: {str(e)}"
def create_interface():
analyzer = DicomAnalyzer()
with gr.Blocks() as interface:
gr.Markdown("# DICOM Image Analyzer")
with gr.Row():
with gr.Column():
file1 = gr.File(label="Upload first DICOM file")
image1 = gr.Image(label="Image 1", interactive=True)
file1.change(fn=analyzer.process_image1, inputs=file1, outputs=image1)
with gr.Column():
file2 = gr.File(label="Upload second DICOM file")
image2 = gr.Image(label="Image 2", interactive=True)
file2.change(fn=analyzer.process_image2, inputs=file2, outputs=image2)
with gr.Row():
circle_diameter = gr.Slider(
minimum=1,
maximum=20,
value=9,
step=1,
label="Circle Diameter"
)
circle_diameter.change(
fn=analyzer.update_circle_diameter,
inputs=circle_diameter,
outputs=gr.Textbox(label="Status")
)
with gr.Row():
clear_btn = gr.Button("Clear Results")
blank_row_btn = gr.Button("Add Blank Row")
save_btn = gr.Button("Save Results")
results = gr.Textbox(label="Results", interactive=False)
# Connect events
image1.select(fn=analyzer.handle_click1, outputs=[image1, results])
image2.select(fn=analyzer.handle_click2, outputs=[image2, results])
clear_btn.click(fn=analyzer.clear_results, outputs=results)
blank_row_btn.click(fn=analyzer.add_blank_row, outputs=results)
save_btn.click(fn=analyzer.save_results, outputs=results)
return interface
if __name__ == "__main__":
interface = create_interface()
interface.launch()123456789gradio==5.9.1
numpy>=1.25
pandas
opencv-python-headless
pydicom
pillow
openpyxl
streamlit==1.18.0
altair==4.2.2app.pyAdded+289
requirements.txtAdded+9