是否有 python 函数用于将文件夹中的多个图像读取到单个数组中
is there a python function for reading multiple images from a folder into a single array
我正在尝试从单个 numpy 数组中的文件夹中读取多张图像,以将它们提供给我的深度学习模型。当我打印形状时,我收到 none 类型对象没有形状的错误消息。这意味着图像没有被opencv(for jpg)/tifffile(for .tif)读取我的代码如下
import numpy as np
import cv2 as cv
import tifffile as tiff
filepath1 = "D:/Programs/transnet/dataset/train"
filepath2 = "D:/Programs/transnet/dataset/train_label"
img = np.ndarray((cv.imread(filepath1 + "*.jpg")))
clt = np.ndarray((tiff.imread(filepath2 + "*.tif")))
print(img.shape)
print(clt.shape)
我已经尝试过 glob.glob 但它不起作用。
我期待 rgb 图像数量的 4 维数组
可以使用os模块进行文件遍历操作,特别是os.listdir
和os.path.join
如下
import os
def get_all_images(folder, ext):
all_files = []
#Iterate through all files in folder
for file in os.listdir(folder):
#Get the file extension
_, file_ext = os.path.splitext(file)
#If file is of given extension, get it's full path and append to list
if ext in file_ext:
full_file_path = os.path.join(folder, file)
all_files.append(full_file_path)
#Get list of all files
return all_files
filepath1 = "D:/Programs/transnet/dataset/train"
filepath2 = "D:/Programs/transnet/dataset/train_label"
#List of all jps and tif files
jpg_files = get_all_images(filepath1, 'jpg')
tif_files = get_all_images(filepath2, 'tif')
现在一旦您有了所有文件的列表,您就可以遍历列表并打开图像。
我正在尝试从单个 numpy 数组中的文件夹中读取多张图像,以将它们提供给我的深度学习模型。当我打印形状时,我收到 none 类型对象没有形状的错误消息。这意味着图像没有被opencv(for jpg)/tifffile(for .tif)读取我的代码如下
import numpy as np
import cv2 as cv
import tifffile as tiff
filepath1 = "D:/Programs/transnet/dataset/train"
filepath2 = "D:/Programs/transnet/dataset/train_label"
img = np.ndarray((cv.imread(filepath1 + "*.jpg")))
clt = np.ndarray((tiff.imread(filepath2 + "*.tif")))
print(img.shape)
print(clt.shape)
我已经尝试过 glob.glob 但它不起作用。 我期待 rgb 图像数量的 4 维数组
可以使用os模块进行文件遍历操作,特别是os.listdir
和os.path.join
如下
import os
def get_all_images(folder, ext):
all_files = []
#Iterate through all files in folder
for file in os.listdir(folder):
#Get the file extension
_, file_ext = os.path.splitext(file)
#If file is of given extension, get it's full path and append to list
if ext in file_ext:
full_file_path = os.path.join(folder, file)
all_files.append(full_file_path)
#Get list of all files
return all_files
filepath1 = "D:/Programs/transnet/dataset/train"
filepath2 = "D:/Programs/transnet/dataset/train_label"
#List of all jps and tif files
jpg_files = get_all_images(filepath1, 'jpg')
tif_files = get_all_images(filepath2, 'tif')
现在一旦您有了所有文件的列表,您就可以遍历列表并打开图像。