Skip to content

Instantly share code, notes, and snippets.

@ufxpri
Created August 4, 2022 02:53
Show Gist options
  • Select an option

  • Save ufxpri/65518eabd358cddc2ca56c7d7b7d5177 to your computer and use it in GitHub Desktop.

Select an option

Save ufxpri/65518eabd358cddc2ca56c7d7b7d5177 to your computer and use it in GitHub Desktop.
def to_numpy(im:Image):
im.load()
e = Image._getencoder(im.mode, 'raw', im.mode)
e.setimage(im.im)
# NumPy buffer for the result
shape, typestr = Image._conv_type_shape(im)
data = np.empty(shape, dtype=np.dtype(typestr))
mem = data.data.cast('B', (data.data.nbytes,))
bufsize, s, offset = 65536, 0, 0
while not s:
l, s, d = e.encode(bufsize)
mem[offset:offset + len(d)] = d
offset += len(d)
if s < 0:
raise RuntimeError("encoder error %d in tobytes" % s)
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment