Building a Real-Time Logistics Counting System with YOLOv10 and Flask
In this blog, we’ll walk through the steps to create a Logistics Counting System using YOLOv10 for real-time object detection and Flask for the web interface. This system is designed to count different types of logistics-related objects (e.g., trucks, forklifts, pallets) using computer vision in a live video stream.
We’ll cover the following steps:
- Setting up the environment
- Training a custom YOLOv10 model
- Integrating the model into a Flask web app
- Streaming real-time video and counting detected objects
Let’s dive in!
Step 1: Setting Up the Environment
To build this project, you will need a few dependencies. You can install them by running the following commands:
pip install opencv-python
pip install ultralytics
pip install supervision
pip install Flask
Make sure you have OpenCV, Ultralytics YOLOv10, Supervision, and Flask installed. These libraries will handle video streaming, object detection, and the web interface.
Step 2: YOLOv10 Model Training
Before using the YOLOv10 model, you need to ensure it’s trained with your custom dataset that includes logistics-related objects like forklifts, pallets, trucks, etc. For this example, we’ll assume that your model is trained and saved as last.pt.
If you haven’t trained a YOLOv10 model yet, you can follow these steps:
- Label your dataset using tools like LabelImg or Roboflow.
- Train your custom YOLOv10 model using the Ultralytics library:
from ultralytics import YOLOv10
model = YOLOv10(‘yolov10.yaml’) # Initialize a new model
model.train(data=‘path/to/your/logistics_data.yaml’, epochs=50)
model.save(‘last.pt’)
Once you have your custom-trained model, we can integrate it into the Flask web application.
Step 3: Creating the Flask Web Application
The following Python script sets up the Flask app, integrates the YOLOv10 model, and enables real-time video streaming from a webcam. It also counts the detected objects and displays them in real-time.
import cv2
import os
import supervision as sv
from ultralytics import YOLOv10
from flask import Flask, render_template, Response, jsonify# Initialize Flask appapp = Flask(__name__)
# Load the model (ensure this is trained with your custom dataset)model = YOLOv10(“last.pt”)
# Replace category_dict with your custom class namescategory_dict = {
0: ‘barcode’, 1: ‘car’, 2: ‘cardboard box’, 3: ‘fire’, 4: ‘forklift’,
5: ‘freight container’, 6: ‘gloves’, 7: ‘helmet’, 8: ‘ladder’, 9: ‘license plate’,
10: ‘person’, 11: ‘qr code’, 12: ‘road sign’, 13: ‘safety vest’, 14: ‘smoke’,
15: ‘traffic cone’, 16: ‘traffic light’, 17: ‘truck’, 18: ‘van’, 19: ‘wood pallet’
}
# Dictionary to hold the count of detected objects
object_counts = {category: 0 for category in category_dict.values()}
def generate_frames():
cap = cv2.VideoCapture(0) # 0 is typically the default webcam
if not cap.isOpened():
raise RuntimeError(“Error: Could not open webcam.”)
bounding_box_annotator = sv.BoundingBoxAnnotator()
while True:
ret, frame = cap.read()
if not ret:
break
# Run the YOLOv10 model on the current frame
results = model(frame)[0]
# Convert results to Supervision Detections
detections = sv.Detections.from_ultralytics(results)
# Reset object count for each frame
global object_counts
object_counts = {category: 0 for category in category_dict.values()}
for box, class_id, confidence in zip(detections.xyxy, detections.class_id, detections.confidence):
class_name = category_dict.get(class_id, “Unknown”) # Use custom class names
object_counts[class_name] += 1 # Increment count for each detected object
# Annotate the detection on the frame
cv2.rectangle(frame, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (255, 0, 0), 2)
cv2.putText(frame, f”{class_name}: {confidence:.2f}“, (int(box[0]), int(box[1] – 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)
# Encode the frame for web streaming
ret, buffer = cv2.imencode(‘.jpg’, frame)
frame = buffer.tobytes()
# Yield the frame for Flask streaming
yield (b’–frame\r\n’
b’Content-Type: image/jpeg\r\n\r\n’ + frame + b’\r\n’)
cap.release()
@app.route(‘/’)
def index():
# Load the HTML page
return render_template(‘index.html’)
@app.route(‘/video_feed’)
def video_feed():
# Video streaming route
return Response(generate_frames(), mimetype=‘multipart/x-mixed-replace; boundary=frame’)
@app.route(‘/object_counts’)
def get_object_counts():
# Return the object counts as JSON
return jsonify(object_counts)
if __name__ == “__main__”:
app.run(debug=True, host=‘0.0.0.0’)
Step 4: Flask Web Interface Setup
To display the video stream and object counts, create an index.html file in a templates/ directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logistics Counting System</title>
</head>
<body>
<h1>Logistics Counting System</h1>
<img src="{{ url_for('video_feed') }}" width="800px">
<h2>Object Counts</h2>
<ul id="counts-list"></ul><script>// Fetch object counts from the server and update the webpage
function fetchObjectCounts() {
fetch(‘/object_counts’)
.then(response => response.json())
.then(data => {
let countsList = document.getElementById(‘counts-list’);
countsList.innerHTML = ”;
for (const [key, value] of Object.entries(data)) {
let listItem = document.createElement(‘li’);
listItem.textContent = `${key}: ${value}`;
countsList.appendChild(listItem);
}
});
}
// Refresh object counts every secondsetInterval(fetchObjectCounts, 1000);
</script>
</body>
</html>
Step 5: Running the Application
To run the app, execute:
python app.py
Open a web browser and go to http://localhost:5000/. You’ll see the live video stream and the real-time counts of detected objects in your logistics management system.
Conclusion
In this tutorial, we have successfully built a Logistics Counting System using a custom-trained YOLOv10 model and deployed it with a Flask web interface. This system can be used to count logistics-related objects in real-time, making it a powerful tool for automating tasks like inventory tracking and warehouse management.
With this foundation, you can expand the system to include additional features like detection alerts, object tracking, or data logging.