读取视频文件
- linux和window系统均可运行;
- C++脚本输入默认参数有两个:一是视频帧保存路径,二是输入视频路径;
- 可调用python实现多个视频流的读取
/*//use g++ to build
g++ read_video.cpp -o read -std=c++11 -lopencv_core -lopencv_imgproc -lopencv_highgui
*/
#include<iostream>
#include<string>
#ifdef _WIN32
#include <io.h> /* _access */
#include<direct.h> /* _mkdir */
#else
#include<unistd.h> /* access */
#include<sys/stat.h> /*mkdir*/
#endif
#include<opencv2/opencv.hpp>
using namespace cv;
// 读取视频流,保存为图片
int videoSplitFrame(std::string inputVideoPath, std::string saveDir) {
if (saveDir.back()!='/') {saveDir +="/"; }
cv::VideoCapture capture; //加载视频
capture.open(inputVideoPath);
// 总帧数
long totalFrameNumber = capture.get(cv::CAP_PROP_FRAME_COUNT);
//循环显示每一帧
if (!capture.isOpened()){
cout << "Could not open the input video: " << inputVideoPath << endl;
return -1;
}
//cv::namedWindow("video", cv::WINDOW_AUTOSIZE);
int i = 0;
while (true && i < totalFrameNumber)
{
cv::Mat frame;
capture >> frame; //读取当前帧
if (frame.empty()) {
continue;
}
string saveName = saveDir + to_string(i) + ".jpg";
cv::imwrite(saveName, frame);
cout << saveName << endl;
i++;
}
capture.release();
return 0;
}
int main(int argc, char* argv[])
{
if(argc !=3)
{
//[IN]<saveDir>:保存的路径
//[IN]<srcVideo.avi>:源视频路径
printf("Usage: ./read saveDir srcVideo.avi\n");
return -1;
}
std::string saveDir(argv[1]);
if (saveDir.back()!='/') {saveDir +="/"; }
#ifdef _WIN32
if(0 != _access(saveDir.c_str(),0))
{
_mkdir(saveDir.c_str());//create the folder
printf("dest folder had created. \n");
}
#else
if ( 0 != access(saveDir.c_str(),0))//if this is not a directory
{
mkdir(saveDir.c_str(),0755);//create the folder
printf("dest folder had created. \n");
}
#endif
std::string inputVideoPath(argv[2]);
videoSplitFrame(inputVideoPath,saveDir);
return 0;
}
- python脚本调用可执行文件实现对多个视频流的读取;
# -*- coding: utf-8 -*-
"""
直接使用python读取视频感觉会出现bug,暂时没查出什么原因
"""
import cv2
import os
def read_avi(video_Path, dst_dir):
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
cap = cv2.VideoCapture(video_Path)
#print cap.isOpened()
if cap.isOpened():
frame_count = 1
success = True
while(success):
success, frame = cap.read()
print 'Read a new frame: ', success
params = []
#params.append(cv.CV_IMWRITE_PXM_BINARY)
params.append(1)
# if frame_count%3==0:
# name = "video" + "_%d.png" % frame_count
# savePath = os.path.join("video_1",name)
# cv2.imwrite(savePath, frame, params)
name = "video" + "_%d.png" % frame_count
savePath = os.path.join(dst_dir,name)
cv2.imwrite(savePath, frame, params)
frame_count += 1
cap.release()
if __name__ == "__main__":
src_dir = r"./src_video";
save_dir = r"./dst_video"
for index, item in enumerate(os.listdir(src_dir)):
if item.endswith(".avi"):
abspath = os.path.join(src_dir,item)
dest_dir = os.path.join(save_dir,"ID_%s"%index)
#read_avi(abspath, dest_dir)
#调用生成的可执行文件read传入参数进行读取
os.system("./read %s %s "%(dest_dir,abspath))
print ("%d done\n"%index)
python读取内存流字节
- cv2.imdecode()函数从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像。
- cv2.imencode()函数是将图片格式转换(编码)成流数据,赋值到内存缓存中;主要用于图像数据格式的压缩,方便网络传输。
imdecode()使用 - 代码实现: 从网络读取图像数据并转换成图片格式:
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
url = 'http://www.pyimagesearch.com/wp-content/uploads/2015/01/google_logo.png'
resp = urllib.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('URL2Image',image)
cv2.waitKey()
将图片编码到缓存,并保存到本地:
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
img = cv2.imread('0122.jpg')
# '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
img_encode = cv2.imencode('.jpg', img)[1]
# imgg = cv2.imencode('.png', img)
data_encode = np.array(img_encode)
str_encode = data_encode.tostring()
# 缓存数据保存到本地
with open('img_encode.txt', 'w') as f:
f.write(str_encode)
f.flush
- imencode()+imdecode()使用, 图片编码保存到本地,读取本地文件解码恢复成图片格式:
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
img = cv2.imread('0122.jpg')
# '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
img_encode = cv2.imencode('.jpg', img)[1]
# imgg = cv2.imencode('.png', img)
data_encode = np.array(img_encode)
str_encode = data_encode.tostring()
# 缓存数据保存到本地,以txt格式保存
with open('img_encode.txt', 'w') as f:
f.write(str_encode)
f.flush
with open('img_encode.txt', 'r') as f:
str_encode = f.read()
nparr = np.fromstring(str_encode, np.uint8)
img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
cv2.imshow("img_decode", img_decode)
cv2.waitKey()
或
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
img = cv2.imread('0122.jpg')
# '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
img_encode = cv2.imencode('.jpg', img)[1]
# imgg = cv2.imencode('.png', img)
data_encode = np.array(img_encode)
str_encode = data_encode.tostring()
# 缓存数据保存到本地,以txt格式保存
with open('img_encode.txt', 'w') as f:
f.write(str_encode)
f.flush
with open('img_encode.txt', 'r') as f:
str_encode = f.read()
image = np.asarray(bytearray(str_encode), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('img_decode',image)
cv2.waitKey()