Convert PIL Image to byte array?

吃可爱长大的小学妹 提交于 2019-11-27 00:56:23

问题


I have an image in PIL Image format. I need to convert it to byte array.

img = Image.open(fh, mode='r')  
roiImg = img.crop(box)

Now I need the roiImg as a byte array.


回答1:


Thanks everyone for your help.

Finally got it resolved!!

import io

img = Image.open(fh, mode='r')
roiImg = img.crop(box)

imgByteArr = io.BytesIO()
roiImg.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()

With this i don't have to save the cropped image in my hard disc and I'm able to retrieve the byte array from a PIL cropped image.




回答2:


This is my solution.Please use this function.

from PIL import Image
import io

def image_to_byte_array(image:Image):
  imgByteArr = io.BytesIO()
  image.save(imgByteArr, format=image.format)
  imgByteArr = imgByteArr.getvalue()
  return imgByteArr



回答3:


I think you can simply call the PIL image's .tobytes() method, and from there, to convert it to an array, use the bytes built-in.

#assuming image is a flattened, 3-channel numpy array of e.g. 600 x 600 pixels
bytesarray = bytes(Image.fromarray(array.reshape((600,600,3))).tobytes())


来源:https://stackoverflow.com/questions/33101935/convert-pil-image-to-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!