Python生成视频边缘动画
实现技巧
1.导入依赖库
主要是安装相关的依赖库。本文实现的环境为:python 3.7。
# 导入所需要的库import cv2import numpy as np
2.读取视频
读取需要生成边缘动画的视频。也可以直接读取摄像头视频。
# 读取视频文件 视频文件路径videoCapture = cv2.VideoCapture("./input.mp4")# 通过摄像头的方式# videoCapture=cv2.VideoCapture(1)
3.动画视频参数设置
主要是对动画视频的基本参数进行初始化设置。
# 边缘动画视频参数设置fps = 30fps = videoCapture.get(cv2.CAP_PROP_FPS)size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))print(size)fourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter('./output1.mp4', fourcc, fps, size)
4.边缘检测与动画保存
主要是读取帧图像,进行边缘检测,并保存动画。
# 读取帧图像进行边缘检测与动画保存success, frame = videoCapture.read()i = 0fast = 1while success: i = i + 1 if (i % fast == 0): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200) print(frame.shape,edges.shape) cv2.imshow('Edge Detection', edges) out.write(cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)) k=cv2.waitKey(20) success, frame = videoCapture.read()
5.释放资源
完成工作后释放资源。
# 完成工作后释放资源videoCapture.release()out.release()cv2.destroyAllWindows()
完整源代码
# 导入所需要的库import cv2import numpy as np# 读取视频文件 视频文件路径videoCapture = cv2.VideoCapture("./input.mp4")# 通过摄像头的方式# videoCapture=cv2.VideoCapture(1)# 边缘动画视频参数设置fps = 30fps = videoCapture.get(cv2.CAP_PROP_FPS)size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))print(size)fourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter('./output1.mp4', fourcc, fps, size)# 读取帧图像进行边缘检测与动画保存success, frame = videoCapture.read()i = 0fast = 1while success: i = i + 1 if (i % fast == 0): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200) print(frame.shape,edges.shape) cv2.imshow('Edge Detection', edges) out.write(cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)) k=cv2.waitKey(20) success, frame = videoCapture.read()# 完成工作后释放资源videoCapture.release()out.release()cv2.destroyAllWindows()
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.