递归遍历文件夹中的图片(c++17)

#include<filesystem>
#include<vector>

namespace fs = std::filesystem;

void traverseDirectory(const std::string& directoryPath, std::vector<std::string>& datapath)
{
    for (const auto& entry : fs::directory_iterator(directoryPath))
    {
        if (fs::is_directory(entry))
        {
            // 递归遍历子目录
            traverseDirectory(entry.path().string(), datapath);
        }
        else if (fs::is_regular_file(entry))
        {
            std::string filePath = entry.path().string();
            datapath.emplace_back(filePath);


        }
    }
}

深度学习等比resize和反向resize

#include <opencv2/opencv.hpp>

cv::Mat restoreImage(const cv::Mat& image, const cv::Size& originalSize) {
    // 获取图像的原始宽度和高度
    int width = originalSize.width;
    int height = originalSize.height;

    // 计算缩放比例
    double scale = std::min((double)image.cols / width, (double)image.rows / height);

    // 计算缩放后的宽度和高度
    int newWidth = static_cast<int>(width * scale);
    int newHeight = static_cast<int>(height * scale);

    // 计算填充位置
    int xOffset = (image.cols - newWidth) / 2;
    int yOffset = (image.rows - newHeight) / 2;

    // 将调整后的图像放置在原始图像中心
    cv::Mat restoredImage = image(cv::Rect(xOffset, yOffset, newWidth, newHeight)).clone();

    // 调整图像大小
    cv::resize(restoredImage, restoredImage, originalSize, 0, 0, cv::INTER_LANCZOS4);

    return restoredImage;
}

cv::Mat resizeImage(const cv::Mat& image, const cv::Size& targetSize, const cv::Scalar& fillValue) {
    // 获取图像的原始宽度和高度
    int width = image.cols;
    int height = image.rows;

    // 计算缩放比例
    double scale = std::min((double)targetSize.width / width, (double)targetSize.height / height);

    // 计算缩放后的宽度和高度
    int newWidth = static_cast<int>(width * scale);
    int newHeight = static_cast<int>(height * scale);

    // 调整图像大小
    cv::Mat resizedImage;
    cv::resize(image, resizedImage, cv::Size(newWidth, newHeight), 0, 0, cv::INTER_LANCZOS4);

    // 创建目标大小的空白图像,并填充特定值
    cv::Mat paddedImage(targetSize, image.type(), fillValue);

    // 计算填充位置
    int xOffset = (targetSize.width - newWidth) / 2;
    int yOffset = (targetSize.height - newHeight) / 2;

    // 将调整后的图像放置在填充图像中心
    resizedImage.copyTo(paddedImage(cv::Rect(xOffset, yOffset, newWidth, newHeight)));

    return paddedImage;
}

c++性能测试精确到秒、毫秒、纳秒 

#include <iostream>
#include <string>
#include <chrono>

void Run()
{
	for (int i = 0; i < 1000000000; ++i)
	{

	}

}

int main()
{
	auto beforeTime = std::chrono::steady_clock::now();
	
	Run();

	auto afterTime = std::chrono::steady_clock::now();

	std::cout << "总耗时:" << std::endl;
	//秒
	double duration_second = std::chrono::duration<double>(afterTime - beforeTime).count();
	std::cout << duration_second << "秒" << std::endl;

	//毫秒级
	double duration_millsecond = std::chrono::duration<double, std::milli>(afterTime - beforeTime).count();
	std::cout << duration_millsecond << "毫秒" << std::endl;

	//微妙级
	double duration_microsecond = std::chrono::duration<double, std::micro>(afterTime - beforeTime).count();
	std::cout << duration_microsecond << "微秒" << std::endl;

	//纳秒级
	double duration_nanosecond = std::chrono::duration<double, std::nano>(afterTime - beforeTime).count();
	std::cout << duration_nanosecond << "纳秒" << std::endl;

	getchar();
	return 0;
}


读取文件夹的所有图片

#include <iostream>
#include <string>
#include <bitset>
#include <io.h>
#include <fstream>
#include <windows.h>
#include <iomanip>
#include <chrono>
#include <vector>


using namespace std;
void getFiles(string path, vector<string>& files)
{
	//文件句柄
	intptr_t hFile = 0;
	//文件信息
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之
			//如果不是,加入列表
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

c++向文本文件一行行写入数据

\r\n换行

fp=fopen("aa.txt","w+");
fwrite("a\r\n",1,3,fp);
fwrite("a\r\n",1,3,fp);
fclose(fp);

OpenCV:glob遍历文件夹下的所有图片

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
    //要绝对路径
    string path = "D:\\data\\*.bmp";
    cout << path << endl;
    vector<Mat> images;
    // 必须cv的String
    vector<String> fn;
    glob(path, fn, false);
    size_t count = fn.size();
    cout << count << endl;
    for (int i = 0; i < count; i++)
    {
        images.push_back(imread(fn[i]));
        imshow("pic", images[i]);
        waitKey(10);
    }
    return 0;
}

//用void glob(String pattern, std::vector& result, bool recursive = false);
//当recursive为false时,仅仅遍历指定文件夹内符合模式的文件,当recursive为true时,会同时遍历指定文件夹的子文件夹
 

由于glob遍历图像名称不是按顺序进行遍历的;
在读取图像序列的时候经常要按顺序读取,如在多目标跟踪中;
这时可以sort进行排序;
 

//获取文件夹下所有图像名称,
// 图像名称按升序排列
int imageNameLists(string filePath, vector<string>& nameArr)
{
    vector<cv::String> fn;
    cv::glob(filePath, fn, false);
    size_t count = fn.size();
    if (count==0)
    {
        cout << "file " << filePath << " not  exits"<<endl;
        return -1;
    }
    for (int i = 0; i < count; ++i)
    {
        //1.获取不带路径的文件名,000001.jpg
        string::size_type iPos = fn[i].find_last_of('/') + 1;
        string filename = fn[i].substr(iPos, fn[i].length() - iPos);
        //cout << filename << endl;
        //2.获取不带后缀的文件名,000001
        string name = filename.substr(0, filename.rfind("."));
        //cout << name << endl;
        nameArr.emplace_back(name);
    }
    sort(nameArr.begin(), nameArr.end(),
         [](string a, string b) {return stoi(a) < stoi(b); });
    return 0;
}

图片里的等比缩放,图片缩放不变性

// 等比缩放
    cv::Mat Geometric_scaling(cv::Mat& img, int dst_w, int dst_h)
    {
        // 先生成一张目的图片,填充像素值为114
        cv::Mat resized_frame = cv::Mat(dst_h,dst_w,img.type(), cv::Scalar::all(114));
        // 获取缩放尺度较小的那个尺度,将以这个较小的尺度进行缩放
        float resize_scale_ = std::min((float)dst_w / (float)(img.cols), (float)dst_h / (float)(img.rows)); 
        cv::Mat tmp_mat;
        // 开始缩放,此时是不会变形的,因为根据小缩放比例进行的,然后获得图片,但是此时无法达到目标的大小,
        cv::resize(img, tmp_mat, cv::Size((int)(img.cols * resize_scale_), (int)(img.rows * resize_scale_)));
        // 此时直接把缩放后的图片覆盖resized_frame即可,此时resized_frame就是符合要求的缩放了
        tmp_mat.copyTo(resized_frame(cv::Rect(0, 0, tmp_mat.cols, tmp_mat.rows)));
        return resized_frame;
    }

读取序列化文件

// 加载序列化文件
    static std::vector<uint8_t> load_file(const string& file){

        ifstream in(file, ios::in | ios::binary);
        if (!in.is_open())
            return {};

        in.seekg(0, ios::end);
        size_t length = in.tellg();

        std::vector<uint8_t> data;
        if (length > 0){
            in.seekg(0, ios::beg);
            data.resize(length);

            in.read((char*)&data[0], length);
        }
        in.close();
        return data;
    }

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐