Your current script is running object detection and segmentation using a YOLO model from Ultralytics, then iterating through the results to create a list of pandas DataFrames, each containing information about detected objects.
Several potential bottlenecks could be slowing down your code, such as loading the model, running the prediction, transferring data from GPU to CPU, and handling the results. Below are some suggestions to possibly speed up your solution:
-
Batch Processing: If your video consists of many frames, consider batch processing if the model.predict() method supports it. This will utilize the GPU more effectively rather than processing one frame at a time.
-
Minimize Data Transfer: Minimizing the amount of data transferred between CPU and GPU can speed things up. If you do not need to process the mask data on the CPU, consider skipping that step.
-
Vectorized Operations: Instead of looping over results and appending to list_entries one DataFrame at a time, you can try to perform operations on the full numpy array and create a single DataFrame at the end.
-
Efficient DataFrame Creation: Appending to a list of DataFrames in a loop is slower compared to appending to a list of dictionaries and then creating one DataFrame at the end.
Here's an example of a streamlined version of your code:
from ultralytics import YOLO
import pandas as pd
model = YOLO("/content/saqib/best_seg_75.pt") # Load the model
results = model.predict('/content/out.mp4', save=True, save_txt=True, stream=True, save_frames=True)
entries = [] # Initialize a list to store entries
for result in results:
boxes = result.boxes.cpu().numpy()
probs = result.probs.cpu().numpy()
classes = boxes[:, -1] # Assuming last index stores class index
confidences = probs[:, -1] # Assuming last index stores confidence
entry = {
'item_no': range(1, len(boxes) + 1),
'class_name': [model.names[int(cls)] for cls in classes],
'confidence': (confidences * 100).astype(int)
}
entries.append(entry)
# Creating a single DataFrame from list of dictionaries
entries_df = pd.concat([pd.DataFrame(e) for e in entries], ignore_index=True)
In this code, I've made some assumptions about the shape and content of boxes and probs arrays. You might need to adjust these parts depending on the actual structure of your data.
Please note:
- This code assumes that the model output includes the class index and confidence in the last positions of the
boxes and probs arrays, respectively.
- You'll also want to ensure your system has enough memory to handle the large number of results before concatenating them into a single DataFrame.
To further speed up the process, you would ideally profile your code using tools like cProfile or line_profiler to see exactly where the bottlenecks are and then optimize those parts. Depending on the requirements of the rest of your workflow, you might be able to find additional optimizations.