Opencv3.4.0实现视频中的帧保存为图片功能
现在有一个收集人脸的需求,每一张照片只有一个人。我的解决办法是用收集录制一段视频,然后上传到PC上。在PC上使用OpenCV将图片中的每一帧保存为JPG图片。
以下是代码:
import time import cv2 if __name__ == '__main__': # 填写视频的绝对路径 vidcap = cv2.VideoCapture('/home/shushi/video/猎场.mp4') success, image = vidcap.read() start_time = time.time() print(start_time) while success: end_time = time.time() file_name = str(end_time).replace('.', '') # 每隔三秒截屏 if 3 == int(end_time - start_time): start_time = end_time # 保存JGP 的绝对路径 cv2.imwrite('/home/shushi/video/' + file_name + ".jpg", image) # save frame as JPEG file success, image = vidcap.read() if cv2.waitKey(10) == 27: # exit if Escape is hit break
将视频放到与Python文件同级目录下,然后运行程序,你就会得到视频帧对应的JPG图片了:
小编再为大家分享一段代码:OpenCV按视频帧进行截取,作者是Haku_yyf
#include <opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include <iostream> int main(int argc, char **argv) { //打开视频文件 cv::VideoCapture cap("E:\\New folder\\DSC_3543.MOV"); if (!cap.isOpened()) { std::cout << "不能打开视频文件" << std::endl; return -1; } //从3000ms开始播放视频 //cap.set(CV_CAP_PROP_POS_MSEC, 3000); //获取视频的帧速率 double fps = cap.get(cv::CAP_PROP_FPS); double width = cap.get(cv::CAP_PROP_FRAME_WIDTH); double height = cap.get(cv::CAP_PROP_FRAME_HEIGHT); //std::cout << fps << std::endl; //std::cout << width << std::endl; //std::cout << height << std::endl; cv::VideoWriter wrt("C:\\Users\\Administrator\\Desktop\\1.avi", CV_FOURCC('M', 'J', 'P', 'G'), fps, cv::Size(width, height)); int cout = 0; while (true) { cv::Mat frame; //从视频中读取一个帧 bool bSuccess = cap.read(frame); ++cout; if (!bSuccess) { std::cout << "不能从视频文件读取帧" << std::endl; break; } //在MyVideo窗口上显示当前帧 if (cout>=fps*1 && cout<=fps*56)//取视频1-56秒内容 { std::cout << "正在截取..."<<(int)(((cout-fps)/(fps*(56-1)))*100)<<"%" << std::endl; wrt << frame; } if (cout>fps*57) { std::cout << "ENd!!!" << std::endl; break; } } system("pause"); return 0; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)