Views
No views yet
1pip install torch torchvision timm huggingface_hub numpy Pillow
21import torch
2import numpy as np
3from PIL import Image
4from huggingface_hub import hf_hub_download
5from gazemoe_builder import get_gazemoe_model
6
7# --- 1. Load Model & Weights ---
8device = "cuda" if torch.cuda.is_available() else "cpu"
9model, transform = get_gazemoe_model()
10
11# Download custom 14MB weights from Hugging Face
12weights_path = hf_hub_download(repo_id="zdai257/GazeMoE", filename="GazeMoE.pt")
13state_dict = torch.load(weights_path, map_location=device)
14model.load_gazemoe_state_dict(state_dict)
15model.to(device).eval()
16
17# --- 2. Prepare Input ---
18# GazeMoE expects:
19# - images: [B, 3, 448, 448] tensor
20# - bboxes: A list of lists containing [xmin, ymin, xmax, ymax] normalized (0-1)
21raw_image = Image.open("example.jpg").convert("RGB")
22w, h = raw_image.size
23
24# Example: One person with a head bounding box (normalized) OR Multi-person heads in a list
25# Format: [xmin, ymin, xmax, ymax]
26example_bbox = [0.4, 0.2, 0.55, 0.4]
27
28inputs = {
29 "images": transform(raw_image).unsqueeze(dim=0).to(device),
30 "bboxes": [[example_bbox]]
31}
32
33# --- 3. Inference ---
34with torch.no_grad():
35 preds = model(inputs)
36
37# --- 4. Process Outputs ---
38# 'inout' predicts if the gaze is Inside (IFT) or Outside (OFT) the frame
39inout_prob = preds['inout'][0][0].item()
40
41if inout_prob < 0.5:
42 print(f"Gaze is OUT-OF-FRAME (Prob: {inout_prob:.2f})")
43else:
44 print(f"Gaze is IN-FRAME (Prob: {inout_prob:.2f})")
45
46 # Heatmap is 64x64. Get the (x, y) via argmax
47 heatmap = preds['heatmap'][0][0].cpu().numpy()
48
49 argmax = heatmap.flatten().argmax()
50 pred_y, pred_x = np.unravel_index(argmax, (64, 64))
51
52 # Normalize coordinates to 0-1
53 x_norm, y_norm = pred_x / 64.0, pred_y / 64.0
54
55 print(f"Estimated Gaze Target (Normalized): x={x_norm:.2f}, y={y_norm:.2f}")
56 print(f"Pixel Coordinates: X={x_norm * w:.1f}, Y={y_norm * h:.1f}")
57images: A torch.Tensor of shape (Batch, 3, 448, 448). Use the transform provided by the factory function to ensure correct normalization and resizing.bboxes: A list of lists. Each sub-list corresponds to an image in the batch and contains the head bounding box proposals in normalized coordinates .inout: A sigmoid output. Values indicate the person is looking at something outside the image boundaries.heatmap: A spatial map. The gaze target is typically identified by taking the argmax of this map to find the peak intensity coordinate.