Pickleable Image Object

2019-02-04 22:42发布

How do I create a pickleable file from a PIL Image object such that you could save those images as a single pickle file then maybe upload to another computer such as a server running PIL and unpickle it there?

2条回答
Summer. ? 凉城
2楼-- · 2019-02-04 23:01

You can convert the Image object into data then you can pickle it:

image = {
    'pixels': im.tostring(),
    'size': im.size,
    'mode': im.mode,
}

And back to an Image:

im = Image.fromstring(image['mode'], image['size'], image['pixels'])

NOTE: As astex mentioned, if you're using Pillow (which is recommended instead of PIL), the tostring() method is deprecated for tobytes(). Likewise with fromstring() for frombytes().

查看更多
Explosion°爆炸
3楼-- · 2019-02-04 23:09

Slight variation of Gerald's answer using keyword args

create pickleable object

image = {'data': im.tostring(), 'size':im.size, 'mode':im.mode}

or

image = dict(data=im.tostring(), size=im.size, mode=im.mode)

unpickle back to image

im = Image.fromstring(**image)
查看更多
登录 后发表回答