BytesIO 对象到图像
BytesIO object to image
我正在尝试在我的程序中使用 Pillow 将相机中的字节串保存到文件中。这是一个来自我的相机的小原始字节字符串的示例,它应该代表分辨率为 10x5 像素的灰度图像,使用 LSB 和 12 位:
import io
from PIL import Image
rawBytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\x00\\x00Z\x00\\x00_\x00[\x00\\x00\\x00`\x00]\x00\\x00^\x00_\x00\\x00\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\x00^\x00\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\x00Z\x00\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
rawIO = io.BytesIO(rawBytes)
rawIO.seek(0)
byteImg = Image.open(rawIO)
byteImg.save('test.png', 'PNG')
但是我在第 7 行(使用 Image.open
)出现以下错误:
OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8>
来自 Pillow 的文档暗示这是要走的路。
我尝试应用
中的解决方案
- PIL open() method not working with BytesIO
- PIL cannot identify image file for io.BytesIO object
但无法正常工作。为什么这不起作用?
我不确定生成的图像应该是什么样子(你有例子吗?),但如果你想将每个像素有 12 位的打包图像解压缩为 16 位图像,你可以使用此代码:
import io
from PIL import Image
rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\x00\\x00Z\x00\\x00_\x00[\x00\\x00\\x00`\x00]\x00\\x00^\x00_\x00\\x00\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\x00^\x00\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\x00Z\x00\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()
我正在尝试在我的程序中使用 Pillow 将相机中的字节串保存到文件中。这是一个来自我的相机的小原始字节字符串的示例,它应该代表分辨率为 10x5 像素的灰度图像,使用 LSB 和 12 位:
import io
from PIL import Image
rawBytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\x00\\x00Z\x00\\x00_\x00[\x00\\x00\\x00`\x00]\x00\\x00^\x00_\x00\\x00\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\x00^\x00\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\x00Z\x00\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
rawIO = io.BytesIO(rawBytes)
rawIO.seek(0)
byteImg = Image.open(rawIO)
byteImg.save('test.png', 'PNG')
但是我在第 7 行(使用 Image.open
)出现以下错误:
OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8>
来自 Pillow 的文档暗示这是要走的路。
我尝试应用
中的解决方案- PIL open() method not working with BytesIO
- PIL cannot identify image file for io.BytesIO object
但无法正常工作。为什么这不起作用?
我不确定生成的图像应该是什么样子(你有例子吗?),但如果你想将每个像素有 12 位的打包图像解压缩为 16 位图像,你可以使用此代码:
import io
from PIL import Image
rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\x00\\x00Z\x00\\x00_\x00[\x00\\x00\\x00`\x00]\x00\\x00^\x00_\x00\\x00\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\x00^\x00\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\x00Z\x00\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()