I would like to be able to display a PIL image object created from a numpy array of 8 bit integers (essentially just a grayscale image) using pygame, but have been running into several errors in the process. Referring to this post, I tried using this function:
def pilImageToSurface(pilImage):
return pygame.image.fromstring(
pilImage.tobytes(), pilImage.size,pilImage.mode)
to take my PIL image object (created from a numpy array with datatype np.uint8
) and convert it to a pygame surface, but it would return the error
ValueError: Unrecognized type of format
I tried troubleshooting this by printing out pilImage.mode
which returned 'L'. simply replacing pilImage.mode
with 'L' in the function returned the same error. When I tried the format 'P', it simply displayed a solid gray image. What can I do to rectify this? here is an example of what I tried:
import numpy as np
from PIL import Image
import pygame
#initiating pygame and displaying a blank image to the screen
pygame.init()
white = (255, 255, 255)
X = 1920
Y = 1080
display_surface = pygame.display.set_mode((X, Y ))
pygame.display.set_caption('Image')
display_surface.fill(white)
#make PIL image object from a numpy array
imagelist = ((0,1,2,3),(255,254,253,252),(100,101,102,103)) #example array
imagearray = np.array(imagelist,dtype = np.uint8)
imagedata = Image.fromarray(imagearray)
def pilImageToSurface(pilImage):
return pygame.image.fromstring(
pilImage.tobytes(), pilImage.size,pilImage.mode)
pygameimage = pilImageToSurface(imagedata)
display_surface.blit(pygame_image, (0, 0)) #sends image to the display
pygame.display.update()