在OpenCv中读取文件夹上的多个图像(python)

4xy9mtcn  于 2023-04-12  发布在  Python
关注(0)|答案(8)|浏览(117)

我想使用opencv(python)读取同一文件夹上的多个图像。要做到这一点,我需要使用for循环或while循环与imread功能?如果是这样,如何?请帮助我...
我想把图像放入一个数组中,然后通过循环一次处理一个。

pbpqsu0x

pbpqsu0x1#

import glob
import cv2

images = [cv2.imread(file) for file in glob.glob("path/to/files/*.png")]
gv8xihay

gv8xihay2#

这将获取onlyfiles中一个文件夹中的所有文件,然后读取它们并将它们存储在数组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]) )
kmb7vmvb

kmb7vmvb3#

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

lrl1mhuk4#

这个有更好的时间效率。

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]
mbskvtky

mbskvtky5#

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

nzrxty8p6#

下面是我在不使用glob的情况下,使用os模块的方法,因为我无法让它在我的计算机上与glob一起工作:

# 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]
e7arh2l6

e7arh2l67#

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

s4n0splo8#

你可以试试这个

import glob
import cv2

path="D:\OMR_IMAGES\*.jpg"    #Replace with your folder 
path("your path\*.jpg") 
k=glob.glob(path)
images=[cv2.imread(images) for images in glob.glob(path)]

print(len(images))     #number of images in folder
for i in range(len(images)):
    cv2.imshow("images",images[i])
    cv2.waitKey(0)

在我的情况下,它起作用了

相关问题