当前位置: 首页 > news >正文

4:OpenCV—保存图像

将图像和视频保存到文件

在许多现实世界的计算机视觉应用中,需要保留图像和视频以供将来参考。最常见的持久化方法是将图像或视频保存到文件中。因此,本教程准备解释如何使用 OpenCV C++将图像和视频保存到文件中。

将图像保存到文件

可以学习如何保存从文件加载的图像。同样,您可以保存从相机或任何其他方法拍摄的图像。


//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"#include <opencv2/opencv.hpp>
#include <iostream>using namespace cv;
using namespace std;int main(int argc, char** argv)
{// Read the image fileMat image = imread("C:/Users/Desktop/lena.png");// Check for failureif (image.empty()){cout << "Could not open or find the image" << endl;cin.get(); //wait for any key pressreturn -1;}// imwrite函数完成图像另存为bool isSuccess = imwrite("D:/lenaBack.jpg", image); //write the image to a file as JPEG //bool isSuccess = imwrite("D:/MyImage.png", image); //write the image to a file as PNGif (isSuccess == false){cout << "Failed to save the image" << endl;cin.get(); //wait for a key pressreturn -1;}cout << "Image is succusfully saved to a file" << endl;String windowName = "The Saved Image"; //Name of the windownamedWindow(windowName); // Create a windowimshow(windowName, image); // Show our image inside the created window.waitKey(0); // Wait for any keystroke in the windowdestroyWindow(windowName); //destroy the created windowreturn 0;
}

将上述代码片段复制并粘贴到 IDE 中并运行它。请注意,您必须将代码中的“C:/Users/Desktop/lena.png”替换为计算机中图像的有效位置。然后,您的图像应保存在指定位置。

解释

这些代码行从指定的文件中读取图像。如果无法加载图像,程序将退出。

上面的代码段将给定的图像写入指定的文件。如果无法将映像写入文件,程序将退出。


// Read the image file
Mat image = imread("D:/My OpenCV Website/fly-agaric.jpg");// Check for failure
if (image.empty())
{cout << "Could not open or find the image" << endl;cin.get(); //wait for any key pressreturn -1;
}bool isSuccess = imwrite("D:/MyImage.jpg", image); //write the image to a file as JPEG 
//bool isSuccess = imwrite("D:/MyImage.png", image); //write the image to a file as PNG
if (isSuccess == false)
{cout << "Failed to save the image" << endl;cin.get(); //wait for a key pressreturn -1;
}cout << "Image is succusfully saved to a file" << endl;

bool imwrite( const String& filename, InputArray img, const std::vector& params = std::vector())

此函数将给定的 img 对象写入指定的文件。成功后,此函数将返回 true,否则将返回 false。

  1. 文件名 - 输出图像的文件名。请注意,文件名的扩展名将用于确定图像格式。(例如 - 如果文件名是 MyImage.jpg,则将写入 JPEG 图像。如果文件名为 MyImage.png,则将写入 PNG 图像。始终支持 JPEG、JPG、BMP、PNG、TIFF 和 TIF 扩展名。支持其他映像文件类型,具体取决于您的平台和安装的编解码器。
  2. img - 要保存的图像对象。请注意,此图像对象应具有以下属性。
      • 图像对象的位深度应为 8 位有符号或 16 位无符号。
    • 图像的通道数应为 1 或 3。对于 3 通道图像对象,应存在 BGR 通道顺序。
  3. 如果图像对象的位深度或通道顺序与上述规范不同,则可以使用 Mat::convertTo 和 cv::cvtColor 函数来转换图像。

  4. 参数 - 这是一个可选参数。


tring windowName = "The Saved Image"; //Name of the window
namedWindow(windowName); // Create a window
imshow(windowName, image); // Show our image inside the created window.waitKey(0); // Wait for any keystroke in the windowdestroyWindow(windowName); //destroy the created window

这些代码行创建一个新窗口并在其中显示图像。程序将在窗口中显示图像,直到按下任何键。按下一个键后,窗口将被销毁。

将视频保存到文件

将上述代码片段复制并粘贴到 IDE 中并运行它。然后,您应该在创建的窗口中看到网络摄像头的输出。按下“Esc”键后,创建的窗口将被销毁,网络摄像头的视频输出将保存在给定位置。


//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"#include <opencv2/opencv.hpp>
#include <iostream>using namespace cv;
using namespace std;int main(int argc, char* argv[])
{// 打开电脑上的默认摄像头VideoCapture cap(0);// if not success, exit programif (cap.isOpened() == false){cout << "Cannot open the video camera" << endl;cin.get(); //wait for any key pressreturn -1;}// 获取贞的分辨率int frame_width = static_cast<int>(cap.get(CAP_PROP_FRAME_WIDTH)); //get the width of frames of the videoint frame_height = static_cast<int>(cap.get(CAP_PROP_FRAME_HEIGHT)); //get the height of frames of the video// 创建采集图像的大小Size frame_size(frame_width, frame_height);// 设置保存图像贞率int frames_per_second = 24;//创建VideoWriter对象,并指定存储文件名称及使用编码器格式,帧率,大小VideoWriter oVideoWriter("D:/MyVideo.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'),frames_per_second, frame_size, true);//If the VideoWriter object is not initialized successfully, exit the programif (oVideoWriter.isOpened() == false){cout << "Cannot save the video to a file" << endl;cin.get(); //wait for any key pressreturn -1;}string window_name = "My Camera Feed";namedWindow(window_name); //create a window called "My Camera Feed"// 循环采集图像while (true){// 从相机中读取采集的新的贞Mat frame;bool isSuccess = cap.read(frame);//Breaking the while loop if frames cannot be read from the cameraif (isSuccess == false){cout << "Video camera is disconnected" << endl;cin.get(); //Wait for any key pressbreak;}// 把采集当前贞写入到文件中oVideoWriter.write(frame);// 把当前贞显示到创建的窗口中imshow(window_name, frame);// 按下ESC键 停止采集if (waitKey(10) == 27){cout << "Esc key is pressed by the user. Stopping the video" << endl;break;}}// 必须释放使用VideoWriter的对象oVideoWriter.release();return 0;
}

此代码段获取网络摄像头视频帧的宽度和高度。使用获得的信息,构造并初始化视频编写器对象。如果初始化失败,程序将退出。


/Open the default video camera
VideoCapture cap(0);// if not success, exit program
if (cap.isOpened() == false)
{cout << "Cannot open the video camera" << endl;cin.get(); //wait for any key pressreturn -1;
}

int frame_width = static_cast<int>(cap.get(CAP_PROP_FRAME_WIDTH)); //get the width of frames of the video
int frame_height = static_cast<int>(cap.get(CAP_PROP_FRAME_HEIGHT)); //get the height of frames of the videoSize frame_size(frame_width, frame_height);
int frames_per_second = 10;//Create and initialize the VideoWriter object 
VideoWriter oVideoWriter("D:/MyVideo.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), frames_per_second, frame_size, true); //If the VideoWriter object is not initialized successfully, exit the program                                                    
if (oVideoWriter.isOpened() == false) 
{cout << "Cannot save the video to a file" << endl;cin.get(); //wait for any key pressreturn -1;
}

VideoWriter**(const String&filename, int fourcc, double fps, Size frameSize, bool isColor = true)**
这是 VideoWriter 对象的可用重载构造函数之一。它构造并初始化视频编写器对象,以便将视频帧写入给定文件。

  1. 文件名 - 要写入视频帧的文件的名称。

  2. fourcc - 用于压缩视频的编解码器的 4 个字符的代码。完整的代码列表可以在此页面中找到。但此页面中列出的大多数编解码器可能无法在您的计算机中使用。这些是一些可能适合您的流行编解码器。

    • VideoWriter::fourcc(‘P’, ‘I’, ‘M’, ‘1’) for MPEG-1
  • VideoWriter::fourcc(‘M’, ‘J’, ‘P’, ‘G’) for Motion JPEG
  • VideoWriter::fourcc(‘M’, ‘P’, ‘4’, ‘2’) for MPEG-4 变体 Microsoft
  1. fps - 写入视频流的每秒帧数。

  2. 帧大小 - 写入此视频流的视频帧的大小

  3. isColor - 始终传递此参数


while (true)
{Mat frame;bool isSuccess = cap.read(frame); // read a new frame from the video camera //Breaking the while loop if frames cannot be read from the cameraif (isSuccess == false){cout << "Video camera is disconnected" << endl;cin.get(); //Wait for any key pressbreak;}/*Make changes to the frame as necessarye.g.  1. Change brightness/contrast of the image2. Smooth/Blur image3. Crop the image4. Rotate the image5. Draw shapes on the image*///write the video frame to the fileoVideoWriter.write(frame); //show the frame in the created windowimshow(window_name, frame);//Wait for for 10 milliseconds until any key is pressed.  //If the 'Esc' key is pressed, break the while loop.//If any other key is pressed, continue the loop //If any key is not pressed within 10 milliseconds, continue the loop if (waitKey(10) == 27){cout << "Esc key is pressed by the user. Stopping the video" << endl;break;}
}

在上述 while 循环的每次迭代中,程序执行以下任务。

  • 从相机读取帧。
  • 将帧写入文件。
  • 在窗口中显示框架。

如果按下 Esc 键或程序无法从相机读取帧,while 循环将中断。

void write(const Mat&image)
将帧写入文件。帧的大小应与您在初始化视频编写器对象期间指定的大小相同。


//Flush and close the video file
oVideoWriter.release();

此功能刷新并关闭视频文件。此函数也在析构函数 VideoWriter 对象中执行。

http://www.dtcms.com/a/198227.html

相关文章:

  • Spring AI Alibaba集成阿里云百炼大模型应用
  • 05 部署Nginx反向代理
  • 【Linux高级全栈开发】2.1.2 事件驱动reactor的原理与实现
  • 【运营商查询】批量手机号码归属地和手机运营商高速查询分类,按省份城市,按运营商移动联通电信快速分类导出Excel表格,基于WPF的实现方案
  • ChatGPT:OpenAI Codex—一款基于云的软件工程 AI 代理,赋能 ChatGPT,革新软件开发模式
  • RISC-V 开发板 MUSE Pi Pro V2D图像加速器测试,踩坑介绍
  • 抖音视频怎么去掉抖音号水印
  • uni-app学习笔记七-vue3事件处理
  • esp32课设记录(一)按键的短按、长按与双击
  • 区间带边权并查集,XY4060泄露的测试点
  • pycharm连接github(详细步骤)
  • 如何利用 Java 爬虫获得某书笔记详情:实战指南
  • 面向GIS的Android studio移动开发(二)--在地图上绘制电子围栏
  • Spring AI Alibaba集成阿里云百炼大模型
  • 【已经解决诸多问题】Mamba安装
  • 延时双删-争议与我的思路-001
  • Neo4j数据库
  • 有哪些GIF图片转换的开源工具
  • 07 负载均衡
  • Linux的MySQL头文件和找不到头文件问题解决
  • windows多版本Python共存(大合集)
  • 方案精读:104页DeepSeek金融银行核算流程场景部署建设方案【附全文阅读】
  • LeetCode 155. 最小栈:Java 双栈解法详解
  • LWIP的Socket接口
  • SmartETL函数式组件的设计与应用
  • 【时时三省】(C语言基础)数组习题
  • 前端三剑客之HTML
  • LLM大语言模型系列1-token
  • 【AWS入门】Amazon SageMaker简介
  • [原创工具] 小说写作软件