视频提取图片,视频为MP4格式,图片为jpg格式
下面展示一些 内联代码片
。
直接上代码 python视频提取图片
# 全局变量
VIDEO_PATH = 'E:/SSS/xingche.mp4' # 视频地址
EXTRACT_FOLDER = 'E:/pythonProject1/pythonProject/tiqutu' # 存放帧图片的位置
EXTRACT_FREQUENCY = 10 # 帧提取频率
def extract_frames(video_path, dst_folder, index):
# 主操作
import cv2
video = cv2.VideoCapture()
if not video.open(video_path):
print("can not open the video")
exit(1)
count = 1
while True:
_, frame = video.read()
if frame is None:
break
if count % EXTRACT_FREQUENCY == 0:
save_path = "{}/{:>03d}.jpg".format(dst_folder, index)
cv2.imwrite(save_path, frame)
index += 1
count += 1
video.release()
# 打印出所提取帧的总数
print("Totally save {:d} pics".format(index-1))
def main():
import shutil
try:
shutil.rmtree(EXTRACT_FOLDER)# 递归删除之前存放帧图片的文件夹,并新建一个
except OSError:
pass
import os
os.mkdir(EXTRACT_FOLDER)
# 抽取帧图片,并保存到指定路径
extract_frames(VIDEO_PATH, EXTRACT_FOLDER, 1)
if __name__ == '__main__':
main()
参考https://cloud.tencent.com/developer/article/1348946
下面展示一些 内联代码片
。
pythhon 图片转是视频
import cv2
import os
fps = 10
path = './tiqutu'
filelist = os.listdir(path)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(filename='./t.mp4', fourcc=fourcc, fps=fps, frameSize=(1280, 720)) # 图片实际尺寸,不然生成的视频会打不开
#for i in range(0,150):
# p = i
# if os.path.exists('./tiqutu/'+str(p)+'.jpg'): #判断图片是否存在
for item in filelist:
if item.endswith('.jpg'):
#img = cv2.imread(filename='./tiqutu/'+str(p)+'.jpg')
print(item)
img = cv2.imread(filename='./tiqutu/'+item)
cv2.waitKey(100)
video_writer.write(img)
video_writer.release()
参考:https://blog.csdn.net/happyeee/article/details/105522478
注意:视频大小和图片大小相同
路径正确
python 重命名 名字=“文件头”+“数字”+“图片类型”
import os
import sys
def rename():
#path=input("请输入路径:")
#name=input("请输入开头名:")
#startNumber=input("请输入开始数:")
#fileType=input("请输入后缀名(如 .jpg、.txt等等):")
path = "F:/SSS/picture/calib"
name = ""
startNumber = "0"
fileType = ".png"
print("正在生成以"+name+startNumber+fileType+"迭代的文件名")
count=0
filelist=os.listdir(path)
for files in filelist:
Olddir=os.path.join(path,files)
if os.path.isdir(Olddir):
continue
Newdir=os.path.join(path,name+str(count+int(startNumber))+fileType)
os.rename(Olddir,Newdir)
count+=1
print("一共修改了"+str(count)+"个文件")
rename()
/ted block
var foo = 'bar';
C++视频转图片
// A code block
var foo = 'bar';
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace cv;
int main()
{
string mp4Path = "E:/SSS/xingche.mp4"; // 视频文件路径
string saveImgHead = "E:/SSS/du2/"; // 图片存取路径
long frameToStart = 1; // 设置起始帧
int frameToStop = 1500; // 设置结束帧
int intervalFrame = 100; // 设置间隔时间
//打开视频文件:其实就是建立一个VideoCapture结构
VideoCapture capture(mp4Path);
//检测是否正常打开:成功打开时,isOpened返回ture
if (!capture.isOpened())
cout << "fail toopen!" << endl;
//获取整个帧数CV_CAP_PROP_FRAME_COUNT
long totalFrameNumber = capture.get(7);
cout << "the vedio have: " << totalFrameNumber << " frames" << endl;
capture.set(1, frameToStart);
cout << "begin with " << frameToStart << " frame" << endl;
if (frameToStop < frameToStart)
{
cout << "frameToStop < frameToStart, the pragram end " << endl;
return -1;
}
else
{
cout << "the stop frame :" << frameToStop << "frame" << endl;
}
//获取帧率
double rate = capture.get(5);
cout << "frame rate:" << rate << endl;
//定义一个用来控制读取视频循环结束的变量
bool stop = false;
//承载每一帧的图像
Mat frame;
//namedWindow( "Extractedframe" );
//两帧间的间隔时间:
double delay = 1000 / rate;
//利用while循环读取帧
//currentFrame是在循环体中控制读取到指定的帧后循环结束的变量
long currentFrame = frameToStart;
while (!stop)
{
//读取下一帧
if (!capture.read(frame))
{
cout << "can not read the vedio" << endl;
return -1;
}
//cout << "正在读取第" << currentFrame << "帧" << endl;
//imshow( "Extractedframe", frame );
//此处为跳帧操作
if (currentFrame % intervalFrame == frameToStart) //此处为帧数间隔,修改这里就可以了
{
cout << "writing the frame: " << currentFrame << endl;
// stringstream str;
//str << "E:/初阳绘/du2/" << currentFrame << ".png"; /*图片存储位置*/
string saveImgPath = saveImgHead + format("%d", currentFrame)+".png";
//cout << str.str() << endl;
imwrite(saveImgPath, frame);
saveImgPath = "";
}
//waitKey(intdelay=0)当delay≤ 0时会永远等待;当delay>0时会等待delay毫秒
//当时间结束前没有按键按下时,返回值为-1;否则返回按键
int c = waitKey(delay);
//按下ESC或者到达指定的结束帧后退出读取视频
if ((char)c == 27 || currentFrame > frameToStop)
{
stop = true;
}
//按下按键后会停留在当前帧,等待下一次按键
if (c >= 0)
{
waitKey(0);
}
currentFrame += intervalFrame;
}
//关闭视频文件
capture.release();
waitKey(0);
return 0;
}
C++图片转视频 main()
#include
#include
#include"tvedio.h"
using namespace std;
using namespace cv;
int main()
{
string imgPath="E:/du2/*.png"; //图片路径
string vedioSavePath="E:/testl.mp4"; //视频保存路径
string vedioPath="E:/xingche.mp4"; //读取视频路径
double framerate=10.0; //帧率
img2Mp4(imgPath,vedioSavePath,framerate);
showVedio(vedioPath);
system("pause");
return 0;
cpp
#include"tvedio.h"
void img2Mp4(string imgPath,string vedioSavePath,double rate)
{
vector<string> imgPaths;
cv::glob(imgPath,imgPaths);
if(imgPaths.empty()){
cout<<"file path error"<<endl;
}
cv::Mat img = cv::imread(imgPaths[0],1);
cv::namedWindow("first_img");
cv::imshow("first_img",img);
waitKey(100);
int height=img.rows;
int width=img.cols;
//MatSize sizel=img::Size();
cv::VideoWriter track_writer;
track_writer.open (vedioSavePath, cv::VideoWriter::fourcc('M', 'P', '4', 'V'), rate, cv::Size(width, height));
//FLV1,MP4V,MJPG,
if(!track_writer.isOpened())
{
assert("track writer open failed!\n");
}
for (string filepath:imgPaths)
{
Mat src=imread(filepath,1);
//cv::resize(img, img, cv::Size(width, height));
imshow("first_img",src);
track_writer.write(src); // track_writer<
cout << "frame" << filepath << endl;
waitKey(100);
}
cout<<"vedio write done"<<endl;
}
void showVedio(string vedioPath)
{
VideoCapture capture;
Mat frame;
frame=capture.open(vedioPath);
if(!capture.isOpened()){
cout<<"vedio path error"<<endl;
}
namedWindow("output window",WINDOW_AUTOSIZE);
while(capture.read(frame)){ //capture.grap()
imshow("output window",frame); //capture>>frame;
waitKey(1);
if(waitKey(30)==27){
break;
}
}
waitKey(0);
capture.release();
}
头文件
#ifndef TVEDIO_H
#define TVEDIO_H
#include
#include
#include
using namespace std;
using namespace cv;
void img2Mp4(string imgPath,string vedioSavePath,double rate);
void showVedio(string vedioPath);
#endif // TVEDIO_H