'Read Multiple images on a folder in OpenCv (python)
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.
Solution 1:[1]
import glob
import cv2
images = [cv2.imread(file) for file in glob.glob("path/to/files/*.png")]
Solution 2:[2]
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]) )
Solution 3:[3]
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)
Solution 4:[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]
Solution 5:[5]
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)
Solution 6:[6]
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)
Solution 7:[7]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Soufiane S |
| Solution 2 | |
| Solution 3 | Felipe Weber |
| Solution 4 | Shivaraj |
| Solution 5 | Eric Aya |
| Solution 6 | Dhiren Biren |
| Solution 7 |
