python或C++读取指定文件夹下的所有图片

yipeiwu_com5年前Python基础

本文实例为大家分享了python或C++读取指定文件夹下的所有图片,供大家参考,具体内容如下

1.python读取指定文件夹下的所有图片路径和图片文件名

import cv2
from os import walk,path

def get_fileNames(rootdir):
 data=[]
 prefix = []
 for root, dirs, files in walk(rootdir, topdown=True):
  for name in files:
   pre, ending = path.splitext(name)
   if ending != ".jpg" and ending != ".jepg" and ending != ".png":
    continue
   else:
    data.append(path.join(root, name))
    prefix.append(pre)
 return data, prefix



if __name__ == '__main__':

 images, preifx = get_fileNames('/home/yasin/target_pics') #得到指定文件夹下的图片,例如.jpg,.jepg或.png等,可根据上述代码更改
 for i in range(len(images)):
  img = cv2.imread(images[i])
  w = img.shape[1]
  l = img.shape[0]
  img_res = cv2.resize(img, (w*2,l*2)) #对图片操作后
  cv2.imwrite("./resized_wb/{}.jpg".format(preifx[i]),img_res)

2.C++得到指定文件夹下的所有图片并返回读取Mat值

#include <stdio.h>
#include <highgui.h>
#include <opencv2/opencv.hpp>
#include <cv.h>

using namespace std;
using namespace cv;


//读取指定文件下的所有图片
vector<Mat> read_images_in_folder(cv::String pattern)
{
 vector<cv::String> fn;
 glob(pattern, fn, false);

 vector<Mat> images;
 // vector<cv::String>&prefix //
 size_t count = fn.size(); //number of png files in images folder
 for (size_t i = 0; i < count; i++)
 {
  // prefix.push_back(fn[i].substr(20, 4)); // 此处可以得到文件名的子字符串,可以获取图片前缀
 images.push_back(imread(fn[i])); //直读取图片并返回Mat类型
 //imshow("img", imread(fn[i]));
 //waitKey(1000);
 }
 return images;
}

int main()
{

 cv::String pattern = "./*.jpg";

 //遍历得到目标文件中所有的.jpg文件
 vector<Mat> images = read_images_in_folder(pattern);

 for (int i = 0; i < images.size(); i++)
 {
 imshow("img", images[i]);
 waitKey(1000);
 }
 // system("pause");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python常用的json标准库

当请求 headers 中,添加一个name为 Accept,值为 application/json 的 header(也即“我”(浏览器)接收的是 json 格式的数据),这样,向服务...

python实现n个数中选出m个数的方法

python实现n个数中选出m个数的方法

题目: 某页纸上有一个数列A,A包含了按照从小到大的顺序排列的多个自然数,但是因为一些原因,其中有M个连续的位置看不清了。这M个数左边最小的数是X,右边最大的数是Y,这些数之和大于等于P...

numpy中索引和切片详解

numpy中索引和切片详解

索引和切片 一维数组 一维数组很简单,基本和列表一致。 它们的区别在于数组切片是原始数组视图(这就意味着,如果做任何修改,原始都会跟着更改)。 这也意味着,如果不想更改原始数组,我们需要...

PyQt5组件读取参数的实例

1.QLineEdit QLineEdit.text() #输出str类型 2.QCheckBox QCheckBox.checkState() #状态 选定: int(QCh...

django fernet fields字段加密实践详解

一、fernet介绍 Fernet 用于django模型字段对称加密,使用 crytography 库。 官网帮助文档 1、先决条件 django-fernet-fields 支持D...