Predict file to run yourself
Browse files- predict.py +20 -0
predict.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from model import CnnNet
|
| 5 |
+
|
| 6 |
+
# Index order used in training: 0 = background, 1 = helicopter, 2 = drone
|
| 7 |
+
CLASS_NAMES = ["background", "helicopter", "drone"]
|
| 8 |
+
|
| 9 |
+
model = CnnNet()
|
| 10 |
+
model.load_state_dict(torch.load("weightsfilefromspectrogram.pth", map_location="cpu"))
|
| 11 |
+
model.eval()
|
| 12 |
+
|
| 13 |
+
def predict(image_path):
|
| 14 |
+
# Spectrograms are single-channel, 480x640, pixel values scaled to 0-1
|
| 15 |
+
img = Image.open(image_path).convert("L").resize((640, 480))
|
| 16 |
+
x = torch.tensor(np.array(img) / 255.0, dtype=torch.float32)
|
| 17 |
+
x = x.unsqueeze(0).unsqueeze(0) # shape [1, 1, 480, 640]
|
| 18 |
+
with torch.no_grad():
|
| 19 |
+
probs = torch.exp(model(x))[0] # the model outputs log-probabilities
|
| 20 |
+
return {name: float(p) for name, p in zip(CLASS_NAMES, probs)}
|