Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

how to convert a numpy array to an Image that can be shown using PIL?

  1. User

    how to convert a numpy array to an Image that can be shown using PIL?

  2. Assistant

    To convert a numpy array to an image that can be shown using PIL, you can use the following code:

    import numpy as np
    from PIL import Image
    
    # assume we have a numpy array 'img_array'
    
    # normalize the array values between 0 and 255
    img_array = ((img_array - np.min(img_array)) / (np.max(img_array) - np.min(img_array))) * 255
    
    # convert the array to an image of type 'uint8'
    img = Image.fromarray(img_array.astype('uint8'))
    
    # show the image using PIL
    img.show()
    

    In the above code, we first normalize the array values between 0 and 255, as PIL expects values in that range. Then, we convert the array to an image of type uint8, which is the format expected by PIL. Finally, we show the image using the show() method of PIL.