由视频提取图片

由视频提取图片

从视频中隔帧或者使用帧差法提取图片

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
# -*-coding:utf-8 -*-
import cv2
import os
import glob
import numpy as np

__author__ = 'Heroinlj <heroinlj@gmail.com>'


# 隔帧提取图片
def extract_frames_by_frame(video_folders_path, dst_folder, index=1):
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
video = cv2.VideoCapture()
for video_path in glob.glob("{}/*.avi".format(video_path_folder)):
if not video.open(video_path):
print("can not open the video")
continue
count = 1
while True:
_, frame = video.read()
if frame is None:
break
if count % 100 == 0:
save_path = "{}\\{:>08d}.jpg".format(dst_folder, index)
if index % 1000 == 0:
print("save {:d} images".format(index))
print(video_path)
cv2.imwrite(save_path, frame)
index += 1
count += 1
video.release()
return index


# 帧差提取图片
def extract_frames_by_frame_diff(video_path_folder, dst_folder):
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
video = cv2.VideoCapture()
pre_frame = None
for video_path in glob.glob("{}/*.avi".format(video_path_folder)):
video_name = video_path.replace('\\', "/").split('/')[-1].split('.')[0]
# print(video_name)
index = 1
if not video.open(video_path):
print("can not open the video")
continue
count = 1
# pre_frame = None
while True:
_, frame = video.read()
if frame is None:
break
if pre_frame is None:
pre_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if count % 5 == 0:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frameDelta = cv2.absdiff(pre_frame, gray)
empty_image = np.asarray(frameDelta, np.uint8)
# cv2.imshow("diff", frameDelta)
# cv2.waitKey(1)
if np.sum(empty_image)/np.sum(gray) > 0.15:
save_path = "{}\\{:s}_{:>03d}.jpg".format(dst_folder, video_name, index)
# print(save_path)
if count % 10 == 0:
cv2.imwrite(save_path, frame)
index += 1
pre_frame = gray
count += 1
video.release()


def main():
video_folders_path = r"./videos"
dst_folder = r"./images"
# extract_frames_by_frame(video_folders_path, dst_folder)
extract_frames_by_frame_diff(video_folders_path,
dst_folder)


if __name__ == '__main__':
main()