19

I want to read multiple images on a same folder using opencv (python). To do that do I need to use for loop or while loop with imread funcion? If so, how? please help me...

I want to get images into an array and then processed them one at a time through a loop.

1

7 Answers 7

43
import glob
import cv2

images = [cv2.imread(file) for file in glob.glob("path/to/files/*.png")]
Sign up to request clarification or add additional context in comments.

1 Comment

this returns empty lists only
15

This will get all the files in a folder in onlyfiles. And then it will read them all and store them in the array images.

from os import listdir
from os.path import isfile, join
import numpy
import cv2

mypath='/path/to/folder'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = numpy.empty(len(onlyfiles), dtype=object)
for n in range(0, len(onlyfiles)):
  images[n] = cv2.imread( join(mypath,onlyfiles[n]) )

Comments

5
import glob
import cv2 as cv

path = glob.glob("/path/to/folder/*.jpg")
cv_img = []
for img in path:
    n = cv.imread(img)
    cv_img.append(n)

Comments

4

This one has better time efficiency.

def read_img(img_list, img):
    n = cv2.imread(img, 0)
    img_list.append(n)
    return img_list

path = glob.glob("*.bmp") #or jpg
list_ = []`

cv_image = [read_img(list_, img) for img in path]

Comments

1
import cv2
from pathlib import Path

path=Path(".")

path=path.glob("*.jpg")

images=[]`


for imagepath in path.glob("*.jpg"):

        img=cv2.imread(str(imagepath))
        img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)                         
        img=cv2.resize(img,(200,200))
        images.append(img)
print(images)

Comments

1

Here is how I did it without using glob, but with using the os module instead, since I could not get it to work with glob on my computer:

# This is to get the names of all the files in the desired directory
# Here I assume that they are all images
original_images = os.listdir('./path/containing/images')

# Here I construct a list of relative path strings for each image
original_images = [f"./path/containing/images/{file_name}" for file_name in original_images]

original_images = [cv2.imread(file) for file in original_images]

Comments

0
def flatten_images(folder):               # Path of folder (dataset)
    images=[]                             # list contatining  all images
    for filename in os.listdir(folder):
        print(filename)
        img=plt.imread(folder+filename)  # reading image (Folder path and image name )
        img=np.array(img)                #
        img=img.flatten()                # Flatten image 
        images.append(img)               # Appending all images in 'images' list 
    return(images)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.