def pil_to_array(pilImage):
 def toarray(im):
  'return a 1D array of floats'
  x_str = im.tostring('raw', im.mode, 0, (-1))
  x = np.fromstring(x_str, np.uint8)
  return x
 if (pilImage.mode in ('RGBA', 'RGBX')):
  im = pilImage
 elif (pilImage.mode == 'L'):
  im = pilImage
  x = toarray(im)
  x.shape = (im.size[1], im.size[0])
  return x
 elif (pilImage.mode == 'RGB'):
  im = pilImage
  x = toarray(im)
  x.shape = (im.size[1], im.size[0], 3)
  return x
 else:
  try:
   im = pilImage.convert('RGBA')
  except ValueError:
   raise RuntimeError('Unknown image mode')
 x = toarray(im)
 x.shape = (im.size[1], im.size[0], 4)
 return x

def pil_to_array ( pilImage ) : def toarray ( im ) : x_str = im . tostring ( 'raw' , im . mode , 0 , ( - 1 ) ) x = np . fromstring ( x_str , np . uint8 ) return x if ( pilImage . mode in ( 'RGBA' , 'RGBX' ) ) : im = pilImage elif ( pilImage . mode == 'L' ) : im = pilImage x = toarray ( im ) x . shape = ( im . size [ 1 ] , im . size [ 0 ] ) return x elif ( pilImage . mode == 'RGB' ) : im = pilImage x = toarray ( im ) x . shape = ( im . size [ 1 ] , im . size [ 0 ] , 3 ) return x else : try : im = pilImage . convert ( 'RGBA' ) except ValueError : raise RuntimeError ( 'Unknown image mode' ) x = toarray ( im ) x . shape = ( im . size [ 1 ] , im . size [ 0 ] , 4 ) return x
load a pil image and return it as a numpy array of uint8 .