torinriley commited on
Commit
59755ed
1 Parent(s): facd432

Upload 2 files

Browse files
Files changed (2) hide show
  1. demo.py +65 -0
  2. model.pt +3 -0
demo.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ from model import get_model
4
+ from torchvision.transforms import ToTensor
5
+
6
+ num_classes = 4
7
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
+ model = get_model(num_classes).to(device)
9
+
10
+ checkpoint_path = "models/model.pt"
11
+ checkpoint = torch.load(checkpoint_path, map_location=device)
12
+ model.load_state_dict(checkpoint["model_state_dict"])
13
+ model.eval()
14
+
15
+ CONFIDENCE_THRESHOLD = 0.5
16
+
17
+ video_capture = cv2.VideoCapture(0)
18
+ if not video_capture.isOpened():
19
+ print("Error: Could not open video device.")
20
+ exit()
21
+
22
+ def preprocess_frame(frame):
23
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
24
+ frame_tensor = ToTensor()(frame_rgb).unsqueeze(0).to(device)
25
+ return frame_tensor
26
+
27
+ def draw_predictions(frame, predictions):
28
+ boxes = predictions[0]["boxes"]
29
+ labels = predictions[0]["labels"]
30
+ scores = predictions[0]["scores"]
31
+
32
+ label_map = {1: "yellow", 2: "red", 3: "blue"}
33
+
34
+ for box, label, score in zip(boxes, labels, scores):
35
+ if score >= CONFIDENCE_THRESHOLD:
36
+ x1, y1, x2, y2 = map(int, box)
37
+
38
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
39
+
40
+ color_name = label_map.get(label.item(), "unknown")
41
+ label_text = f"{color_name} game piece"
42
+ cv2.putText(frame, label_text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
43
+
44
+ return frame
45
+
46
+ print("Starting video stream... Press 'q' to quit.")
47
+ while video_capture.isOpened():
48
+ ret, frame = video_capture.read()
49
+ if not ret:
50
+ break
51
+
52
+ frame_tensor = preprocess_frame(frame)
53
+
54
+ with torch.no_grad():
55
+ predictions = model(frame_tensor)
56
+
57
+ frame = draw_predictions(frame, predictions)
58
+
59
+ cv2.imshow("Real-Time Object Detection", frame)
60
+
61
+ if cv2.waitKey(1) & 0xFF == ord("q"):
62
+ break
63
+
64
+ video_capture.release()
65
+ cv2.destroyAllWindows()
model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48fc2815a72c09a0fead45b7d6607c2945136ad4d9b2768a1cf9c57e78448214
3
+ size 330136991