我希望使用opencv (python)从同一个文件夹中读取多个图像。为此,我需要使用
我想将图像加载到数组中,并通过循环逐个处理它们。
for
循环或while
循环以及imread
函数吗?如果需要,如何操作?请帮助我...我想将图像加载到数组中,并通过循环逐个处理它们。
for
循环或while
循环以及imread
函数吗?如果需要,如何操作?请帮助我...import glob
import cv2
images = [cv2.imread(file) for file in glob.glob("path/to/files/*.png")]
这将获取文件夹中的所有文件到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]) )
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)
这个更加高效。
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]
这是我如何在不使用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]
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)
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)
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)
在我的情况下它起作用了