Repository navigation
Expand file tree
/
Copy pathencode_submission.py
More file actions
190 lines (145 loc) · 6.15 KB
/
Copy pathencode_submission.py
File metadata and controls
190 lines (145 loc) · 6.15 KB
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
import json
import torch
import matplotlib.pyplot as plt
import numba
import numpy as np
from numba import types
import numpy.typing as npt
import pandas as pd
import scipy.optimize
import torch
import torch.nn.functional as F
from edarnn import *
from dataloader import *
from scoring import *
class ParticipantVisibleError(Exception):
pass
@numba.jit(nopython=True)
def _rle_encode_jit(x: npt.NDArray, fg_val: int = 1) -> list[int]:
"""Numba-jitted RLE encoder."""
dots = np.where(x.T.flatten() == fg_val)[0]
run_lengths = []
prev = -2
for b in dots:
if b > prev + 1:
run_lengths.extend((b + 1, 0))
run_lengths[-1] += 1
prev = b
return run_lengths
def rle_encode(masks, fg_val: int = 1) -> str:
# single mask H×W
if hasattr(masks, "shape") and len(masks.shape) == 2:
if hasattr(masks, "cpu"):
masks = masks.detach().cpu().numpy()
masks = (masks > 0.5).astype(np.uint8)
return json.dumps(_rle_encode_jit(masks, fg_val))
# list of masks
rles = []
for x in masks:
if hasattr(x, "cpu"):
x = x.detach().cpu().numpy()
x = (x > 0.5).astype(np.uint8)
rles.append(json.dumps(_rle_encode_jit(x, fg_val)))
return ";".join(rles)
@numba.njit
def _rle_decode_jit(mask_rle: npt.NDArray, height: int, width: int) -> npt.NDArray:
"""
s: numpy array of run-length encoding pairs (start, length)
shape: (height, width) of array to return
Returns numpy array, 1 - mask, 0 - background
"""
if len(mask_rle) % 2 != 0:
# Numba requires raising a standard exception.
raise ValueError('One or more rows has an odd number of values.')
starts, lengths = mask_rle[0::2], mask_rle[1::2]
starts -= 1
ends = starts + lengths
for i in range(len(starts) - 1):
if ends[i] > starts[i + 1]:
raise ValueError('Pixels must not be overlapping.')
img = np.zeros(height * width, dtype=np.bool_)
for lo, hi in zip(starts, ends):
img[lo:hi] = 1
return img
def rle_decode(mask_rle: str, shape: tuple[int, int]) -> npt.NDArray:
"""
mask_rle: run-length as string formatted (start length)
empty predictions need to be encoded with '-'
shape: (height, width) of array to return
Returns numpy array, 1 - mask, 0 - background
"""
mask_rle = json.loads(mask_rle)
mask_rle = np.asarray(mask_rle, dtype=np.int32)
starts = mask_rle[0::2]
if sorted(starts) != list(starts):
raise ParticipantVisibleError('Submitted values must be in ascending order.')
try:
return _rle_decode_jit(mask_rle, shape[0], shape[1]).reshape(shape, order='F')
except ValueError as e:
raise ParticipantVisibleError(str(e)) from e
# Make sure device is consistent
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load model and weights
model = get_coco_initialized_model(num_classes=2)
#state = torch.load("./images/frozen_natural_300/natural_frozen_300epochs.pth", map_location=device) # load directly to device
state = torch.load("../pretrained_full.pth", map_location=device)
model.load_state_dict(state)
model.to(device) # ensure model is on same device as inputs
model.eval()
base_path = "../recodai-luc-scientific-image-forgery-detection/"
test_dataset = ForgeryDataset(paths['train_authentic'],paths['train_forged'],paths['train_masks'],)
test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False,collate_fn=lambda x: tuple(zip(*x)))
if __name__ == "__main__":
from pathlib import Path
""" ONLY PLOTS THE FIRST ELEM IN BATCH """
plot = True
dices = []
submission = {
"case_id": [],
"annotation": []
}
for idx, (image, target, filename) in enumerate(train_loader):
image = image[0] # take first item from batch
target = target[0]
raw_img, raw_mask = full_dataset.get_raw_img_mask(idx)
with torch.no_grad():
outputs = model(image.unsqueeze(0).to(device)) # forward pass
target_mask = combine_resize_submasks(target, raw_img, threshold = None)
outputs_orig_size = combine_resize_submasks(outputs[0], raw_img, threshold = 0.5)
######
target_mask_norm = resize_mask(target_mask.unsqueeze(0), image) # to normalized
target_paintedboxes = paint_boxes(outputs[0], target, torch.tensor(target_mask_norm))
target_paintedboxes = resize_mask(target_paintedboxes, raw_img) # to original
dice = soft_dice(outputs_orig_size, target_mask, True)
print(f"\nIdx: {idx} DICE: {dice:.4f}")
dices.append(dice)
if plot:
fig, ax = plt.subplots(1, 2, figsize=(10,5))
# Denormalize image for display
mean = torch.tensor([0.485, 0.456, 0.406]).view(3,1,1)
std = torch.tensor([0.229, 0.224, 0.225]).view(3,1,1)
image_denorm = image.cpu() * std + mean
image_denorm = resize_mask(image_denorm, target_mask)
image_plot = np.clip(image_denorm.squeeze(0).permute(1,2,0).numpy(), 0, 1)
ax[0].imshow(image_plot)
ax[0].imshow(target_paintedboxes.squeeze(0).squeeze(0).cpu().numpy(), alpha=0.5)
outputs_orig_size = np.clip(outputs_orig_size.cpu().numpy(), 0, 1)
ax[1].imshow(outputs_orig_size)
ax[0].set_title("Target mask + output boxes")
ax[1].set_title(" Output mask")
plt.savefig(str(idx)+".png")
if (len(outputs[0]["boxes"]) == 0):
submission["annotation"].append("authentic")
else:
print(outputs_orig_size.shape)
submission["annotation"].append(rle_encode(outputs_orig_size))
print(rle_encode(outputs_orig_size))
imagename = full_dataset.get_filename(idx)["image_id"]
submission["case_id"].append(Path(imagename).stem)
print(" MEAN DICE: ")
print(np.mean(dices), np.std(dices))
# Prepare submission
submission = {
"case_id": filename[0],
"submission": rle_encode([outputs_orig_size])
}