Day 11 C++ 读取图像文件

Day 11 C++ 读取图像文件

    • 1. 在头文件 ImgIOInterface.h 中定义如下函数
    • 2. 在cpp文件 ImgIOInterface.cpp 实现头文件中函数
    • 3. 在main函数中调用

1. 在头文件 ImgIOInterface.h 中定义如下函数

#pragma once
#include 
#include 

using namespace std;

/// 
/// 从路径读取图像文件
/// 
/// img path
/// 
pair<char*, int> imgread(std::string path);

/// 
/// 保存图像文件
/// 
/// 
/// 
/// 
void imgsave(char* buffer, int buflength, string savepath);

2. 在cpp文件 ImgIOInterface.cpp 实现头文件中函数

#include "ImgIOInterface.h"
#include 

pair<char*, int> imgread(std::string path)
{
	ifstream is(path, ifstream::in | ios::binary);  // 读取图像
	is.seekg(0, is.end);
	int length = is.tellg();  // 计算图像长度
	is.seekg(0, is.beg);
	char* buffer = new char[length];  // 创建内存缓存区
	is.read(buffer, length);  // 读取图片
	return { buffer, length };   // 由于后面保存图像文件需要用到length,所以将其return
}

void imgsave(char* buffer, int buflength, string savepath)
{
	std::string  strFile;
	for (size_t i = 0; i < buflength; i++)
	{
		strFile += buffer[i];
	}
	ofstream fout(savepath, ios::binary);
	if (fout)
	{
		fout.write(strFile.c_str(), strFile.size());
		fout.close();
	}
}


3. 在main函数中调用

#include 
#include    // 对应头文件
#include 
#include 
#include 
#include 
#include "ImgIOInterface.h"

using namespace std;
using namespace cv;

int main()
{
    /*
	* C++ 读取图像文件
    */
	auto startTime = std::chrono::system_clock::now();

	pair<char*, int> buffer = imgread("4.jpg");

	auto endTime = std::chrono::system_clock::now();

	std::cout << "time:" << std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count() << std::endl;

	imgsave(buffer.first, buffer.second, "save.jpg");

	delete[] buffer.first;
	buffer.first = NULL;

	return 0;

}

运行结果:1920*1080的彩色图像,在Release模式下的运行时间是218us.
Day 11 C++ 读取图像文件_第1张图片

你可能感兴趣的:(OpenCV,计算机视觉,c++,开发语言)