4:OpenCV—保存图像

news2025/5/19 13:53:54

将图像和视频保存到文件

在许多现实世界的计算机视觉应用中,需要保留图像和视频以供将来参考。最常见的持久化方法是将图像或视频保存到文件中。因此,本教程准备解释如何使用 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 file
	Mat image = imread("C:/Users/Desktop/lena.png");

	// Check for failure
	if (image.empty())
	{
		cout << "Could not open or find the image" << endl;
		cin.get(); //wait for any key press
		return -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 PNG
	if (isSuccess == false)
	{
		cout << "Failed to save the image" << endl;
		cin.get(); //wait for a key press
		return -1;
	}

	cout << "Image is succusfully saved to a file" << endl;

	String 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 window

	destroyWindow(windowName); //destroy the created window

	return 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 press
 return -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 press
 return -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 window

destroyWindow(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 program
    if (cap.isOpened() == false)
    {
        cout << "Cannot open the video camera" << endl;
        cin.get(); //wait for any key press
        return -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 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 program
    if (oVideoWriter.isOpened() == false)
    {
        cout << "Cannot save the video to a file" << endl;
        cin.get(); //wait for any key press
        return -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 camera
        if (isSuccess == false)
        {
            cout << "Video camera is disconnected" << endl;
            cin.get(); //Wait for any key press
            break;
        }

        // 把采集当前贞写入到文件中
        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 press
    return -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 video

Size 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 press
    return -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 camera
    if (isSuccess == false)
    {
        cout << "Video camera is disconnected" << endl;
        cin.get(); //Wait for any key press
        break;
    }

    /*
    Make changes to the frame as necessary
    e.g.  
     1. Change brightness/contrast of the image
     2. Smooth/Blur image
     3. Crop the image
     4. Rotate the image
     5. Draw shapes on the image
    */

    //write the video frame to the file
    oVideoWriter.write(frame); 

    //show the frame in the created window
    imshow(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.coloradmin.cn/o/2379324.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Selenium-Java版(css表达式)

css表达式 前言 根据 tag名、id、class 选择元素 tag名 #id .class 选择子元素和后代元素 定义 语法 根据属性选择 验证CSS Selector 组选择 按次序选择子节点 父元素的第n个子节点 父元素的倒数第n个子节点 父元素的第几个某类型的子节点 父元素的…

产品更新丨谷云科技 iPaaS 集成平台 V7.5 版本发布

五月&#xff0c;谷云科技 iPaaS 集成平台保持月度更新&#xff0c; V7.5 版本于近日正式发布。我们一起来看看新版本有哪些升级和优化。 核心新增功能&#xff1a;深化API治理&#xff0c;释放连接价值 API网关&#xff1a;全链路可控&#xff0c;精准管控业务状态 业务状态…

深度学习让鱼与熊掌兼得

通常,一个大的复杂的模型的loss会低,但是拟合方面不够,小的模型在拟合方面更好,但是loss高,我们可以通过深度学习来得到一个有着低loss的小模型 我们之前学过,peacewise linear可以用常数加上一堆这个阶梯型函数得到,然后因为peacewise linear可以逼近任何function,所以理论上…

TDuckX 2.6 正式发布|API 能力开放,核心表单逻辑重构,多项实用功能上线。

大家好&#xff0c;TDuckX 2.6 已正式发布。 本次更新以可集成性提升、数据处理能力增强和交互体验优化为核心&#xff0c;新增了包括 新增OpenAPI 模块、表单数据批量修改、字段导出分列 等多个面向开发者和实际业务落地场景的功能。 我们也重构了部分底层逻辑模块&#xff…

JAVA EE(进阶)_进阶的开端

别放弃浸透泪水的昨天&#xff0c;晨光已为明天掀开新篇 ——陳長生. ❀主页&#xff1a;陳長生.-CSDN博客❀ &#x1f4d5;上一篇&#xff1a;JAVA EE_HTTP-CSDN博客 1.什么是Java EE Java EE&#xff08;Java Pla…

ArcGIS Pro调用多期历史影像

一、访问World Imagery Wayback&#xff0c;基本在我国范围 如下图&#xff1a; 二、 放大到您感兴趣的区域 三、 查看影像版本信息 点击第二步的按钮后&#xff0c;便可跳转至World Imagery (Wayback 2025-04-24)的相关信息。 四 、点击上图影像版本信息&#xff0c;页面跳转…

组态王|组态王中如何添加西门子1200设备

哈喽,你好啊,我是雷工! 最近使用组态王采集设备数据,设备的控制器为西门子的1214CPU, 这里边实施边记录,以下为在组态王中添加西门子1200PLC的笔记。 1、新建 在组态王工程浏览器中选择【设备】→点击【新建】。 2、选择设备 和设备建立通讯要通过对应的设备驱动。 在…

6.2.2邻接表法-图的存储

知识总览&#xff1a; 为什么要用邻接表 因为邻接矩阵的空间复杂度高(O(n))&#xff0c;且不适合边少的稀疏图&#xff0c;所以有了邻接表 用代码表示顶点、图 声明顶点图信息 声明顶点用一维数组存储各个顶点的信息&#xff0c;一维数组字段包括2个&#xff0c;每个顶点的…

C++23 放宽范围适配器以允许仅移动类型(P2494R2)

文章目录 引言背景与动机提案内容与实现细节提案 P2494R2实现细节编译器支持 对开发者的影响提高灵活性简化代码向后兼容性 示例代码总结 引言 C23 标准中引入了许多重要的改进&#xff0c;其中一项值得关注的特性是放宽范围适配器&#xff08;range adaptors&#xff09;以允…

【技海登峰】Kafka漫谈系列(十一)SpringBoot整合Kafka之消费者Consumer

【技海登峰】Kafka漫谈系列(十一)SpringBoot整合Kafka之消费者Consumer spring-kafka官方文档: https://docs.spring.io/spring-kafka/docs/2.8.10/reference/pdf/spring-kafka-reference.pdf KafkaTemplate API: https://docs.spring.io/spring-kafka/api/org/springframe…

WebRTC技术下的EasyRTC音视频实时通话SDK,助力车载通信打造安全高效的智能出行体验

一、方案背景​ 随着智能交通与车联网技术的飞速发展&#xff0c;车载通信在提升行车安全、优化驾驶体验以及实现智能交通管理等方面发挥着越来越重要的作用。传统的车载通信方式在实时性、稳定性以及多媒体交互能力上存在一定局限&#xff0c;难以满足现代车载场景日益复杂的…

数据科学和机器学习的“看家兵器”——pandas模块 之二

目录 pandas 模块介绍 4.2 pandas 数据读取 4.2.1 课程目标 4.2.2 读取 Excel 文件中的数据 (一)读取某个工作表中的数据 (二)读取指定数据列的标签内容 (三)读取指定数据行的标签内容 (四)读取指定行或者列 4.2.3、读取 CSV 文件数据 4.2.4、课程总结回顾 4.2.5、课后…

MySQL--day2--基本的select语句

&#xff08;以下内容全部来自上述课程&#xff09; SQL概述 结构化查询语句 1. SQL分类 DDL&#xff1a;数据定义&#xff08;definition&#xff09;语言&#xff1a;create、drop、alter… DML&#xff1a;数据操作&#xff08;manipulation&#xff09;语言&#xff…

自动化:批量文件重命名

自动化&#xff1a;批量文件重命名 1、前言 2、效果图 3、源码 一、前言 今天来分享一款好玩的自动化脚&#xff1a;批量文件重命名 有时候呢&#xff0c;你的文件被下载下来文件名都是乱七八糟毫无规律&#xff0c;但是当时你下载的时候没办法重名或者你又不想另存为重新重…

学习!FastAPI

目录 FastAPI简介快速开始安装FastApiFastAPI CLI自动化文档 Reqeust路径参数Enum 类用于路径参数路径参数和数值校验 查询参数查询参数和字符串校验 请求体多个请求体参数嵌入单个请求体参数 CookieHeader表单文件直接使用请求 ResponseResponse Model多个关联模型 响应状态码…

【第三十六周】LoRA 微调方法

LoRA 摘要Abstract文章信息引言方法LoRA的原理LoRA在Transformer中的应用补充其他细节 实验与分析LoRA的使用论文实验结果分析 总结 摘要 本篇博客介绍了LoRA&#xff08;Low-Rank Adaptation&#xff09;&#xff0c;这是一种面向大规模预训练语言模型的参数高效微调方法&…

Redis 数据类型与操作完全指南

Redis 是一个开源的、内存中的数据结构存储系统&#xff0c;它可以用作数据库、缓存和消息中间件。与传统的关系型数据库不同&#xff0c;Redis 提供了丰富的数据类型和灵活的操作方式&#xff0c;这使得它能够高效地解决各种不同场景下的数据存储和处理问题。本文将全面介绍 R…

Digi XBee XR 系列介绍

Digi 延续了 20 多年来亚 GHz 射频模块的传统&#xff0c;推出了 Digi XBee XR 系列远距离模块&#xff0c;包括 Digi XBee XR 900 - 已通过多个地区的预先认证 - 以及 Digi XBee XR 868 - 已通过欧洲地区应用的预先认证。 这些先进的射频模块专为远距离抗干扰无线通信而设计。…

【方法论】金字塔原理概述:写作逻辑的底层架构与实践法则

文章目录 一、为何采用金字塔结构&#xff1a;对抗认知局限的思维框架1、 梳理逻辑&#xff0c;抽象归纳2、自上而下&#xff0c;结论居首3、 结论先行之必要 三、金字塔结构1、纵向逻辑&#xff1a;上层思想必须是下层思想的概括提炼2、横向逻辑&#xff1a;每组思想需属于同一…

BERT 核心技术全解析:Transformer 双向编码与掩码语言建模的底层逻辑

一、引言&#xff1a;从 BERT 到生成式 AI 的进化之路 科学的突破从来不是孤立的奇迹&#xff0c;而是人类知识长河中无数基石的累积。 当我们惊叹于 ChatGPT、Google Bard 等大型语言模型&#xff08;LLM&#xff09;在生成式 AI 领域的惊人表现时&#xff0c;不能不回溯到 20…