Build a customer analytics system using OpenCV and YOLOv8 for jewelry and watch shops. Includes visitor counting, demographic analysis, and employee filtering with thread-safe UI implementation.
Build a customer analytics system for jewelry and watch shops using OpenCV and YOLOv8. This skill guides you through creating a thread-safe real-time video processing application with visitor counting, demographic analysis, and employee filtering.
Structure your project with clear separation of concerns:
```
src/
├── core/ # Main processing modules
├── models/ # ML models and weights
├── utils/ # Helper functions
├── config/ # Configuration files
├── data/ # Data storage
└── ui/ # User interface
```
1. **Follow PEP 8** for all Python code
2. **Naming conventions:**
- Constants: `UPPER_SNAKE_CASE`
- Variables: `snake_case`
- Classes: `PascalCase`
- Functions: `snake_case`
3. **Documentation:**
- Write function names and class names in English
- Use Turkish for comments and docstrings (or your preferred language)
- Include docstrings for all functions and classes
4. **File organization:**
- Create `__init__.py` for each module
- Keep related functionality together
Install these core libraries:
```python
opencv-python # Image processing and camera access
ultralytics # YOLOv8 for human detection
mediapipe # Alternative detection system (optional)
face-recognition # Face recognition (optional, requires dlib)
pandas # Data analysis
matplotlib # Visualization
seaborn # Statistical visualization
sqlite3 # Data storage (built-in)
tkinter # GUI framework (built-in)
```
**CRITICAL:** Always maintain thread safety in UI updates:
1. **Never update widgets from background threads**
2. **Use `root.after()` for timer-based updates** (33ms = 30 FPS target)
3. **Process frames in background, update UI in main thread**
4. **Manage image references properly:**
```python
photo = ImageTk.PhotoImage(image=image)
self.video_label.configure(image=photo)
self.video_label.image = photo # Keep reference!
```
5. **Safely add/remove frame callbacks**
6. **Store `current_image` thread-safely**
7. **Implement exception handling for system stability**
**Goal:** Establish camera input, human detection, and thread-safe UI
**Steps:**
1. Set up camera capture with OpenCV (target: 1280x720@30fps)
2. Integrate YOLOv8n (nano model for speed)
3. Create Tkinter UI with real-time video display
4. Implement timer-based frame updates (avoid threading issues)
5. Add start/stop controls
6. Display FPS monitoring
**Key code pattern:**
```python
def update_frame(self):
"""Timer-based frame update (main thread only)"""
if self.current_image is not None:
# Process image
photo = ImageTk.PhotoImage(image=self.current_image)
self.video_label.configure(image=photo)
self.video_label.image = photo
# Schedule next update (33ms = ~30 FPS)
self.root.after(33, self.update_frame)
```
**Goal:** Implement visitor counting and data persistence
**Steps:**
1. Count unique visitors per detection
2. Add timestamp for each entry
3. Export data to CSV
4. Integrate SQLite database:
```python
# Schema example
CREATE TABLE visitors (
id INTEGER PRIMARY KEY,
timestamp DATETIME,
count INTEGER,
confidence FLOAT
)
```
5. Implement daily log rotation
**Goal:** Filter out employees from visitor counts
**Steps:**
1. Create face database for employees
2. Implement face recognition using `face_recognition` library
3. Add employee registration UI
4. Hash face encodings for privacy
5. Filter detections to exclude recognized employees
**Goal:** Add age and gender estimation
**Steps:**
1. Integrate age estimation model
2. Add gender detection
3. Collect demographic statistics
4. Store anonymized demographic data
**Goal:** Visualize data and generate reports
**Steps:**
1. Analyze peak hours and foot traffic patterns
2. Create matplotlib/seaborn visualizations
3. Generate daily/weekly/monthly reports
4. Add export functionality for analytics
**Goal:** Implement returning customer detection and alerts
**Steps:**
1. Track returning customers using face recognition
2. Build dashboard with real-time metrics
3. Add alert system for unusual patterns
4. Implement GDPR-compliant data retention policies
1. **Resize frames for processing:** Use 640x480 for detection (resize from capture resolution)
2. **Use ROI (Region of Interest)** to focus on entrance area
3. **Timer-based UI updates:** 33ms interval for smooth 30 FPS
4. **Memory management:** Clear image references properly
5. **Target metrics:**
- Minimum 15 FPS
- Ideal 30 FPS
- Keep memory usage stable (no leaks)
1. **Use YOLOv8n (nano)** for best speed/accuracy balance
2. **Auto-detect CPU/GPU** and configure accordingly
3. **Implement model caching** to avoid repeated loads
4. **Consider batch inference** for future scalability
1. **Use SQLite for production data:**
- Visitor logs
- Employee database
- Analytics cache
2. **Create CSV backups** daily
3. **Hash sensitive data** (face encodings)
4. **Implement data retention policies** (GDPR compliance)
1. **Timestamp all operations**
2. **Mandatory error logging**
3. **Daily log rotation**
4. **Detailed debug mode** for troubleshooting
1. **Hash face encodings** before storage
2. **Use local storage only** (no cloud by default)
3. **Minimize network access**
4. **GDPR-compliant data processing:**
- Store only necessary data
- Allow data deletion requests
- Anonymize demographic data
1. **Input validation** for all user inputs
2. **Comprehensive exception handling**
3. **Graceful shutdown** procedures
4. **Automatic backup mechanisms**
1. **Use Turkish (or preferred language)** for all UI text
2. **Provide real-time updates** without lag
3. **Thread-safe widget updates** only
4. **Responsive design** that adapts to window size
5. **Include:**
- Loading indicators
- Clear error messages
- Status bar with system info
- Screenshot capture button
- Dark mode friendly colors
Create `test_requirements.py` to verify:
1. All required libraries installed
2. Camera access working
3. YOLOv8 model loading correctly
4. UI responsiveness
Test complete workflows:
1. End-to-end visitor detection and counting
2. Database write and read operations
3. Screenshot capture functionality
4. System startup and shutdown procedures
Provide multiple requirement files:
Note: Dlib requires Visual Studio C++ build tools on Windows. Provide instructions for optional installation.
1. **Primary support:** Windows 10/11
2. **Python version:** 3.8-3.10
3. **Camera support:** USB cameras and built-in webcams
4. **Test multiple camera indices** (0, 1, 2) for detection
1. **Camera index problems:** Try indices 0, 1, 2 sequentially
2. **UI freezing:** Check thread safety of widget updates
3. **Memory leaks:** Verify image references are cleared
4. **Model loading errors:** Ensure correct paths and permissions
Track these metrics:
Use semantic commit messages:
```
feat: Add new feature
fix: Bug fix
docs: Documentation update
style: Code formatting
refactor: Code refactoring
test: Add or fix tests
chore: Project maintenance
```
Write commit messages in Turkish (or your preferred language) with descriptive titles. Always note thread safety fixes and performance improvements.
```python
import cv2
from ultralytics import YOLO
import tkinter as tk
from PIL import Image, ImageTk
class CustomerAnalysisSystem:
def __init__(self, root):
self.root = root
self.model = YOLO('yolov8n.pt')
self.cap = cv2.VideoCapture(0)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
self.current_image = None
self.is_running = False
# UI setup
self.video_label = tk.Label(root)
self.video_label.pack()
# Start timer-based updates
self.update_frame()
def update_frame(self):
"""Thread-safe frame update"""
if self.is_running and self.cap.isOpened():
ret, frame = self.cap.read()
if ret:
# Run detection
results = self.model(frame, conf=0.5)
annotated = results[0].plot()
# Convert for Tkinter
rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)
img = Image.fromarray(rgb)
photo = ImageTk.PhotoImage(image=img)
# Update UI (main thread)
self.video_label.configure(image=photo)
self.video_label.image = photo
# Schedule next update (33ms = ~30 FPS)
self.root.after(33, self.update_frame)
```
These guidelines are living documents and should be updated as the project evolves. The current system status shows excellent foundation with working camera, active YOLOv8, and successful thread-safe UI updates. Build upon this stable base for advanced features.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/opencv-customer-analysis-system-for-retail/raw