-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathget_frame_stats.py
More file actions
192 lines (153 loc) · 5.53 KB
/
get_frame_stats.py
File metadata and controls
192 lines (153 loc) · 5.53 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
import os
import cv2
import statistics
from pathlib import Path
def get_video_frame_count(video_path):
"""
Get the total number of frames in a video file.
Args:
video_path (str): Path to the video file
Returns:
int: Number of frames, or None if error
"""
try:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: Could not open video {video_path}")
return None
# Get total frame count
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
return frame_count
except Exception as e:
print(f"Error processing {video_path}: {str(e)}")
return None
def scan_video_folder(folder_path, verbose=False):
"""
Scan a folder for video files and analyze frame counts.
Args:
folder_path (str): Path to the folder containing videos
verbose (bool): Whether to show detailed processing info
Returns:
dict: Statistics about video frame counts
"""
# Common video file extensions
video_extensions = {
".mp4",
".avi",
".mov",
".mkv",
".wmv",
".flv",
".webm",
".m4v",
".3gp",
}
folder = Path(folder_path)
if not folder.exists():
print(f"Error: Folder '{folder_path}' does not exist")
return None
frame_counts = []
video_info = []
print(f"Scanning folder: {folder_path}")
# Find all video files in the folder
video_files = []
for file_path in folder.rglob("*"):
if file_path.is_file() and file_path.suffix.lower() in video_extensions:
video_files.append(file_path)
if not video_files:
print("No video files found in the specified folder")
return None
print(f"Processing {len(video_files)} video files...")
# Process each video file
processed_count = 0
for i, video_file in enumerate(video_files, 1):
if verbose:
print(f"Processing ({i}/{len(video_files)}): {video_file.name}")
frame_count = get_video_frame_count(str(video_file))
if frame_count is not None:
frame_counts.append(frame_count)
video_info.append(
{
"filename": video_file.name,
"path": str(video_file),
"frames": frame_count,
}
)
processed_count += 1
if verbose:
print(f" Frames: {frame_count}")
else:
if verbose:
print(f" Failed to process")
# Show progress every 100 files
if not verbose and i % 100 == 0:
print(f" Processed {i}/{len(video_files)} files...")
print(f"Successfully processed {processed_count}/{len(video_files)} videos")
if not frame_counts:
print("No videos could be processed successfully")
return None
# Calculate statistics
stats = {
"total_videos": len(frame_counts),
"mean_frames": statistics.mean(frame_counts),
"min_frames": min(frame_counts),
"max_frames": max(frame_counts),
"median_frames": statistics.median(frame_counts),
"total_frames": sum(frame_counts),
"video_details": video_info,
}
return stats
def print_statistics(stats, show_all_videos=False):
"""Print the video frame statistics in a formatted way."""
if not stats:
return
print("\n" + "=" * 50)
print("VIDEO FRAME ANALYSIS RESULTS")
print("=" * 50)
print(f"Total videos processed: {stats['total_videos']}")
print(f"Total frames across all videos: {stats['total_frames']:,}")
print()
print("FRAME COUNT STATISTICS:")
print(f" Mean (Average): {stats['mean_frames']:.2f} frames")
print(f" Minimum: {stats['min_frames']} frames")
print(f" Maximum: {stats['max_frames']} frames")
print(f" Median: {stats['median_frames']:.2f} frames")
print()
# Find videos with min and max frames
min_videos = [
v for v in stats["video_details"] if v["frames"] == stats["min_frames"]
]
max_videos = [
v for v in stats["video_details"] if v["frames"] == stats["max_frames"]
]
print("VIDEOS WITH MINIMUM FRAMES:")
for video in min_videos[:3]: # Show only first 3
print(f" {video['filename']}: {video['frames']} frames")
if len(min_videos) > 3:
print(f" ... and {len(min_videos) - 3} more")
print("\nVIDEOS WITH MAXIMUM FRAMES:")
for video in max_videos[:3]: # Show only first 3
print(f" {video['filename']}: {video['frames']} frames")
if len(max_videos) > 3:
print(f" ... and {len(max_videos) - 3} more")
if show_all_videos:
print("\nALL VIDEO DETAILS:")
print("-" * 50)
for video in sorted(stats["video_details"], key=lambda x: x["frames"]):
print(f"{video['filename']}: {video['frames']} frames")
def main():
"""Main function to run the video frame analysis."""
folder_path = "UCF-101"
# Ask for verbosity preference
# verbose_input = input("Show detailed processing (y/n, default=n): ").strip().lower()
verbose = False
# Ask if user wants to see all video details
# show_all_input = input("Show all video details in results (y/n, default=n): ").strip().lower()
show_all = False
# Scan the folder and get statistics
stats = scan_video_folder(folder_path, verbose=verbose)
# Print results
print_statistics(stats, show_all_videos=show_all)
if __name__ == "__main__":
main()