Opencv将目录下的图片存储为视频

文章目录

源码

/*************************************************************************
    > File Name: main.cpp
    > Author: 
    > Mail: 1@163.com 
    > Created Time: 2022年06月17日 星期五 14时00分37秒
    > g++ main.cpp -o main `pkg-config --cflags --libs opencv`
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <libgen.h>

#include <opencv2/opencv.hpp>  
#include <iostream>
#include <unistd.h>

using namespace cv;  
using namespace std;

vector <string> relativePath;
vector <string> fileName;


/******************************************************************************
 *
 * 功能:
 *		获得 (文件名.后缀) 和 (文件名) 和 (文件后缀),Windows和Linux通用!
 *
 * 参数:
 *		_filePaht:			C语言字符指针,文件路径字符串
 *		_fullFileName:		C++字符串引用,获得[(文件名.后缀) 或 (文件名)]返回
 *		_fileName:			C++字符串引用,获得(文件名.后缀)返回
 *		_fileSuffix:		C++字符串引用,获得(后缀)返回
 *		_dot:				true,后缀带点(.txt);false,后缀不带点(txt);默认值为true
 *
 * 返回值:
 *		有后缀返回"."的索引;没有后缀则返回-1
 *
 ******************************************************************************/
int get_fileName_fileSuffix(const char *_filePaht, std::string &_fullFileName, std::string &_fileName, std::string &_fileSuffix, bool _dot = true) {

	// 合法性检查
	if (!_filePaht) return -1;
	std::string str = _filePaht;
	if (str.empty()) return -1;

	// .txt    的情况
	if (str.at(0) == '.') return -1;
	// file.   的情况
	if (str.at(str.size() - 1) == '.') return -1;



	char c = '\0';

	// 区分此函数是在Windows环境调用还是Linux环境调用
#if defined (_WIN64) || defined (WIN32) || defined (_WIN32)
	//printf("---Windows---\n");
	c = '\\';
#else
	//printf("---Linux---\n");
	c = '\/';
#endif

	// 去除字符串中的路径,剩下文件名
	std::string filename = strrchr(_filePaht, c) == NULL ? "" : strrchr(_filePaht, c) + 1;
	if (filename == "") {
		/* 说明字符串是file.txt或者file形式 */
		filename = _filePaht;

	} else {
		/* 说名字符串是C:\\abc\\file.txt或者C:\\abc\\file形式 */
	}

	// 找到 . 的位置
	size_t _size = filename.rfind(".");
	// 获得文件名,不包含后缀
	_fileName = filename.substr(0, _size);

	// 获得文件后缀
	std::string strsuffix = "";
	if (_size != -1) {	// 不等于-1说明有后缀 file.txt形式

		// true后缀带点,false后缀不带点
		if (_dot == true) {
			strsuffix = filename.substr(_size);     // 文件后缀 .txt

		} else {
			strsuffix = filename.substr(_size + 1);     // 文件后缀 txt
		}
	}
	// 后缀
	_fileSuffix = strsuffix;

	// 获得文件名.后缀(file.txt | file)
	_fullFileName = filename;

	return _size;
}

int readFileList(char *basePath)
{
    DIR *dir;
    struct dirent *ptr;
    char base[1000];

    if ((dir=opendir(basePath)) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8){    ///file
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
            // 文件名
            string s1 = ptr->d_name;
            fileName.push_back(s1);
            // 全路径
            string s = basePath;
            s = s + "/";
            s = s + +ptr->d_name;
            relativePath.push_back(s);
            
            std::string fullFilename, filename, fileSuffix;
	          int r = get_fileName_fileSuffix(s1.c_str(), fullFilename, filename, fileSuffix, true);
	         
        }else if(ptr->d_type == 10){    ///link file
            printf("d_name:%s/%s\n",basePath,ptr->d_name);
        }else if(ptr->d_type == 4)    ///dir
        {
            memset(base,'\0',sizeof(base));
            strcpy(base,basePath);
            strcat(base,"/");
            strcat(base,ptr->d_name);
            readFileList(base);
        }
    }
    closedir(dir);
    return 1;
}

int main(int argc, const char *argv[])
{
    DIR *dir;
    #if 0
    char basePath[1000];
    memset(basePath,'\0',sizeof(basePath));
    // 得到当前的绝对路径
    getcwd(basePath, 999);
    #else
    char *basePath = (char *)argv[1];
    #endif
    
    // 获取目录下的全部文件
    //readFileList(basePath);
    
    
  VideoWriter w1;
  int encode_type = VideoWriter::fourcc('M', 'J', 'P', 'G'); 
 	bool isColor = true; 
	double fps = 25.0;
	string filename = "test_save.avi";
	w1.open(filename, encode_type, fps, cv::Size(1280, 720), isColor);  
 
	if (!w1.isOpened()) {     
		cout << "视频打开失败" << endl;
	}


    int id = 0;
    int maxNum = 300;
    for (int i = 0; i<maxNum; i++)
    {
      string filePathName = argv[1] ;
      filePathName = filePathName+ "/" + to_string(i) + ".png";

      if (! access(filePathName.c_str() ,0) )
      {
          Mat img;
          img = imread(filePathName.c_str());  
          if (img.empty())  //判断图像文件是否存在
          {
            cout << "读取失败" << endl;
            if (w1.isOpened())
              w1.release();
            return -1;
          }
          w1.write(img);
          imshow("test", img);  //显示图像
          waitKey(0); 
      }
    
    }
    return 0;
}

编译

 g++ img2video.cpp -o img2video `pkg-config --cflags --libs opencv`

运行

./img2video  ../results
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用 OpenCV 将多张图片编码为视频可以分为以下几个步骤: 1. 读取图片并将它们保存到一个列表中; 2. 设置视频编码参数; 3. 创建一个视频写入对象; 4. 将每张图片写入视频; 5. 释放视频写入对象和销毁所有窗口。 下面是示例代码: ```python import cv2 import os # 图片文件夹路径和视频保存路径 img_folder_path = 'path/to/images/folder' video_save_path = 'path/to/video.avi' # 获取图片文件名列表 img_names = os.listdir(img_folder_path) # 将图片文件名按数字排序 img_names.sort(key=lambda x: int(x.split('.')[0])) # 获取第一张图片的尺寸 img = cv2.imread(os.path.join(img_folder_path, img_names[0])) height, width, channels = img.shape # 设置视频编码参数 fourcc = cv2.VideoWriter_fourcc(*'AVC1') fps = 30.0 frame_size = (width, height) # 创建视频写入对象 video_writer = cv2.VideoWriter(video_save_path, fourcc, fps, frame_size) # 将每张图片写入视频 for img_name in img_names: img_path = os.path.join(img_folder_path, img_name) img = cv2.imread(img_path) video_writer.write(img) # 释放视频写入对象和销毁所有窗口 video_writer.release() cv2.destroyAllWindows() ``` 上述代码中,`img_folder_path` 是存储图片的文件夹路径,`video_save_path` 是保存视频的文件路径。首先通过 `os.listdir()` 方法获取该文件夹下所有图片的文件名列表,并将它们按数字排序。然后获取第一张图片的尺寸,并设置视频编码参数,包括视频编码格式、帧率和帧尺寸。接着创建一个视频写入对象,并通过 `write()` 方法将每张图片写入视频。最后释放视频写入对象和销毁所有窗口。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听雨听风眠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值