昊虹君 发表于 2022-10-28 13:29

C++下批量读取名字无规则的图片文件的示例代码(利用类WIN32_FIND_DATA实现)

C++下批量读取名字无规则的图片文件的示例代码(利用类WIN32_FIND_DATA实现)

在博文 https://www.hhai.cc/thread-101-1-1.html 中要求批量读取的图片名字是有规律的,有时候我们会遇到图片名字无规律的情况,此时该怎么办呢?
此时可以利用C++的类WIN32_FIND_DATA实现。

具体实现的代码没什么好说的,大家直接拿来用就行。
代码如下:

//出处:昊虹AI笔记网(hhai.cc)
//用心记录计算机视觉和AI技术

//博主微信/QQ 2487872782
//QQ群 271891601
//欢迎技术交流与咨询

//OpenCV版本 OpenCV3.0

#include <opencv2/opencv.hpp>
#include <iostream>

#include <stdio.h>
#include <windows.h>

using namespace cv;
using namespace std;


// LPCWSTR转string
std::string WChar2Ansi(LPCWSTR pwszSrc)
{
    int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);

    if (nLen <= 0) return std::string("");

    char* pszDst = new char;
    if (NULL == pszDst) return std::string("");

    WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
    pszDst = 0;

    std::string strTemp(pszDst);
    delete[] pszDst;

    return strTemp;
}

// 利用winWIN32_FIND_DATA读取文件下的文件名
void readImgNamefromFile(char* fileName, vector <string> &imgNames)
{
    // vector清零 参数设置
    imgNames.clear();
    WIN32_FIND_DATA file;
    int i = 0;
    char tempFilePath;
    char tempFileName;
    // 转换输入文件名
    sprintf_s(tempFilePath, "%s/*", fileName);
    // 多字节转换
    WCHAR   wstr = { 0 };
    MultiByteToWideChar(CP_ACP, 0, tempFilePath, -1, wstr, sizeof(wstr));
    // 查找该文件待操作文件的相关属性读取到WIN32_FIND_DATA
    HANDLE handle = FindFirstFile(wstr, &file);
    if (handle != INVALID_HANDLE_VALUE)
    {
      FindNextFile(handle, &file);
      FindNextFile(handle, &file);
      // 循环遍历得到文件夹的所有文件名
      do
      {
            sprintf(tempFileName, "%s", fileName);
            imgNames.push_back(WChar2Ansi(file.cFileName));
            imgNames.insert(0, tempFileName);
            i++;
      } while (FindNextFile(handle, &file));
    }
    FindClose(handle);
}
int main()
{
    // 设置读入图像序列文件夹的路径
    char* fileName = "F:/material/images/2022/2022-10/batch_read/";
    std::vector <string>imgNames;
    // 获取对应文件夹下所有文件名
    readImgNamefromFile(fileName, imgNames);
    // 遍历对应文件夹下所有文件名
    for (int i = 0; i < imgNames.size(); i++)
    {
      cv::Mat img = cv::imread(imgNames);
      if (!img.data)
            return -1;
      /* 可添加图像处理算法code*/
      cv::imshow("im", img);
      cv::waitKey(0);
    }
    return 0;
}
代码的运行效果为:
按一次任意键,程序读取并显示一张文件夹batch_read下的图片。
页: [1]
查看完整版本: C++下批量读取名字无规则的图片文件的示例代码(利用类WIN32_FIND_DATA实现)