Kalbe-x-Bangkit commited on
Commit
b745ea4
1 Parent(s): 980ed1a

Revised detection.

Browse files
Files changed (1) hide show
  1. app.py +73 -41
app.py CHANGED
@@ -26,56 +26,88 @@ bucket_result = storage_client.bucket(bucket_name)
26
  bucket_name_load = "da-ml-models"
27
  bucket_load = storage_client.bucket(bucket_name_load)
28
 
29
- model_path = os.path.join("model.h5")
30
- model = tf.keras.models.load_model(model_path)
31
 
32
- H, W = 320, 320
33
-
34
- test_samples_folder = 'object_detection_test_samples'
35
-
36
- def cal_iou(y_true, y_pred):
37
- x1 = max(y_true[0], y_pred[0])
38
- y1 = max(y_true[1], y_pred[1])
39
- x2 = min(y_true[2], y_pred[2])
40
- y2 = min(y_true[3], y_pred[3])
41
-
42
- intersection_area = max(0, x2 - x1 + 1) * max(0, y2 - y1 + 1)
43
-
44
- true_area = (y_true[2] - y_true[0] + 1) * (y_true[3] - y_true[1] + 1)
45
- bbox_area = (y_pred[2] - y_pred[0] + 1) * (y_pred[3] - y_pred[1] + 1)
 
46
 
47
- iou = intersection_area / float(true_area + bbox_area - intersection_area)
48
- return iou
 
 
 
 
49
 
50
- df = pd.read_excel('BBox_List_2017.xlsx')
51
- labels_dict = dict(zip(df['Image Index'], df['Finding Label']))
 
 
 
 
52
 
53
- def predict(image):
54
- H, W = 320, 320
 
 
 
 
 
55
 
56
- image_resized = cv2.resize(image, (W, H))
57
- image_normalized = (image_resized - 127.5) / 127.5
58
- image_normalized = np.expand_dims(image_normalized, axis=0)
59
 
60
- # Prediction
61
- pred_bbox = model.predict(image_normalized, verbose=0)[0]
62
 
63
- # Rescale the bbox points
64
- pred_x1 = int(pred_bbox[0] * image.shape[1])
65
- pred_y1 = int(pred_bbox[1] * image.shape[0])
66
- pred_x2 = int(pred_bbox[2] * image.shape[1])
67
- pred_y2 = int(pred_bbox[3] * image.shape[0])
68
 
69
- return (pred_x1, pred_y1, pred_x2, pred_y2)
70
 
71
- st.title("AI Integration for Chest X-Ray Imaging")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- # Concept 1: Select from test samples
74
- # st.header("Select Test Sample Images")
75
- # 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')]
76
- # test_sample_selected = st.selectbox("Select a test sample image", test_sample_images)
77
- # if test_sample_selected:
78
- # st.image(test_sample_selected, caption='Selected Test Sample Image', use_column_width=True)
79
 
80
 
81
  # Utility Functions
@@ -468,4 +500,4 @@ if uploaded_file is not None:
468
  model = load_model()
469
  # Compute and show Grad-CAM
470
  st.write("Generating Grad-CAM visualizations")
471
- compute_gradcam(model, uploaded_file)
 
26
  bucket_name_load = "da-ml-models"
27
  bucket_load = storage_client.bucket(bucket_name_load)
28
 
29
+ H = 224
30
+ W = 224
31
 
32
+ @st.cache_resource
33
+ def load_model():
34
+ model = tf.keras.models.load_model("model-detection.h5", compile=False)
35
+ model.compile(
36
+ loss={
37
+ "bbox": "mse",
38
+ "class": "sparse_categorical_crossentropy"
39
+ },
40
+ optimizer=tf.keras.optimizers.Adam(),
41
+ metrics={
42
+ "bbox": ['mse'],
43
+ "class": ['accuracy']
44
+ }
45
+ )
46
+ return model
47
 
48
+ def preprocess_image(image):
49
+ """ Preprocess the image to the required size and normalization. """
50
+ image = cv2.resize(image, (W, H))
51
+ image = (image - 127.5) / 127.5 # Normalize to [-1, +1]
52
+ image = np.expand_dims(image, axis=0).astype(np.float32)
53
+ return image
54
 
55
+ def predict(model, image):
56
+ """ Predict bounding box and label for the input image. """
57
+ pred_bbox, pred_class = model.predict(image)
58
+ pred_label_confidence = np.max(pred_class, axis=1)[0]
59
+ pred_label = np.argmax(pred_class, axis=1)[0]
60
+ return pred_bbox[0], pred_label, pred_label_confidence
61
 
62
+ def draw_bbox(image, bbox):
63
+ """ Draw bounding box on the image. """
64
+ h, w, _ = image.shape
65
+ x1, y1, x2, y2 = bbox
66
+ x1, y1, x2, y2 = int(x1 * w), int(y1 * h), int(x2 * w), int(y2 * h)
67
+ image = cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
68
+ return image
69
 
70
+ st.title("Chest X-ray Disease Detection")
 
 
71
 
72
+ st.write("Upload a chest X-ray image and click on 'Detect' to find out if there's any disease.")
 
73
 
74
+ model = load_model()
 
 
 
 
75
 
76
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
77
 
78
+ if uploaded_file is not None:
79
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
80
+ image = cv2.imdecode(file_bytes, 1)
81
+
82
+ st.image(image, caption='Uploaded Image.', use_column_width=True)
83
+
84
+ if st.button('Detect'):
85
+ st.write("Processing...")
86
+ input_image = preprocess_image(image)
87
+ pred_bbox, pred_label, pred_label_confidence = predict(model, input_image)
88
+
89
+ # Updated label mapping based on the dataset
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.2:
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
 
500
  model = load_model()
501
  # Compute and show Grad-CAM
502
  st.write("Generating Grad-CAM visualizations")
503
+ compute_gradcam(model, uploaded_file)