基于CNN的多标签图像分类:标签维度异常问题求助
问题根源分析
- 标签存储逻辑错误:原代码中
labels_data[folder] = folder_data将图像数据赋值给标签字典,完全偏离了标签的定义,标签应对应文件夹的类别索引。 - 标签生成逻辑错误:生成
all_labels时使用data[:, 0]作为模板,data是每个文件夹的图像数组(形状为(114,56,56)),data[:,0]提取的是每张图像的第一行像素,形状为(114,56),因此np.full_like生成的数组形状与模板一致,最终拼接后得到(2280,56),而非多标签分类所需的(2280,20)独热编码格式。
修正后的完整代码
import cv2 import os import numpy as np def read_image(image_path): # 读取图像 image = cv2.imread(image_path) # 转为灰度图 image_resized = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 归一化像素值 image_resized = image_resized.astype('float32') / 255.0 # 强制统一图像尺寸为(56,56) if image_resized.shape != (56,56): image_resized = cv2.resize(image_resized, (56,56), interpolation=cv2.INTER_AREA) return image_resized def process_folder(folder_path): images = [] # 获取文件夹内所有图像文件 image_files = sorted([f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]) for image_file in image_files: image_path = os.path.join(folder_path, image_file) image_processed = read_image(image_path) images.append(image_processed) return np.array(images) def create_folder_dictionary(root_folder_path): folder_dictionary = {} # 存储文件夹到类别索引的映射(0-19) folder_label_map = {} folders = sorted([f for f in os.listdir(root_folder_path) if os.path.isdir(os.path.join(root_folder_path, f))]) for idx, folder in enumerate(folders): folder_path = os.path.join(root_folder_path, folder) folder_data = process_folder(folder_path) if folder_data is not None: folder_dictionary[folder] = folder_data folder_label_map[folder] = idx return folder_dictionary, folder_label_map root_folder_path = r'C:\Users\sumit\Downloads\master thesis\ImageDataset' result, folder_label_map = create_folder_dictionary(root_folder_path) folders = list(result.keys()) folder_data_list = list(result.values()) # 统计总图像数 total_images = sum(len(images) for images in folder_data_list) print(f"Total number of images: {total_images}") # 拼接所有图像 all_images = np.concatenate(folder_data_list, axis=0) print(f"All images shape: {all_images.shape}") # 生成(2280,20)的独热编码标签 all_labels = [] for folder, data in zip(folders, folder_data_list): label_idx = folder_label_map[folder] # 为当前文件夹的每张图像生成独热编码 one_hot_label = np.zeros((len(data), 20), dtype=np.float32) one_hot_label[:, label_idx] = 1.0 all_labels.append(one_hot_label) all_labels = np.concatenate(all_labels, axis=0) print(f"Shape of all_labels: {all_labels.shape}")
关键修正说明
- 移除错误的
labels_data字典,改用folder_label_map存储文件夹与类别索引的对应关系。 - 生成标签时采用独热编码格式,每个标签是长度为20的数组,对应类别的位置设为1,其余为0,最终拼接后形状符合多标签分类的
(2280,20)要求。 - 增加图像尺寸检查与强制统一,避免因原始图像尺寸不一致导致后续处理出错。
内容的提问来源于stack exchange,提问作者beschichtung346
相关产品推荐
相关产品推荐

