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

yipeiwu_com6年前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计算字符宽度的方法

本文实例讲述了Python计算字符宽度的方法。分享给大家供大家参考,具体如下: 最近在用python写一个CLI小程序,其中涉及到计算字符宽度,目标是以友好的方式将一个长字符串截取为等宽...

举例简单讲解Python中的数据存储模块shelve的用法

shelve类似于一个key-value数据库,可以很方便的用来保存Python的内存对象,其内部使用pickle来序列化数据,简单来说,使用者可以将一个列表、字典、或者用户自定义的类实...

Python 元组操作总结

Python的元组和列表类似,不同之处在于元组中的元素不能修改(因此元组又称为只读列表),且元组使用小括号而列表使用中括号,如下: tup1=('physics','chemistr...

Python实现冒泡,插入,选择排序简单实例

本文所述的Python实现冒泡,插入,选择排序简单实例比较适合Python初学者从基础开始学习数据结构和算法,示例简单易懂,具体代码如下: # -*- coding: cp936 -...

Python二进制文件读取并转换为浮点数详解

Python二进制文件读取并转换为浮点数详解

本文所用环境: Python 3.6.5 |Anaconda custom (64-bit)| 引言 由于某些原因,需要用python读取二进制文件,这里主要用到struct包,而这...