Home Backend Development Python Tutorial How to share the implementation code of how to traverse all pictures in a folder using Python and C++

How to share the implementation code of how to traverse all pictures in a folder using Python and C++

Jun 04, 2017 am 10:13 AM

这篇文章主要介绍了 Python与C++ 遍历文件夹下的所有图片实现代码的相关资料,需要的朋友可以参考下

 Pyhton与C++ 遍历文件夹下的所有图片实现代码

前言

虽然本文说的是遍历图片,但是遍历其他文件也是可以的。

在进行图像处理的时候,大部分时候只需要处理单张图片。但是一旦把图像处理和机器学习相结合,或者做一些稍大一些的任务的时候,常常需要处理好多图片。而这里面,一个最基本的问题就是如何遍历这些图片。

用OpenCV做过人脸识别的人应该知道,那个项目中并没有进行图片的遍历,而是用了一种辅助方案,生成了一个包含所有图片路径的文件at.txt,然后通过这个路径来读取所有图片。而且这个辅助文件不仅包含了图片的路径,还包含了图片对应的标签。所以在进行训练的时候直接通过这个辅助文件来读取训练用的图片和标签。

其实如果去看看教程,会发现这个at.txt的生成是通过Python代码来实现。所以今天就来看一下如何用C++来实现文件夹下所有图片的遍历。

当然在此之前还是先给出Python遍历的代码,以备后用。

Python遍历

在之前的数独项目中,进行图像处理的时候用到了遍历文件夹下所有的图片。主要是利用glob模块。glob是python自己带的一个文件操作相关模块,内容不多,可以用它查找符合自己目的的文件。

# encoding: UTF-8
import glob as gb
import cv2

#Returns a list of all folders with participant numbers
img_path = gb.glob("numbers\\*.jpg") 
for path in img_path:
  img = cv2.imread(path) 
  cv2.imshow('img',img)
  cv2.waitKey(1000)
Copy after login

C++遍历

1. opencv自带函数glob()遍历

OpenCV自带一个函数glob()可以遍历文件,如果用这个函数的话,遍历文件也是非常简单的。这个函数非常强大,人脸识别的时候用这个函数应该会比用at.txt更加方便。一个参考示例如下。

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

using namespace std;
using namespace cv;

vector<Mat> read_images_in_folder(cv::String pattern);

int main()
{
  cv::String pattern = "G:/temp_picture/*.jpg";
  vector<Mat> images = read_images_in_folder(pattern);

  return 0;  
}

vector<Mat> read_images_in_folder(cv::String pattern)
{
  vector<cv::String> fn;
  glob(pattern, fn, false);

  vector<Mat> images;
  size_t count = fn.size(); //number of png files in images folder
  for (size_t i = 0; i < count; i++)
  {
    images.push_back(imread(fn[i]));
    imshow("img", imread(fn[i]));
    waitKey(1000);
  }
  return images;
}
Copy after login

需要注意的是,这里的路径和模式都用的是cv::String。

2. 自己写一个遍历文件夹的函数

在windows下,没有dirent.h可用,但是可以根据windows.h自己写一个遍历函数。这就有点像是上面的glob的原理和实现了。

#include<opencv2\opencv.hpp>
#include<iostream>
#include <windows.h> // for windows systems

using namespace std;
using namespace cv;

void read_files(std::vector<string> &filepaths,std::vector<string> &filenames, const string &directory);

int main()
{
  string folder = "G:/temp_picture/";
  vector<string> filepaths,filenames;
  read_files(filepaths,filenames, folder);
  for (size_t i = 0; i < filepaths.size(); ++i)
  {
    //Mat src = imread(filepaths[i]);
    Mat src = imread(folder + filenames[i]);
    if (!src.data)
      cerr << "Problem loading image!!!" << endl;
    imshow(filenames[i], src);
    waitKey(1000);
  }
  return 0;

}

void read_files(std::vector<string> &filepaths, std::vector<string> &filenames, const string &directory)
{
  HANDLE dir;
  WIN32_FIND_DATA file_data;

  if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
    return; /* No files found */

  do {
    const string file_name = file_data.cFileName;
    const string file_path = directory + "/" + file_name;
    const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

    if (file_name[0] == &#39;.&#39;)
      continue;

    if (is_directory)
      continue;

    filepaths.push_back(file_path);
    filenames.push_back(file_name);
  } while (FindNextFile(dir, &file_data));

  FindClose(dir);
}
Copy after login

3. 基于Boost

如果电脑上配置了boost库,用boost库来实现这一功能也是比较简洁的。为了用这个我还专门完全编译了Boost。

然而只用到了filesystem。

#include <boost/filesystem.hpp>
#include<iostream>
#include<opencv2\opencv.hpp>

using namespace cv;
using namespace std;
using namespace boost::filesystem;

void readFilenamesBoost(vector<string> &filenames, const string &folder);

int main()
{
  string folder = "G:/temp_picture/";
  vector<string> filenames;
  readFilenamesBoost(filenames, folder);
  for (size_t i = 0; i < filenames.size(); ++i)
  {
    Mat src = imread(folder + filenames[i]);

    if (!src.data)
      cerr << "Problem loading image!!!" << endl;
    imshow("img", src);
    waitKey(1000);
  }
  return 0;
}

void readFilenamesBoost(vector<string> &filenames, const string &folder)
{
  path directory(folder);
  directory_iterator itr(directory), end_itr;
  string current_file = itr->path().string();

  for (; itr != end_itr; ++itr)
  {
    if (is_regular_file(itr->path()))
    {
      string filename = itr->path().filename().string(); // returns just filename
      filenames.push_back(filename);
    }
  }
}
Copy after login

各种方法都记录在这里,以便以后用的时候查找。

The above is the detailed content of How to share the implementation code of how to traverse all pictures in a folder using Python and C++. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Do you use c in visual studio code Do you use c in visual studio code Apr 15, 2025 pm 08:03 PM

Writing C in VS Code is not only feasible, but also efficient and elegant. The key is to install the excellent C/C extension, which provides functions such as code completion, syntax highlighting, and debugging. VS Code's debugging capabilities help you quickly locate bugs, while printf output is an old-fashioned but effective debugging method. In addition, when dynamic memory allocation, the return value should be checked and memory freed to prevent memory leaks, and debugging these issues is convenient in VS Code. Although VS Code cannot directly help with performance optimization, it provides a good development environment for easy analysis of code performance. Good programming habits, readability and maintainability are also crucial. Anyway, VS Code is

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles