AWS SageMaker Jupyter Notebook图片无法显示问题求助
问题解决:AWS SageMaker Jupyter Notebook无法显示图片
问题现象
在AWS SageMaker的Jupyter Notebook中,编写了加载并显示指定条件随机X光胸片的函数,但调用后仅输出图片索引、路径以及<matplotlib.image.AxesImage at 0x7fd89ab86090>对象,图片未正常渲染显示。已尝试登出重新登录、重启Python 3内核,问题仍存在。
原函数代码:
import glob import random import matplotlib.pyplot as plt def get_random_image(dir, condition): placeholder = '' if condition == 'n': placeholder = 'NORMAL' elif condition == 'p': placeholder = 'PNEUMONIA' else: raise Exception("Sorry, invalid condition") #folder to look through for images folder = f"./data/chest_xray/{dir}/{placeholder}/*.jpeg" img_paths = glob.glob(folder) #folders have different number of images in them max_length = len(img_paths) randomNumber = random.randint(0, max_length) for index, item in enumerate(img_paths, start = 1): if index == randomNumber: #print image path print(index, item) #image from folder image = plt.imread(item) readyImage = plt.imshow(image) return readyImage
调用代码:
get_random_image("train", "p")
示例输出:
2078 ./data/chest_xray/train/PNEUMONIA/person522_virus_1041.jpeg <matplotlib.image.AxesImage at 0x7fd89ab86090>
问题原因及修复方案
- 缺少图片显示触发命令:Jupyter Notebook环境中,
plt.imshow()仅完成图片绘制准备,必须调用plt.show()才能触发图片渲染显示。 - 随机数范围错误:
random.randint(0, max_length)可能生成超出列表有效索引范围的数值,应将范围改为1到max_length(匹配enumerate的起始索引),或直接基于列表索引生成随机数。 - 遍历取随机元素效率低下:无需通过循环匹配索引,直接用随机索引从列表中取元素即可,简化逻辑同时提升效率。
修改后的代码
import glob import random import matplotlib.pyplot as plt def get_random_image(dir, condition): placeholder = '' if condition == 'n': placeholder = 'NORMAL' elif condition == 'p': placeholder = 'PNEUMONIA' else: raise Exception("无效的条件参数,仅支持'n'或'p'") # 构建图片路径匹配规则 folder = f"./data/chest_xray/{dir}/{placeholder}/*.jpeg" img_paths = glob.glob(folder) if not img_paths: raise Exception("指定路径下未找到任何jpeg图片") # 生成有效范围内的随机索引并选中图片 random_index = random.randint(0, len(img_paths)-1) selected_path = img_paths[random_index] # 输出选中的图片信息 print(random_index + 1, selected_path) # 加载并显示图片 image = plt.imread(selected_path) plt.imshow(image) plt.show() # 关键:触发图片显示
调用方式不变,执行后即可正常显示图片。
内容的提问来源于stack exchange,提问作者MRL
相关产品推荐
相关产品推荐

