I am a High School student trying to do some fun projects and put it onto my website. Currently, I am working on a rock, paper, scissors game with OpenCV, but when I just try it locally on my webcam it takes like 2 minutes to load and when I see the webcam, it is really slow and laggy. I was wondering how I can fix this. I plan on using a React.js frontend and a Django or Flask backend. Is there something wrong I am doing in my script or do I have to change the architecture when adding the frontend and backend. Or is there some place to host the frontend and backend to compute faster and fix the problem? Or is there a tool I should be using instead of OpenCV?
from ultralytics import YOLO
import cv2
import random
import time
from ultralytics.utils.plotting import Annotator
# Initialize the YOLO model
model = YOLO('runs\detect\train6\weights\best.pt')
# Initialize the webcam
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Set frame width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # Set frame height
cap.set(cv2.CAP_PROP_FPS, 15) # Limit the frames per second to reduce processing load
player_score = 0
cpu_score = 0
def determine_winner(player, cpu):
global player_score, cpu_score
if player == cpu:
return "Tie!"
elif (player == 'rock' and cpu == 'scissors') or
(player == 'scissors' and cpu == 'paper') or
(player == 'paper' and cpu == 'rock'):
player_score += 1
return "Player wins!"
else:
cpu_score += 1
return "CPU wins!"
choices = ['rock', 'paper', 'scissors']
while True:
ret, img = cap.read()
if not ret:
break # Exit loop if no frame is captured
# Perform prediction using the model
results = model.predict(img)
annotator = Annotator(img, line_width=2, example_text='')
# Display countdown
for countdown in ["Rock", "Paper", "Shoot!"]:
cv2.putText(img, countdown, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('YOLO V8 Detection', img)
cv2.waitKey(1000) # Wait for 1 second for each countdown step
cpu_choice = random.choice(choices)
player_choice = None
if results:
for r in results:
boxes = r.boxes
for box in boxes:
b = box.xyxy[0]
c = box.cls
player_choice = model.names[int(c)]
annotator.box_label(b, f"{player_choice} vs CPU: {cpu_choice}")
if player_choice:
game_result = determine_winner(player_choice, cpu_choice)
cv2.putText(img, game_result, (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.putText(img, f"Player: {player_score} CPU: {cpu_score}", (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
# Display the final frame with annotations
img = annotator.result()
cv2.imshow('YOLO V8 Detection', img)
cv2.waitKey(5000) # Wait for 5 seconds after displaying the result
if cv2.waitKey(1) & 0xFF == ord(' '):
break
cap.release()
cv2.destroyAllWindows()
I tried multithread processing and trying to make the loop more efficient, but it did not make a difference.
Raiyan Zaman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.