0

I want to read images of multiple datatypes from multiple subdirectories in python using glob function

I have successfully read images of JPG type from the subdirectories. Want to know how can I read images of multiple datatypes. Below are the codes I have tried so far

###########READ IMAGES OF MULTIPLE DATATYPES from a SINGLE Folder######

    import os
    import glob

    files = []
    for ext in ('*.jpg', '*.jpeg'):
       files.extend(glob(join("C:\\Python35\\target_non_target\\test_images", ext)))
    count=0   

    for i in range(len(files)):
        image=cv2.imread(files[i])
        print(image)

###### READ MULTIPLE JPG IMAGS FROM MULTIPLE SUBDIRECTORIES#########

import os
import glob
from glob import glob

folders = glob("C:\\Python36\\videos\\videos_new\\*")

img_list = []
for folder in folders:
    for f in glob(folder+"/*.jpg"):
        img_list.append(f)

for i in range(len(img_list)):
    print(img_list[i])

Both codes work perfectly but I am confused how to include the line for reading multiple datatype images from multiple subdirectories. I have a directory with multiple subdirectories in which there are images of multiple datatypes like JPG,PNG,JPEG,etc. I want to read all those images and use them in my code

Ankit
  • 203
  • 3
  • 14

1 Answers1

2

Try this:

import glob
my_root = r'C:\Python36\videos\videos_new'
my_exts = ['*.jpg', 'jpeg', '*.png']
files = [glob.glob(my_root + '/**/'+ x, recursive=True) for x in my_exts]  

Check this out for various ways to recursively search folders.

On another note, instead of this:

for i in range(len(img_list)):  
    print(img_list[i])

do this for simple, readable for-loop using python:

for img in img_list:
    print(img)
SanV
  • 855
  • 8
  • 16
  • sorry for the really late reply. Your code suggestion works fine. Thanks for the help :) – Ankit Apr 08 '19 at 14:38