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。
- 文件名 - 输出图像的文件名。请注意,文件名的扩展名将用于确定图像格式。(例如 - 如果文件名是 MyImage.jpg,则将写入 JPEG 图像。如果文件名为 MyImage.png,则将写入 PNG 图像。始终支持 JPEG、JPG、BMP、PNG、TIFF 和 TIF 扩展名。支持其他映像文件类型,具体取决于您的平台和安装的编解码器。
- img - 要保存的图像对象。请注意,此图像对象应具有以下属性。
- 图像对象的位深度应为 8 位有符号或 16 位无符号。
- 图像的通道数应为 1 或 3。对于 3 通道图像对象,应存在 BGR 通道顺序。
如果图像对象的位深度或通道顺序与上述规范不同,则可以使用 Mat::convertTo 和 cv::cvtColor 函数来转换图像。
参数 - 这是一个可选参数。
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 对象的可用重载构造函数之一。它构造并初始化视频编写器对象,以便将视频帧写入给定文件。
文件名 - 要写入视频帧的文件的名称。
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
fps - 写入视频流的每秒帧数。
帧大小 - 写入此视频流的视频帧的大小
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 对象中执行。