我有一张以PIL图像格式存在的图片,我需要将它转换为字节数组。
img = Image.open(fh, mode='r')
roiImg = img.crop(box)
现在我需要将roiImg
作为字节数组。
我有一张以PIL图像格式存在的图片,我需要将它转换为字节数组。
img = Image.open(fh, mode='r')
roiImg = img.crop(box)
现在我需要将roiImg
作为字节数组。
感谢大家的帮助。
终于解决了!!
import io
from PIL import Image
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 裁剪後的圖像檢索字節數組。
format="jpg"
时,保存为字节不起作用,而 "jpeg"
对于文件和字节都有效,而 "jpg"
仅对文件有效。 - Evgeny Nozdrevstream = io.BytesIO(img_byte_array)
然后 img = Image.open(stream)
- Sean McCarthy这是我的解决方案:
from PIL import Image
import io
def image_to_byte_array(image: Image) -> bytes:
# BytesIO is a file-like buffer stored in memory
imgByteArr = io.BytesIO()
# image.save expects a file-like as a argument
image.save(imgByteArr, format=image.format)
# Turn the BytesIO object back into a bytes object
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')
Image.getdata()
获得,它返回PIL在特定平台上使用的图像的内部表示格式。 - dhkeImage
的getdata()
方法。 - martineau