2

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()

I get the following error

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 
4
  • Possible duplicate of load image with openCV Mat c++ - Im pretty sure you need backslashes in your image path and then it will work. Commented Mar 28, 2018 at 14:46
  • I have no idea about c++ Commented Mar 28, 2018 at 14:51
  • It's nothing to do with C++, use C:\\... rather than c:\\. Read the answer Commented Mar 28, 2018 at 14:52
  • Sorry I could not understand Commented Mar 28, 2018 at 15:02

1 Answer 1

6

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

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Yes windows will require \\ in the filenames

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.