-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcamera-video-analysis.py
More file actions
205 lines (157 loc) Β· 6.2 KB
/
camera-video-analysis.py
File metadata and controls
205 lines (157 loc) Β· 6.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""
Camera Video Recording and Analysis Example
This example demonstrates recording video segments from camera
and analyzing them using PraisonAI vision agents.
Requirements:
pip install praisonaiagents opencv-python
Usage:
python camera-video-analysis.py
Environment Variables:
OPENAI_API_KEY=your_openai_api_key
"""
import cv2
import os
import time
from datetime import datetime
from praisonaiagents import Agent, Task, AgentTeam
class CameraVideoAnalyzer:
"""Camera video recording and analysis system"""
def __init__(self, camera_id=0):
"""
Initialize video analyzer
Args:
camera_id (int): Camera ID (0 for default)
"""
self.camera_id = camera_id
# Create video analysis agent
self.video_agent = Agent(
name="VideoAnalyst",
role="Video Content Analyzer",
goal="Analyze video content for activities, objects, and events",
backstory="Expert in video analysis and temporal event detection with computer vision expertise",
llm="gpt-4o-mini"
)
def record_video_segment(self, duration_seconds=10):
"""
Record a video segment from camera
Args:
duration_seconds (int): Length of video to record
Returns:
str: Path to recorded video file or None if failed
"""
cap = cv2.VideoCapture(self.camera_id)
if not cap.isOpened():
print(f"Error: Could not open camera {self.camera_id}")
return None
# Get video properties
fps = int(cap.get(cv2.CAP_PROP_FPS)) or 30
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Setup video writer
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
video_path = f"camera_recording_{timestamp}.mp4"
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(video_path, fourcc, fps, (width, height))
print(f"π¬ Recording video for {duration_seconds} seconds...")
print(f"πΉ Resolution: {width}x{height}, FPS: {fps}")
start_time = time.time()
frame_count = 0
try:
while (time.time() - start_time) < duration_seconds:
ret, frame = cap.read()
if ret:
out.write(frame)
frame_count += 1
# Show recording indicator
if frame_count % fps == 0: # Update every second
elapsed = int(time.time() - start_time)
remaining = duration_seconds - elapsed
print(f"β±οΈ Recording... {remaining}s remaining")
else:
break
finally:
cap.release()
out.release()
cv2.destroyAllWindows()
if frame_count > 0:
print(f"β
Video recorded: {video_path} ({frame_count} frames)")
return video_path
else:
print("β Failed to record video")
if os.path.exists(video_path):
os.remove(video_path)
return None
def analyze_video(self, video_path):
"""
Analyze recorded video
Args:
video_path (str): Path to video file
Returns:
dict: Analysis results
"""
task = Task(
name="analyze_video_content",
description="""Analyze this video recording and provide:
1. Summary of main activities and events observed
2. Timeline of key moments or changes
3. Identification of people, objects, and movements
4. Any notable interactions or behaviors
5. Overall assessment of what happened in the video
Focus on providing a comprehensive temporal analysis.""",
expected_output="Detailed video analysis with timeline and event description",
agent=self.video_agent,
images=[video_path] # PraisonAI supports video files in images parameter
)
agents = AgentTeam(
agents=[self.video_agent],
tasks=[task],
process="sequential",
)
return agents.start()
def record_and_analyze(self, duration=10):
"""
Record video and analyze it
Args:
duration (int): Recording duration in seconds
"""
# Record video
video_path = self.record_video_segment(duration)
if not video_path:
return None
print(f"\nπ Analyzing recorded video...")
# Analyze video
result = self.analyze_video(video_path)
# Clean up video file
if os.path.exists(video_path):
os.remove(video_path)
print(f"ποΈ Cleaned up temporary video file")
return result
def main():
"""Main function"""
print("π₯ Camera Video Recording and Analysis")
print("=" * 50)
# Configuration
camera_id = 0
recording_duration = 15 # seconds
print(f"πΉ Camera: {camera_id}")
print(f"β±οΈ Recording Duration: {recording_duration} seconds")
print("\nMake sure your camera is connected and accessible")
print("The system will record a video segment and then analyze it")
input("\nPress Enter to start recording...")
# Create analyzer and run
analyzer = CameraVideoAnalyzer(camera_id)
result = analyzer.record_and_analyze(recording_duration)
if result:
print("\n" + "="*60)
print("π VIDEO ANALYSIS RESULTS")
print("="*60)
for task_id, task_result in result["task_results"].items():
print(f"\nTask: {task_id}")
print("-" * 40)
print(task_result.raw)
print("\n" + "="*60)
print("β
Video analysis complete!")
else:
print("β Failed to record and analyze video")
if __name__ == "__main__":
main()