1.python读取指定文件夹下的所有文件和图片文件名
import cv2
import os
from os import path
def get_path_prex(img_dir):
paths = []
prefix = []
img_list=os.listdir(img_dir)
for img_name in img_list:
pre, ending = path.splitext(img_name)
#you can change the suffix to video or text suffix.
if ending != ".jpg" and ending != ".jepg" and ending != ".png":
continue
else:
paths.append(os.path.join(img_dir,img_name))
prefix.append(pre)
return paths, prefix
if __name__ == '__main__':
images_paths, preifx = get_path_prex('./images') #得到指定文件夹下的图片,例如.jpg,.jepg或.png等,可根据上述代码更改
for i in range(len(images_paths)):
img = cv2.imread(images_paths[i])
w = img.shape[1]
l = img.shape[0]
img_res = cv2.resize(img, (int(w/2), int(l/2)) ) #对图片操作后
cv2.imshow("img_res", img_res)
cv2.waitKey(10)
cv2.imwrite("./resized_wb/{}.jpg".format(preifx[i]),img_res)
另一种采用os的walk的方法可以得到所有文件夹下的图片,与上述基本一样:
import os
from os import path, walk
def get_path_prex(rootdir):
paths=[]
prefix = []
for root, dirs, files in walk(rootdir, topdown=True):
for name in files:
pre, ending = path.splitext(name)
#you can change the suffix to video or text suffix.
if ending != ".jpg" and ending != ".jepg" and ending != ".png":
continue
else:
paths.append(path.join(root, name))
prefix.append(pre)
return paths, prefix
if __name__ == '__main__':
images_paths, preifx = get_path_prex("./images")
# 对相应的图片操作
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");
}