[英]Convert PIL Image to byte array?
我有一個 PIL Image 格式的圖像。 我需要將其轉換為字節數組。
img = Image.open(fh, mode='r')
roiImg = img.crop(box)
現在我需要roiImg
作為字節數組。
感謝大家的幫助。
終於解決了!!
import io
img = Image.open(fh, mode='r')
roi_img = img.crop(box)
img_byte_arr = io.BytesIO()
roi_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
有了這個,我不必將裁剪后的圖像保存在我的硬盤中,我可以從 PIL 裁剪后的圖像中檢索字節數組。
這是我的解決方案。請使用此功能。
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
我認為您可以簡單地調用 PIL 圖像的.tobytes()
方法,然后從那里將其轉換為數組,使用內置的bytes
。
#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())
Python文件讀取和提取二進制數組
import base64
with open(img_file_name, "rb") as f:
image_binary = f.read()
base64_encode = base64.b64encode(image_binary)
byte_decode = base64_encode.decode('utf8')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.