我想你想创建一个带有标签作为维度的 numpy 图像数组?您可以使用以下代码:
def class_segmentation(dir_path,df):
""" takes a given folder and splits it into respective classes based on the csv file labels
mapped to the names of the files
dir_path = path of the directory which needs to be segmented
classes = list of classes present in the dataset, as string
"""
image_list = os.listdir(dir_path)
classes = get_classes(df)
for clas in classes:
os.makedirs(os.path.join(dir_path,clas))
for image in image_list:
if(image in df['image_extensions'].tolist()):
label = (df[df['image_extensions']==image]['label']).tolist()[0]
image_path_src = os.path.join(dir_path, image)
dest = os.path.join(dir_path, str(label))
image_path_dest = os.path.join(dest,image)
shutil.move(image_path_src, image_path_dest)
接下来需要将这些图片转换为numpy数组,并加载对应的标签。
def img_to_array_data(dir_path, classes):
data_array = []
for clas in classes:
classpath = os.path.join(dir_path,str(clas))
for img in os.listdir(classpath):
img_array = cv2.imread(os.path.join(classpath,img))
data_array.append([img_array,clas])
random.shuffle(data_array)
X =[]
y =[]
for features, label in data_array:
X.append(features)
y.append(label)
X = np.array(X).reshape(-1, dim[0], dim[0], 3)
X = X.astype('float32')
X /= 255
Y = np_utils.to_categorical(y, 5)
return X,Y
当然,不要忘记导入所有必要的库:os、np_utils 等。