MCPcopy Create free account
hub / github.com/ndleah/python-mini-project / main

Function main

Object_Detection/object-detection.py:7–62  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

5device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
6
7def main():
8
9 # Load YOLOv9 model
10 model = YOLO('yolov9c.pt')
11 model.to(device)
12
13 # Initialize video capture (0 for default camera)
14 cap = cv2.VideoCapture(0)
15
16 # Check if the video capture device is opened
17 if not cap.isOpened():
18 print("Error: Could not open video capture device")
19 return
20
21 while True:
22 # Capture frame-by-frame
23 ret, frame = cap.read()
24
25 if not ret:
26 print("Error: Could not read frame")
27 break
28
29 # Use YOLOv9 model to make predictions
30 results = model(frame)
31
32 # Process the results
33 for result in results:
34 # Loop through each detected object
35 for box in result.boxes:
36 # Get coordinates and class label
37 x1, y1, x2, y2 = box.xyxy[0]
38 label_id = int(box.cls[0].item())
39 confidence = box.conf[0].item()
40
41 # Get the class label from YOLO model
42 class_label = model.names[label_id]
43
44 # Create the label text
45 label_text = f"{class_label}: {confidence:.2f}"
46
47 # Draw bounding box on the frame
48 cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
49
50 # Draw the label text on the frame above the bounding box
51 cv2.putText(frame, label_text, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
52
53 # Display the frame with bounding boxes and labels
54 cv2.imshow('Real-Time Object Detection', frame)
55
56 # Exit the loop if the user presses 'q'
57 if cv2.waitKey(1) & 0xFF == ord('q'):
58 break
59
60 # Release the video capture device and close the window
61 cap.release()
62 cv2.destroyAllWindows()
63
64if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected