Give me the python script to load a model generated by yolov11, to recognize cards…
- User
Give me the python script to load a model generated by yolov11, to recognize cards displayed by webcam, and display on screen which card it is
- Assistant
Give me the python script to load a model generated by yolov11, to recognize cards displayed by webcam, and display on screen which card it is
Certainly! Below is a Python script that loads a custom YOLOv5 model (assuming it's trained to recognize playing cards), captures video from your webcam, processes each frame to detect and recognize the cards, and displays the results in real-time on your screen.
Please make sure you have your custom YOLOv5 model saved as model.pt. Also, ensure you have the necessary libraries installed (torch, opencv-python) and that you have access to the Ultralytics YOLOv5 repository.
import torch
import cv2
import numpy as np
# Load the custom YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='model.pt', force_reload=True)
# Start the webcam video stream
cap = cv2.VideoCapture(0) # Change the index if you have multiple webcams
if not cap.isOpened():
print("Error: Could not open video stream from webcam.")
exit()
while True:
# Read a frame from the webcam
ret, frame = cap.read()
if not ret:
print("Error: Failed to read frame from webcam.")
break
# Perform inference on the frame
results = model(frame)
# Extract bounding boxes, class labels, and confidence scores
# results.xyxy[0] returns a tensor with detections in the format:
# [x1, y1, x2, y2, confidence, class]
detections = results.xyxy[0]
for detection in detections:
x1, y1, x2, y2, confidence, cls = detection
# Convert coordinates and class to integer
x1 = int(x1.item())
y1 = int(y1.item())
x2 = int(x2.item())
y2 = int(y2.item())
cls = int(cls.item())
# Get the class label from the model's class names
label = model.names[cls]
confidence = confidence.item()
# Draw the bounding box around the detected card
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Prepare the label text with the class name and confidence
label_text = f"{label}: {confidence:.2f}"
# Put the label text above the bounding box
cv2.putText(frame, label_text, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the frame with detections
cv2.imshow('Card Recognition', frame)
# Exit the loop when 'q' key is pressed
if cv2.waitKey(1) == ord('q'):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
Instructions and Notes:
Custom Model Path: Replace 'model.pt' with the path to your custom YOLOv5 model file if it's saved elsewhere.
Dependencies:
pip install torch torchvisionpip install opencv-pythonUltralytics YOLOv5 Repository: This script uses torch.hub to load the YOLOv5 model directly from the Ultralytics repository. Make sure you have internet access for torch.hub to download the repository. If you encounter issues, you can clone the repository manually:
git clone https://github.com/ultralytics/yolov5.git
Then, adjust the script to load the local model:
model = torch.hub.load('path/to/yolov5', 'custom', path='model.pt', source='local')
Webcam Index: If you have multiple cameras connected and the script is not accessing the correct one, change cv2.VideoCapture(0) to cv2.VideoCapture(1) or another appropriate index.
Class Names: Your custom model should include class names. These are accessible via model.names. Make sure your model was trained with the correct class labels for card recognition.
Real-Time Display: The script processes frames in real-time. Depending on your system's performance and the model's complexity, you might experience latency. For better performance, consider resizing the frame before inference:
frame_resized = cv2.resize(frame, (640, 480))
results = model(frame_resized)
Remember to adjust drawing coordinates accordingly.
Exiting the Program: Press the 'q' key while the display window is in focus to exit the loop and close the program.
Example Output:
When you run the script and display a playing card in front of your webcam, the program should:
Troubleshooting:
No Detections: If the model isn't detecting the cards, ensure that:
Errors Loading Model: Double-check the path to your model.pt file and ensure it's accessible.
Library Versions: Compatibility issues can occur with different versions of libraries. Ensure you're using versions of PyTorch and OpenCV compatible with your model and Python version.
Final Note:
This script provides a starting point for recognizing cards using a YOLOv5 model and a webcam. Depending on your specific requirements or model version, you might need to adjust the script further. If you have any questions or need assistance with modifications, feel free to ask!
Not yet included in a published release.