Kalbe-x-Bangkit commited on
Commit
3c4bf46
·
verified ·
1 Parent(s): 033ddac

Revised detection.

Browse files
Files changed (1) hide show
  1. app-streamlit.py +71 -40
app-streamlit.py CHANGED
@@ -27,56 +27,87 @@ bucket_result = storage_client.bucket(bucket_name)
27
  bucket_name_load = "da-ml-models"
28
  bucket_load = storage_client.bucket(bucket_name_load)
29
 
30
- model_path = os.path.join("model.h5")
31
- model = tf.keras.models.load_model(model_path)
32
 
33
- H, W = 512, 512
34
-
35
- test_samples_folder = 'object_detection_test_samples'
36
-
37
- def cal_iou(y_true, y_pred):
38
- x1 = max(y_true[0], y_pred[0])
39
- y1 = max(y_true[1], y_pred[1])
40
- x2 = min(y_true[2], y_pred[2])
41
- y2 = min(y_true[3], y_pred[3])
42
-
43
- intersection_area = max(0, x2 - x1 + 1) * max(0, y2 - y1 + 1)
44
-
45
- true_area = (y_true[2] - y_true[0] + 1) * (y_true[3] - y_true[1] + 1)
46
- bbox_area = (y_pred[2] - y_pred[0] + 1) * (y_pred[3] - y_pred[1] + 1)
 
47
 
48
- iou = intersection_area / float(true_area + bbox_area - intersection_area)
49
- return iou
 
 
 
 
50
 
51
- df = pd.read_excel('BBox_List_2017.xlsx')
52
- labels_dict = dict(zip(df['Image Index'], df['Finding Label']))
 
 
 
 
53
 
54
- def predict(image):
55
- H, W = 512, 512
 
 
 
 
 
56
 
57
- image_resized = cv2.resize(image, (W, H))
58
- image_normalized = (image_resized - 127.5) / 127.5
59
- image_normalized = np.expand_dims(image_normalized, axis=0)
60
 
61
- # Prediction
62
- pred_bbox = model.predict(image_normalized, verbose=0)[0]
63
 
64
- # Rescale the bbox points
65
- pred_x1 = int(pred_bbox[0] * image.shape[1])
66
- pred_y1 = int(pred_bbox[1] * image.shape[0])
67
- pred_x2 = int(pred_bbox[2] * image.shape[1])
68
- pred_y2 = int(pred_bbox[3] * image.shape[0])
69
 
70
- return (pred_x1, pred_y1, pred_x2, pred_y2)
71
 
72
- st.title("AI Integration for Chest X-Ray Imaging")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- # Concept 1: Select from test samples
75
- # st.header("Select Test Sample Images")
76
- # test_sample_images = [os.path.join(test_samples_folder, f) for f in os.listdir(test_samples_folder) if f.endswith('.jpg') or f.endswith('.png')]
77
- # test_sample_selected = st.selectbox("Select a test sample image", test_sample_images)
78
- # if test_sample_selected:
79
- # st.image(test_sample_selected, caption='Selected Test Sample Image', use_column_width=True)
80
 
81
 
82
  # Utility Functions
 
27
  bucket_name_load = "da-ml-models"
28
  bucket_load = storage_client.bucket(bucket_name_load)
29
 
30
+ H = 224
31
+ W = 224
32
 
33
+ @st.cache_resource
34
+ def load_model():
35
+ model = tf.keras.models.load_model("model.h5", compile=False)
36
+ model.compile(
37
+ loss={
38
+ "bbox": "mse",
39
+ "class": "sparse_categorical_crossentropy"
40
+ },
41
+ optimizer=tf.keras.optimizers.Adam(),
42
+ metrics={
43
+ "bbox": ['mse'],
44
+ "class": ['accuracy']
45
+ }
46
+ )
47
+ return model
48
 
49
+ def preprocess_image(image):
50
+ """ Preprocess the image to the required size and normalization. """
51
+ image = cv2.resize(image, (W, H))
52
+ image = (image - 127.5) / 127.5 # Normalize to [-1, +1]
53
+ image = np.expand_dims(image, axis=0).astype(np.float32)
54
+ return image
55
 
56
+ def predict(model, image):
57
+ """ Predict bounding box and label for the input image. """
58
+ pred_bbox, pred_class = model.predict(image)
59
+ pred_label_confidence = np.max(pred_class, axis=1)[0]
60
+ pred_label = np.argmax(pred_class, axis=1)[0]
61
+ return pred_bbox[0], pred_label, pred_label_confidence
62
 
63
+ def draw_bbox(image, bbox):
64
+ """ Draw bounding box on the image. """
65
+ h, w, _ = image.shape
66
+ x1, y1, x2, y2 = bbox
67
+ x1, y1, x2, y2 = int(x1 * w), int(y1 * h), int(x2 * w), int(y2 * h)
68
+ image = cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
69
+ return image
70
 
71
+ st.title("Chest X-ray Disease Detection")
 
 
72
 
73
+ st.write("Upload a chest X-ray image and click on 'Detect' to find out if there's any disease.")
 
74
 
75
+ model = load_model()
 
 
 
 
76
 
77
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
78
 
79
+ if uploaded_file is not None:
80
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
81
+ image = cv2.imdecode(file_bytes, 1)
82
+
83
+ st.image(image, caption='Uploaded Image.', use_column_width=True)
84
+
85
+ if st.button('Detect'):
86
+ st.write("Processing...")
87
+ input_image = preprocess_image(image)
88
+ pred_bbox, pred_label, pred_label_confidence = predict(model, input_image)
89
+
90
+ label_mapping = {
91
+ 0: 'Atelectasis',
92
+ 1: 'Cardiomegaly',
93
+ 2: 'Effusion',
94
+ 3: 'Infiltrate',
95
+ 4: 'Mass',
96
+ 5: 'Nodule',
97
+ 6: 'Pneumonia',
98
+ 7: 'Pneumothorax'
99
+ }
100
+
101
+ if pred_label_confidence < 0.01:
102
+ st.write("May not detect a disease.")
103
+ else:
104
+ pred_label_name = label_mapping[pred_label]
105
+ st.write(f"Prediction Label: {pred_label_name}")
106
+ st.write(f"Prediction Bounding Box: {pred_bbox}")
107
+ st.write(f"Prediction Confidence: {pred_label_confidence:.2f}")
108
 
109
+ output_image = draw_bbox(image.copy(), pred_bbox)
110
+ st.image(output_image, caption='Detected Image.', use_column_width=True)
 
 
 
 
111
 
112
 
113
  # Utility Functions