CNN数据预处理遇阻:图片展示无输出求助
问题分析与修复方案
核心问题:图片路径不完整
你收集sample_images时只存储了文件名,没有保存完整的文件路径,导致Image.open(file)无法定位到对应图片文件,因此没有任何输出。
代码修复步骤
1. 修正sample_images的路径存储逻辑
将图片的完整路径存入列表,而非仅文件名:
sample_images = [] for label in labels: image_path = os.path.join(main_path, label) for img in os.listdir(image_path): if img.lower().startswith(label.lower()) and re.search(r'\(1\)', img): # 保存完整路径,确保后续能找到文件 full_img_path = os.path.join(image_path, img) sample_images.append(full_img_path) print(sample_images)
2. 简化图片读取与显示逻辑
既然已经持有完整路径,无需再从文件名推导标签,直接读取并展示即可:
for img_path in sample_images: # 通过完整路径读取图片 img = np.asarray(Image.open(img_path)) plt.imshow(img) # 用文件名作为图片标题 plt.title(os.path.basename(img_path)) plt.axis('off') plt.show()
3. 额外优化:避免train_images重复收集
原代码中收集train_images的循环存在逻辑漏洞,每次新增一个标签就会遍历所有已存标签的文件夹,导致图片被重复添加。可以调整为:
labels = [] train_images = [] for file in os.listdir(main_path): if file == '.DS_Store' or file == 'Rice_Citation_Request.txt': continue labels.append(file) # 仅遍历当前新增的标签文件夹,而非所有已存标签 folder = os.path.join(main_path, file) for img in os.listdir(folder): train_images.append(os.path.join(folder, img)) # 建议同步存完整路径
验证方式
运行修改后的代码,sample_images会输出每个样本的完整路径,后续plt.show()即可正常显示每张目标图片。
内容的提问来源于stack exchange,提问作者Gustavo
相关产品推荐
相关产品推荐

