#大有學(xué)問#
雖然我www.喜歡學(xué)習(xí),但是實(shí)在不想被冗長得視頻浪費(fèi)時(shí)間,于是只好官網(wǎng)動手。
首先引入所需庫(OpenCV):
```python
import cv2
import os
接著,定義一個(gè)名為 `detect_contours()` 得函數(shù),用于計(jì)算給定幀差分圖像中得輪廓數(shù):
```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
```
進(jìn)入循環(huán)處理過程,首先通過cv2.VideoCapture()打開輸入視頻并獲取其FPS。接著,讀取視頻得每一幀并計(jì)算灰度圖像得可能嗎?差值:
```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)
```
接著,調(diào)用 `detect_contours()` 函數(shù)計(jì)算差異圖像中得輪廓數(shù)量。當(dāng)輪廓數(shù)量大于設(shè)定閾值時(shí),將當(dāng)前幀視為關(guān)鍵幀并保存:
```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
```
圖文無關(guān)
處理完整個(gè)視頻后,程序釋放視頻資源并輸出提取到得關(guān)鍵幀數(shù)量:
```python
cap.release()
print(f'Extracted {key_frame_count - 1} key frames.')
```
通過設(shè)定不同得時(shí)間間隔和閾值,專業(yè)根據(jù)官網(wǎng)得需求提取不同數(shù)量得關(guān)鍵幀,從而直觀地分析視頻內(nèi)容而無需觀看完整視頻,節(jié)省了寶貴得時(shí)間。


