digitalai commited on
Commit
124a859
1 Parent(s): 62b8c0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -48
app.py CHANGED
@@ -6,55 +6,130 @@ import requests
6
  from io import BytesIO
7
  from fastai.vision.all import load_learner
8
 
9
- # Initialize Streamlit app
10
- st.title("White Blood Cell Classifier")
11
 
12
- # Add a description or subtitle
13
- st.markdown("""
14
- This app allows you to classify white blood cells from an uploaded image.
15
- You can upload an image of a blood sample, and the app will predict the type of white blood cell present.
16
- Choose from various cell types like eosinophil, lymphocyte, monocyte, and neutrophil.
17
- Note: To get the best results, please make sure there is only one WBC in the image. This model has not been trained on basophils.
18
- """)
19
-
20
- # Load the FastAI model for WBC identification
21
- fastai_model = load_learner('model1.pkl')
22
-
23
- # File uploader for image input
24
- uploaded_file = st.file_uploader("Upload an image for classification", type=["jpg", "png"])
25
-
26
- if uploaded_file:
27
- # Open the uploaded image
28
- image = Image.open(uploaded_file).convert('RGB')
29
 
 
 
 
30
 
31
- # Display the uploaded image with a caption
32
- st.image(image, caption="Reduced Size Image", use_column_width=False, width=150) # 150 pixels wide
33
-
34
- # Perform inference with the FastAI model
35
- pred, idx, probs = fastai_model.predict(image)
36
-
37
- # Display a title for the results section
38
- st.subheader("White Blood Cell Classification Results")
39
-
40
- # Define categories for classification
41
- categories = ('EOSINOPHIL', 'LYMPHOCYTE', 'MONOCYTE', 'NEUTROPHIL')
42
-
43
- # Create a DataFrame with classification probabilities
44
- results_df = pd.DataFrame(
45
- {'Cell Type': categories, 'Probability': probs.tolist()}
46
- )
47
- # Highlight the most likely class
48
- most_likely_class = categories[idx]
49
- st.success(f"Predicted Class: {most_likely_class}")
50
-
51
- # Additional information about the probabilities
52
- st.write("Detailed Classification Results:")
53
- st.table(results_df)
54
-
55
- # Display the probabilities as a bar chart
56
- st.bar_chart(results_df.set_index('Cell Type'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
-
59
- else:
60
- st.warning("Upload an image to start classification.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from io import BytesIO
7
  from fastai.vision.all import load_learner
8
 
 
 
9
 
10
+ options = st.selectbox("which model you wanna choose?", ("wbc classifier", "Blood Cell Detection with YOLOv8"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ if options == "wbc classifier":
13
+ # Initialize Streamlit app
14
+ st.title("White Blood Cell Classifier")
15
 
16
+ # Add a description or subtitle
17
+ st.markdown("""
18
+ This app allows you to classify white blood cells from an uploaded image.
19
+ You can upload an image of a blood sample, and the app will predict the type of white blood cell present.
20
+ Choose from various cell types like eosinophil, lymphocyte, monocyte, and neutrophil.
21
+ Note: To get the best results, please make sure there is only one WBC in the image. This model has not been trained on basophils.
22
+ """)
23
+
24
+ # Load the FastAI model for WBC identification
25
+ fastai_model = load_learner('model1.pkl')
26
+
27
+ # File uploader for image input
28
+ uploaded_file = st.file_uploader("Upload an image for classification", type=["jpg", "png"])
29
+
30
+ if uploaded_file:
31
+ # Open the uploaded image
32
+ image = Image.open(uploaded_file).convert('RGB')
33
+
34
+
35
+ # Display the uploaded image with a caption
36
+ st.image(image, caption="Reduced Size Image", use_column_width=False, width=150) # 150 pixels wide
37
+
38
+ # Perform inference with the FastAI model
39
+ pred, idx, probs = fastai_model.predict(image)
40
+
41
+ # Display a title for the results section
42
+ st.subheader("White Blood Cell Classification Results")
43
+
44
+ # Define categories for classification
45
+ categories = ('EOSINOPHIL', 'LYMPHOCYTE', 'MONOCYTE', 'NEUTROPHIL')
46
+
47
+ # Create a DataFrame with classification probabilities
48
+ results_df = pd.DataFrame(
49
+ {'Cell Type': categories, 'Probability': probs.tolist()}
50
+ )
51
+ # Highlight the most likely class
52
+ most_likely_class = categories[idx]
53
+ st.success(f"Predicted Class: {most_likely_class}")
54
+
55
+ # Additional information about the probabilities
56
+ st.write("Detailed Classification Results:")
57
+ st.table(results_df)
58
+
59
+ # Display the probabilities as a bar chart
60
+ st.bar_chart(results_df.set_index('Cell Type'))
61
+
62
+
63
+ else:
64
+ st.warning("Upload an image to start classification.")
65
 
66
+ if options == "Blood Cell Detection with YOLOv8":
67
+ # Initialize Streamlit app
68
+ st.title("Blood Cell Detection with YOLOv8")
69
+
70
+ # Load YOLO model
71
+ model = YOLO('keremberke/yolov8m-blood-cell-detection')
72
+
73
+ # Set model parameters
74
+ model.overrides['conf'] = 0.25 # NMS confidence threshold
75
+ model.overrides['iou'] = 0.45 # NMS IoU threshold
76
+ model.overrides['agnostic_nms'] = False # NMS class-agnostic
77
+ model.overrides['max_det'] = 1000 # Maximum number of detections per image
78
+
79
+ # Load the FastAI model for WBC identification
80
+ fastai_model = load_learner('model1.pkl')
81
+
82
+ # File uploader for image input
83
+ uploaded_file = st.file_uploader("Upload an image for detection", type=["jpg", "png"])
84
+
85
+ if uploaded_file:
86
+ # Open the uploaded image
87
+ image = Image.open(uploaded_file)
88
+
89
+ # Perform inference
90
+ results = model.predict(np.array(image))
91
+
92
+ # Display results
93
+ st.image(image, caption="Uploaded Image", use_column_width=True)
94
+
95
+ # Render detection results
96
+ rendered_image = render_result(model=model, image=image, result=results[0])
97
+
98
+ # Show the rendered result
99
+ st.image(rendered_image, caption="Detection Results", use_column_width=True)
100
+
101
+ # Count the number of each cell type
102
+ cell_counts = {"RBC": 0, "WBC": 0, "Platelets": 0}
103
+
104
+ # Count cells and check for WBC
105
+ has_wbc = False
106
+ # Display details of detected boxes
107
+ st.write("Detection Results:")
108
+ for box in results[0].boxes:
109
+ class_index = int(box.cls) # Get the class index
110
+ if class_index == 1: # RBC
111
+ cell_counts["RBC"] += 1
112
+ elif class_index == 2: # WBC
113
+ cell_counts["WBC"] += 1
114
+ has_wbc = True # WBC detected
115
+ elif class_index == 0: # Platelets
116
+ cell_counts["Platelets"] += 1
117
+
118
+ # Display bounding box information
119
+ #st.write(f"Bounding box: {box.xyxy}")
120
+ #st.write(f"Confidence: {box.conf}")
121
+ #st.write(f"Class: {box.cls}")
122
+
123
+ # Display the counts of each cell type
124
+ st.write("Cell Type Counts:")
125
+ st.write(pd.DataFrame.from_dict(cell_counts, orient='index', columns=['Count']))
126
+ # If a WBC is detected, run the second model
127
+ if has_wbc:
128
+ # Perform inference with the FastAI model
129
+ pred, idx, probs = fastai_model.predict(image)
130
+ st.write("White Blood Cell Classification:")
131
+ categories = ('EOSINOPHIL', 'LYMPHOCYTE', 'MONOCYTE', 'NEUTROPHIL')
132
+ results_dict = dict(zip(categories, map(float, probs)))
133
+ st.write(results_dict)
134
+ else:
135
+ st.write("Upload an image to start detection.")