File size: 9,280 Bytes
29dbe3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import streamlit as st
import torch
import numpy as np
import cv2

from transformers import (
    pipeline,
    ViTImageProcessor,
    ViTForImageClassification
)
from PIL import Image

from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import show_cam_on_image

MODEL_FOLDER_PATH = "final_vit_model"  


sample_img = {
    "<None>": None,
    "Right_Normal_1": "img/[0] Normal/Normal_R_1.png",
    "Left_Normal_1": "img/[0] Normal/Normal_L_1.png",
    "Right_Normal_2": "img/[0] Normal/Normal_R_2.png",
    "Left_Normal_2": "img/[0] Normal/Normal_L_2.png",

    "Right_DFU_1": "img/[1] DFU/DFU_R_1.png",
    "Left_DFU_1": "img/[1] DFU/DFU_L_1.png",
    "Right_DFU_2": "img/[1] DFU/DFU_R_2.png",
    "Left_DFU_2": "img/[1] DFU/DFU_L_2.png",
}

sample_pairs = {
    "<None>": (None, None),

    "Normal Pair 1": (
        "img/[0] Normal/Normal_R_1.png",
        "img/[0] Normal/Normal_L_1.png",
    ),
    "Normal Pair 2": (
        "img/[0] Normal/Normal_R_2.png",
        "img/[0] Normal/Normal_L_2.png",
    ),

    "DFU Pair 1": (
        "img/[1] DFU/DFU_R_1.png",
        "img/[1] DFU/DFU_L_1.png",
    ),
    "DFU Pair 2": (
        "img/[1] DFU/DFU_R_2.png",
        "img/[1] DFU/DFU_L_2.png",
    ),
}

def reshape_transform(tensor):
    """
    For ViT: remove CLS token and reshape sequence (N) to (H, W).
    """
    tensor = tensor[:, 1:, :] 
    B, N, C = tensor.shape
    H = W = int(N ** 0.5)
    tensor = tensor.reshape(B, H, W, C)
    tensor = tensor.permute(0, 3, 1, 2) 
    return tensor

class HuggingfaceToTensorModelWrapper(torch.nn.Module):
    def __init__(self, model):
        super().__init__()
        self.model = model

    def forward(self, x):
        return self.model(x).logits


@st.cache_resource
def load_classifier():
    return pipeline(
        task="image-classification",
        model=MODEL_FOLDER_PATH
    )
def load_gradcam():
    device = torch.device(
        "mps" if torch.backends.mps.is_available()
        else ("cuda" if torch.cuda.is_available() else "cpu")
    )

    processor = ViTImageProcessor.from_pretrained(MODEL_FOLDER_PATH)
    hf_model = ViTForImageClassification.from_pretrained(MODEL_FOLDER_PATH)

    model = HuggingfaceToTensorModelWrapper(hf_model).to(device).eval()
    target_layers = [model.model.vit.encoder.layer[-1].layernorm_before]

    cam = GradCAM(
        model=model,
        target_layers=target_layers,
        reshape_transform=reshape_transform
    )

    return cam, processor, device

def compute_gradcam_for_pil(pil_img, target_index: int):
    cam, processor, device = load_gradcam()

    img_np = np.array(pil_img).astype(np.float32) / 255.0

    inputs = processor(images=pil_img, return_tensors="pt")
    input_tensor = inputs["pixel_values"].to(device)

    targets = [ClassifierOutputTarget(target_index)]
    grayscale_cam = cam(input_tensor=input_tensor, targets=targets)[0]

    H, W, _ = img_np.shape
    grayscale_cam_resized = cv2.resize(grayscale_cam, (W, H))

    cam_vis = show_cam_on_image(img_np, grayscale_cam_resized, use_rgb=True)
    return img_np, cam_vis


def pretty_label(raw_label: str) -> str:
    mapping = {
        "0": "Normal",                    
        "1": "Diabetic Foot Ulcers",    
    }
    
    return mapping.get(raw_label, raw_label)


def get_target_index(raw_label: str) -> int:
    pretty = pretty_label(raw_label)

    if pretty == "Normal":
        return 0
    elif pretty == "Diabetic Foot Ulcers":
        return 1

    return 1


def app():
    st.title("Early Detection of Diabetic Foot Ulcers Using Thermal Imaging with Vision Transformer & Grad-CAM")

    mode = st.radio(
        "Choose input mode",
        ["Use sample pair (Right + Left)", "Upload your own Right & Left images"],
        index=0
    )
    
    upload_right = None
    upload_left = None
    if mode == "Upload your own Right & Left images":
        upload_right = st.file_uploader(
            "Upload Right Foot Image",
            type=["png", "jpg", "jpeg"],
            key="right_upl"
        )
        upload_left = st.file_uploader(
            "Upload Left Foot Image",
            type=["png", "jpg", "jpeg"],
            key="left_upl"
        )
    
    right_image = None
    left_image = None
    right_path = left_path = None

    if mode == "Use sample pair (Right + Left)":
        with st.expander("Choose a sample pair and view all sample images", expanded=False):
            pair_name = st.selectbox(
                "Select a sample pair (Right + Left):",
                list(sample_pairs.keys()),
                index=0
            )

            st.markdown("**Normal Group**")
            c1, c2, c3, c4 = st.columns(4)
            with c1:
                st.image(sample_img["Right_Normal_1"], caption="Right_Normal_1", width='stretch')
            with c2:
                st.image(sample_img["Left_Normal_1"], caption="Left_Normal_1", width='stretch')
            with c3:
                st.image(sample_img["Right_Normal_2"], caption="Right_Normal_2", width='stretch')
            with c4:
                st.image(sample_img["Left_Normal_2"], caption="Left_Normal_2", width='stretch')

            st.markdown("**Diabetic Foot Ulcers Group**")
            c1, c2, c3, c4 = st.columns(4)
            with c1:
                st.image(sample_img["Right_DFU_1"], caption="Right_DFU_1", width='stretch')
            with c2:
                st.image(sample_img["Left_DFU_1"], caption="Left_DFU_1", width='stretch')
            with c3:
                st.image(sample_img["Right_DFU_2"], caption="Right_DFU_2", width='stretch')
            with c4:
                st.image(sample_img["Left_DFU_2"], caption="Left_DFU_2", width='stretch')

        right_path, left_path = sample_pairs[pair_name]

    col_input, col_output = st.columns(2)
    col_input.header("Input Images")
    col_output.header("Predictions")

    right_col_in, left_col_in = col_input.columns(2)
    right_col_in.subheader("Right Foot")
    left_col_in.subheader("Left Foot")

    if mode == "Use sample pair (Right + Left)":
        if right_path is not None:
            right_image = Image.open(right_path).convert("RGB")
            right_col_in.image(right_image, caption="Sample Right Foot", width='stretch')

        if left_path is not None:
            left_image = Image.open(left_path).convert("RGB")
            left_col_in.image(left_image, caption="Sample Left Foot", width='stretch')

    else:
        if upload_right is not None:
            right_image = Image.open(upload_right).convert("RGB")
            right_col_in.image(right_image, caption="Uploaded Right Foot", width='stretch')

        if upload_left is not None:
            left_image = Image.open(upload_left).convert("RGB")
            left_col_in.image(left_image, caption="Uploaded Left Foot", width='stretch')

    run_pred = col_output.button("Run prediction")

    out_right_col, out_left_col = col_output.columns(2)
    out_right_col.subheader("Right Foot Prediction")
    out_left_col.subheader("Left Foot Prediction")

    right_cam_vis = None
    left_cam_vis = None

    if run_pred:
        classifier = load_classifier()
        any_image = False

        if right_image is not None:
            any_image = True
            preds_right = classifier(right_image, top_k=2)

            for pred in preds_right:
                label = pretty_label(pred["label"])
                score = float(pred["score"])
                out_right_col.progress(score, text=f"{label}: {score * 100:.2f}%")

            top_right_raw_label = preds_right[0]["label"]
            right_target_index = get_target_index(top_right_raw_label)
            _, right_cam_vis = compute_gradcam_for_pil(right_image, right_target_index)

        if left_image is not None:
            any_image = True
            preds_left = classifier(left_image, top_k=2)

            for pred in preds_left:
                label = pretty_label(pred["label"])
                score = float(pred["score"])
                out_left_col.progress(score, text=f"{label}: {score * 100:.2f}%")

            top_left_raw_label = preds_left[0]["label"]
            left_target_index = get_target_index(top_left_raw_label)
            _, left_cam_vis = compute_gradcam_for_pil(left_image, left_target_index)

        if any_image:
            col_output.success("Classification finished ✅")
        else:
            col_output.warning("Please provide images before running prediction.")

        if right_cam_vis is not None or left_cam_vis is not None:
            st.markdown("---")
            if right_target_index == 1:
                right_target_index = "DFU"
            else:
                right_target_index = "Normal"
                
            st.subheader(f"Grad-CAM Visualization (Target class: {right_target_index})")

            gcol_r, gcol_l = st.columns(2)

            if right_cam_vis is not None:
                gcol_r.markdown("**Right Foot**")
                gcol_r.image(right_cam_vis, width='stretch')

            if left_cam_vis is not None:
                gcol_l.markdown("**Left Foot**")
                gcol_l.image(left_cam_vis, width='stretch')

if __name__ == "__main__":
    app()