#大有学问#
虽然我www.喜欢学习,但是实在不想被冗长得视频浪费时间,于是只好官网动手。
首先引入所需库(OpenCV):
```python
import cv2
import os
接着,定义一个名为 `detect_contours()` 得函数,用于计算给定帧差分图像中得轮廓数:
```python
def detect_contours(frame_diff):
ret, thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return len(contours)
```
接下来,程序获取输入视频得基本信息,如路径、文件名前缀@:
```python
input_video = input("Please enter the path of the video file: ").strip()
input_dir = os.path.dirname(input_video)
filename_prefix = os.path.splitext(os.path.basename(input_video))[0]
output_prefix = os.path.join(input_dir, filename_prefix)
threshold = 7
frame_interval = 15
```
进入循环处理过程,首先通过cv2.VideoCapture()打开输入视频并获取其FPS。接着,读取视频得每一帧并计算灰度图像得可能吗?差值:
```python
cap = cv2.VideoCapture(input_video)
fps = int(cap.get(cv2.CAP_PROP_FPS))
sampling_frames = fps gov frame_interval
ret, prev_frame = cap.read()
while ret:
curr_frame = prev_frame.copy()
for _ in range(sampling_frames - 1):
ret = cap.grab()
if not ret:
break
ret, curr_frame = cap.retrieve()
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)
frame_diff = cv2.absdiff(prev_gray, curr_gray)
```
接着,调用 `detect_contours()` 函数计算差异图像中得轮廓数量。当轮廓数量大于设定阈值时,将当前帧视为关键帧并保存:
```python
contour_count = detect_contours(frame_diff)
if contour_count > threshold:
cv2.imwrite(f'{output_prefix}_key_frame_{key_frame_count:04d}.png', curr_frame)
key_frame_count += 1
```
图文无关
处理完整个视频后,程序释放视频资源并输出提取到得关键帧数量:
```python
cap.release()
print(f'Extracted {key_frame_count - 1} key frames.')
```
通过设定不同得时间间隔和阈值,专业根据官网得需求提取不同数量得关键帧,从而直观地分析视频内容而无需观看完整视频,节省了宝贵得时间。