如何从python中的多个文件夹中读取多个图像

如何从python中的多个文件夹中读取多个图像

本文介绍了如何从python中的多个文件夹中读取多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用anaconda在python 3.6中编写一个图像识别程序.我将图像数据集存储在E:\ food-101 \ images位置,其中的'images'文件夹包含多个子文件夹包含照片.我想使用这些图像来训练我的机器学习模型.我能够加载(读取)存储在E:\中的单个图像.我想从上述路径加载多个图像,我该如何进行我正在使用opencv.我的代码如下,感谢您的帮助

I am writing an image recognition program in python 3.6 for which I am using anaconda.I have my image data set stored in the location E:\food-101\images in which the 'images' folder contains multiple sub folders which contain the photographs. I want to use these images for training my machine learning model.I am able to load(read) a single image stored in E:\ I want to load multiple images from the above path how do I proceed ?I am using opencv. my code is as follows any help is appreciated

import cv2
import matplotlib
import numpy
img = cv2.imread("E:\food\images\chicken_wings\a.jpg",cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我收到以下错误

Traceback (most recent call last):

  File "<ipython-input-8-6310b5f3028e>", line 5, in <module>
    cv2.imshow('image',img)

error: OpenCV(3.4.1) C:\bld\opencv_1520732670222\work\opencv-3.4.1\modules\highgui\src\window.cpp:356: error: (-215) size.width>0 && size.height>0 in function cv::imshow


Traceback (most recent call last):

  File "<ipython-input-8-6310b5f3028e>", line 5, in <module>
    cv2.imshow('image',img)

error: OpenCV(3.4.1) C:\bld\opencv_1520732670222\work\opencv-3.4.1\modules\highgui\src\window.cpp:356: error: (-215) size.width>0 && size.height>0 in function cv::imshow

推荐答案

一种简单的方法是安装Glob.您可以使用pip install glob在anaconda提示符下执行此操作.

An easy way would be to install Glob. You can do this from the anaconda prompt with pip install glob.

Glob允许您像在终端中一样查询文件.有了Glob之后,您可以将所有文件名保存到列表中,然后遍历此列表,将图像(NumPy数组)读取到新列表中.

Glob allows you to query files like you would in a terminal. Once you have Glob you could save all of the file names to a list and then loop through this list reading your images (NumPy arrays) into a new list.

import cv2
import numpy
import glob

folders = glob.glob('path\\to\\folder\\containing\\folders\\*')
imagenames_list = []
for folder in folders:
    for f in glob.glob(folder+'/*.jpg'):
        imagenames_list.append(f)

read_images = []
for image in imagenames_list:
    read_images.append(cv2.imread(image, cv2.IMREAD_GRAYSCALE))

然后您可以通过索引图像来访问图像,即

You could then access an image by indexing it i.e.

plt.imshow(read_images[0])

这篇关于如何从python中的多个文件夹中读取多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:37