Views
No views yet
1import torch
2from torchvision.transforms import Compose, ToTensor, Normalize, Pad
3from efficientnet_pytorch import EfficientNet
4from PIL import Image
5
6class ResizeAndPad:
7 def __init__(self, target_size=224):
8 self.target_size = target_size
9
10 def __call__(self, img):
11 w, h = img.size
12 if w > h:
13 new_w = self.target_size
14 new_h = int(h * self.target_size / w)
15 else:
16 new_h = self.target_size
17 new_w = int(w * self.target_size / h)
18 img = img.resize((new_w, new_h), Image.BILINEAR)
19 pad_w = self.target_size - new_w
20 pad_h = self.target_size - new_h
21 padding = (pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2)
22 return Pad(padding, fill=0)(img)
23
24transform = Compose([
25 ResizeAndPad(224),
26 ToTensor(),
27 Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
28])
29
30mapping_steamdbid_game = {
31 570: 'DOTA 2',
32 730: 'Counter-Strike 2',
33 105600: 'Terraria',
34 252490: 'Rust',
35 381210: 'Dead by Daylight',
36 418370: 'Resident Evil 7 Biohazard',
37 578080: 'PUBG: BATTLEGROUNDS',
38 883710: 'Resident Evil 2 Remake',
39 952060: 'Resident Evil 3 Remake',
40 1196590: 'Resident Evil Village',
41 1671340: 'Fears to Fathom - Home Alone (Episode 1)',
42 1763050: 'Fears to Fathom - Norwood Hitchhiker (Episode 2)',
43 1808500: 'ARC Raiders',
44 2050650: 'Resident Evil 4 Remake',
45 2120900: 'Fears to Fathom - Carson House (Episode 3)',
46 2506160: 'Fears to Fathom - Ironbark Lookout (Episode 4)',
47 2507950: 'Delta Force',
48 2961530: 'Fears to Fathom - Woodbury Getaway (Episode 5)',
49 3240220: 'Grand Theft Auto V',
50 3764200: 'Resident Evil Requiem',
51}
52
53checkpoint = torch.load("game_classifier_best_new.pth", map_location="cpu")
54steamdb_to_idx = {steamdb_id: idx for idx, steamdb_id in enumerate(mapping_steamdbid_game.keys())}
55idx_to_steamdb = {idx: steamdb_id for steamdb_id, idx in steamdb_to_idx.items()}
56
57model = EfficientNet.from_name("efficientnet-b0", num_classes=checkpoint["num_classes"])
58model.load_state_dict(checkpoint["model_state_dict"])
59model.eval()
60
61image = Image.open("screenshot_videogame.png").convert("RGB")
62input_tensor = transform(image).unsqueeze(0)
63
64with torch.no_grad():
65 outputs = model(input_tensor)
66 probabilities = torch.softmax(outputs, dim=1)[0]
67 top_prob, top_idx = probabilities.max(0)
68
69steamdb_id = idx_to_steamdb[top_idx.item()]
70print(f"{mapping_steamdbid_game[steamdb_id]}: {top_prob.item() * 100:.2f}%")