write me code for implementing yolov8 large for cctv footage that has 4 diff temp images and 11 videos to train on. and give the detailed video of that particular image of person identifying that person. this code must take video and image from the user and give the detailed video to user.
Assistant
Certainly! Below is a Python script that implements the YOLOv8 large model using the Ultralytics YOLO library. The code trains the model on your provided dataset (4 images and 11 videos) and then uses the trained model to detect a specific person in a new video based on the provided image of that person.
Please ensure you have the necessary libraries installed (ultralytics and its dependencies). You can install them using pip install ultralytics.
python
# Import necessary libraries
from ultralytics import YOLO
import cv2
import os
import shutil
# Function to extract frames from videos and save them as images
def extract_frames_from_videos(video_paths, output_folder, frame_skip=30):
os.makedirs(output_folder, exist_ok=True)
for video_path in video_paths:
cap = cv2.VideoCapture(video_path)
frame_count = 0
success, frame = cap.read()
while success:
if frame_count % frame_skip == 0:
frame_filename = os.path.join(output_folder, f"{os.path.basename(video_path)}_frame_{frame_count}.jpg")
cv2.imwrite(frame_filename, frame)
success, frame = cap.read()
frame_count += 1
cap.release()
# Paths to your 4 images and 11 videos for training
training_images = ['./training_data/image1.jpg', './training_data/image2.jpg', './training_data/image3.jpg', './training_data/image4.jpg']
training_videos = ['./training_data/video1.mp4', './training_data/video2.mp4', './training_data/video3.mp4', './training_data/video4.mp4',
'./training_data/video5.mp4', './training_data/video6.mp4', './training_data/video7.mp4', './training_data/video8.mp4',
'./training_data/video9.mp4', './training_data/video10.mp4', './training_data/video11.mp4']
# Create a dataset directory structure
dataset_dir = './custom_dataset'
train_images_dir = os.path.join(dataset_dir, 'images', 'train')
val_images_dir = os.path.join(dataset_dir, 'images', 'val')
labels_dir = os.path.join(dataset_dir, 'labels')
os.makedirs(train_images_dir, exist_ok=True)
os.makedirs(val_images_dir, exist_ok=True)
os.makedirs(labels_dir, exist_ok=True)
# Copy training images to the dataset directory
for img_path in training_images:
shutil.copy(img_path, train_images_dir)
# Extract frames from training videos and save them to the training images directory
extract_frames_from_videos(training_videos, train_images_dir)
# Prepare a simple YAML configuration for the dataset
data_yaml = """
train: ./custom_dataset/images/train
val: ./custom_dataset/images/val
nc: 1
names: ['person_of_interest']
"""
# Save the dataset configuration
with open(os.path.join(dataset_dir, 'data.yaml'), 'w') as f:
f.write(data_yaml)
# Assume that annotations are prepared and saved in YOLO format in the labels directory
# For simplicity, the code to annotate images is not included
# You can use tools like LabelImg or Roboflow to annotate your dataset
# Initialize the YOLOv8 model (large model)
model = YOLO('yolov8l.pt') # Pre-trained model
# Train the model on your custom dataset
model.train(data=os.path.join(dataset_dir, 'data.yaml'), epochs=50, imgsz=640)
# Load the trained model
model = YOLO('runs/detect/train/weights/best.pt')
# Function to detect the person in a video based on an image
def detect_person_in_video(model, person_image_path, input_video_path, output_video_path):
# Read the person image
person_image = cv2.imread(person_image_path)
# Optionally, extract features of the person image if needed
# Open the input video
cap = cv2.VideoCapture(input_video_path)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
# Prepare to write the output video
out = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (frame_width, frame_height))
while True:
ret, frame = cap.read()
if not ret:
break
# Run detection on the frame
results = model(frame)
# Process the results
for result in results:
boxes = result.boxes
for box in boxes:
# Extract bounding box coordinates
x1, y1, x2, y2 = box.xyxy[0]
conf = box.conf[0]
cls = box.cls[0]
label = model.model.names[int(cls)]
# Draw bounding box and label on the frame
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, f'{label} {conf:.2f}', (int(x1), int(y1)-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
# Write the frame to the output video
out.write(frame)
# Release video resources
cap.release()
out.release()
# Get video and image input from the user
input_video_path = input("Enter the path to the input video: ")
person_image_path = input("Enter the path to the image of the person to detect: ")
output_video_path = 'output_detected_video.mp4'
# Run the detection
detect_person_in_video(model, person_image_path, input_video_path, output_video_path)
print(f"Detection complete. The output video is saved as {output_video_path}")
Notes:
Data Preparation: The code assumes that you have annotated your images and frames extracted from videos. Proper annotations are crucial for training an effective model. You can use annotation tools like LabelImg or Roboflow.
Training: The model is trained for 50 epochs, which you can adjust based on your needs. Ensure that your dataset is sufficiently large and well-annotated for effective training.
Detection Function: The detect_person_in_video function processes each frame of the input video, runs detection, and writes the frames with bounding boxes to the output video.
User Input: The script takes the input video path and the image of the person to detect from the user. Make sure to provide correct paths when prompted.
Output: The processed video with detections is saved as output_detected_video.mp4 in the current directory.
Before Running the Script:
Install Dependencies:
bash
pip install ultralytics
pip install opencv-python
Prepare Your Data: Ensure that the images and videos are placed in the specified directories, and annotations are completed.
Adjust Paths: Modify the paths in the script to match the actual locations of your data.
Annotations: If you haven't annotated your data yet, you need to do this before training. YOLO models require annotations in a specific format.
Additional Tips:
Hardware Requirements: Training deep learning models is computationally intensive. It's recommended to use a machine with a GPU.
Model Size: If you encounter memory issues with yolov8l.pt (large model), consider using yolov8m.pt (medium) or yolov8s.pt (small).
Testing the Model: After training, you can test the model on test images or videos to see how well it performs before running it on new inputs.
Example Usage:
When you run the script, it will prompt:
code
Enter the path to the input video: ./user_data/input_video.mp4
Enter the path to the image of the person to detect: ./user_data/person.jpg
Make sure to replace the paths with the actual paths to your video and image.
Disclaimer: This script is a simplified example to illustrate the process. In a production environment, you would need to handle exceptions, validate user inputs, and possibly integrate with a user interface for better usability.
Let me know if you need further assistance or modifications to the script!