闲着没事想要自己用Python给视频添加一些特效,有时候就需要提取每一帧,或是提取一部分图像进行操作。
没有cv2的话,命令行装一个cv2
pip install cv2
什么,没装python?
** 进入正题 **
先把要用的库准备好
import cv2
import os.path as op
import os
提取图像关os什么事?
当然是要对路径什么的进行操作
video = cv2.VideoCapture(video_path)
-
然后先读取一张(success 为成功与否,frame为提取的图像数据)
success, frame = video.read()
-
然后开始循环(先存取上一次读取的图像,然后接着再读一张)
img_id = 0
while success:
img_outpath = f'...../..../../{img_id}.png'
img_id += 1
cv2.imwrite(img_outpath, frame)
success, frame = video.read()
img_id = 0
while success:
img_outpath = f'...../..../../{img_id}.png'
if not img_id%5:
img_id += 1
cv2.imwrite(img_outpath, frame)
success, frame = video.read()
稍微整理整理,就可以弄成一个小函数,使用起来调用一波就好
def split_video(video_path, out_path):
if not op.exists(out_path):
os.mkdir(out_path)
vc = cv2.VideoCapture(video_path)
success, frame = vc.read()
i = 0
while success:
i += 1
img_path = f'{out_path}\\{i}.jpg'
cv2.imwrite(img_path, frame)
if success:
print(f'\r Split image{i}', end='')
success, frame = vc.read()
提取了图像,就可以进行一系列操作了,比如:
又比如AI换脸
无意冒犯,只是顺手搜的素材,没有恶意,只是作技术交流。