Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
import pydicom
|
4 |
+
import gradio as gr
|
5 |
+
from torchvision import transforms
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
# Load your PyTorch model
|
9 |
+
model = torch.load('your_model.pth') # Replace with your model path
|
10 |
+
model.eval()
|
11 |
+
|
12 |
+
# Define a function to preprocess the DICOM
|
13 |
+
def preprocess_dicom(dicom_path):
|
14 |
+
# Load DICOM file
|
15 |
+
dicom = pydicom.dcmread(dicom_path)
|
16 |
+
image = dicom.pixel_array # Extract image data
|
17 |
+
# Normalize to [0, 1] and convert to PIL Image for transforms
|
18 |
+
image = (image - np.min(image)) / (np.max(image) - np.min(image))
|
19 |
+
image = Image.fromarray((image * 255).astype(np.uint8))
|
20 |
+
# Apply transforms
|
21 |
+
transform = transforms.Compose([
|
22 |
+
transforms.Resize((224, 224)), # Resize to model's input size
|
23 |
+
transforms.ToTensor(),
|
24 |
+
])
|
25 |
+
return transform(image).unsqueeze(0) # Add batch dimension
|
26 |
+
|
27 |
+
# Prediction function
|
28 |
+
def predict_dicom(dicom_file):
|
29 |
+
# Preprocess
|
30 |
+
input_tensor = preprocess_dicom(dicom_file.name)
|
31 |
+
# Inference
|
32 |
+
with torch.no_grad():
|
33 |
+
output = model(input_tensor)
|
34 |
+
# Convert output tensor to image (dummy example, replace as needed)
|
35 |
+
output_image = output.squeeze().numpy()
|
36 |
+
output_image = (output_image - np.min(output_image)) / (np.max(output_image) - np.min(output_image)) * 255
|
37 |
+
output_image = Image.fromarray(output_image.astype(np.uint8))
|
38 |
+
return output_image
|
39 |
+
|
40 |
+
# Create Gradio interface
|
41 |
+
interface = gr.Interface(
|
42 |
+
fn=predict_dicom,
|
43 |
+
inputs=gr.inputs.File(label="Upload DICOM File"),
|
44 |
+
outputs="image",
|
45 |
+
title="DICOM Image Prediction"
|
46 |
+
)
|
47 |
+
|
48 |
+
# Launch the Gradio app
|
49 |
+
interface.launch()
|