Skip to content
Advertisement

AWS SageMaker Jupyter Notebook: Images not Showing

I’m currently trying to display some images using AWS SageMaker making use of its Jupyter Notebook app. However, all I’m trying to do is show the loaded images. I have written a function to do this but all I’m left with is the images index and image name on calling the function.

The function:

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

Calling the function:

get_random_image("train", "p")

Example result:

2078 ./data/chest_xray/train/PNEUMONIA/person522_virus_1041.jpeg
<matplotlib.image.AxesImage at 0x7fd89ab86090>

I’ve done various things from logging out/in to restarting the kernel; only one option and thats python 3.

Advertisement

Answer

You have to add line to the first cell (or before the first plt.show() call) of the notebook:

%matplotlib inline

This a is a magic function in IPython.

According to documentation:

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

3 People found this is helpful
Advertisement