give me a python code to run yolo with webcam
- User
give me a python code to run yolo with webcam
- Assistant
To run YOLO (You Only Look Once) using a webcam in Python, you'll typically use the OpenCV library for handling webcam input and a deep learning framework like PyTorch or TensorFlow to run the YOLO model. Below is an example using OpenCV and PyTorch. This example assumes you're using the YOLOv5 implementation from the
ultralytics/yolov5repository, which is a common starting point.First, ensure you have installed the required libraries:
bashpip install opencv-python opencv-python-headless torch torchvisionYou will also need to clone the YOLOv5 repository if you haven't done so:
bashgit clone https://github.com/ultralytics/yolov5.git cd yolov5 pip install -r requirements.txtHere's a Python script that uses YOLOv5 to process frames from the webcam:
pythonimport cv2 import torch from pathlib import Path # Load YOLOv5 model model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # Using 'yolov5s' model # Start video capture from webcam cap = cv2.VideoCapture(0) # 0 is the default camera while True: # Read frame from webcam ret, frame = cap.read() if not ret: break # Perform inference using YOLOv5 results = model(frame) # Parse results labels, confidence, boxes = results.xyxyn[0][:, -1], results.xyxyn[0][:, -2], results.xyxyn[0][:, :4] # Loop over detections and draw them on the frame for lb, conf, box in zip(labels, confidence, boxes): if conf > 0.3: # Draw only if confidence is above a threshold x1, y1, x2, y2 = int(box[0] * frame.shape[1]), int(box[1] * frame.shape[0]), int(box[2] * frame.shape[1]), int(box[3] * frame.shape[0]) label = f"{model.names[int(lb)]} {conf:.2f}" # Draw the bounding box and label on the image cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Display the frame with detections cv2.imshow('YOLOv5 Webcam', frame) # Press 'q' to exit the loop if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the webcam and close windows cap.release() cv2.destroyAllWindows()