forked from yzhaoinuw/mouse-pupil-analysis
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun_inference.py
More file actions
70 lines (52 loc) · 1.95 KB
/
Copy pathrun_inference.py
File metadata and controls
70 lines (52 loc) · 1.95 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
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 29 00:34:33 2025
@author: yzhao
"""
import os
from pathlib import Path
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
import numpy as np
from PIL import Image
from unet import UNet
from dataset import PupilDataset
checkpoint_dir = Path("checkpoints")
checkpoint_path = (
checkpoint_dir / "unet_attention_84pupils_pred_thresh=0.7_iou=0.8990.pth"
)
image_dir = "images_test_3/"
# Optional: blend with original for transparency
alpha = 0.9
pred_thresh = 0.8
image_paths = sorted(Path(image_dir).glob("*.png"))
test_dataset = PupilDataset(image_paths)
test_loader = DataLoader(test_dataset, batch_size=16, shuffle=False)
model = UNet(use_attention=True)
model.load_state_dict(torch.load(checkpoint_path))
model.eval()
model.to("cuda" if torch.cuda.is_available() else "cpu")
result_dir = "predictions_test"
os.makedirs(result_dir, exist_ok=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
with torch.no_grad():
for images, names in test_loader:
images = images.to(device)
preds = model(images)
preds = (preds > pred_thresh).float().cpu().numpy()
for i in range(len(images)):
# Load the original image from disk again (for visualization)
orig = Image.open(Path(image_dir) / names[i]).convert("L")
orig = transforms.CenterCrop((148, 148))(orig)
orig_np = np.array(orig)
# Create RGB image from grayscale
rgb = np.stack([orig_np] * 3, axis=-1)
# Overlay red where mask is 1
mask = preds[i].squeeze() # shape: (H, W)
overlay = rgb.copy()
overlay[mask == 1] = [255, 0, 0] # red where mask is positive
blended = (alpha * rgb + (1 - alpha) * overlay).astype(np.uint8)
# Save result
out_path = f"{result_dir}/{names[i]}"
Image.fromarray(blended).save(out_path)