raspberry-pi - Cannot identify image file io.BytesIO on raspberry Pi using PiCamera library and PIL
问题描述
I am having trouble using the output from PiCamera capture function (directed in a BytesIO stream) and opening it using the PIL library. Here is the code (based on the PiCamera basic examples):
#Camera stuff
camera = PiCamera()
camera.resolution = (640, 480)
stream = io.BytesIO()
sleep(2)
try:
for frame in camera.capture_continuous(stream, format = "jpeg", use_video_port = True):
frame.seek(0)
image = Image.open(frame) //THIS IS WHERE IS CRASHES
#OTHER STUFF THAT IS NON IMPORTANT GOES HERE
frame.truncate(0)
finally:
camera.close()
stream.close()
The error is : PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0xaa01cf00>
Any help would be greatly appreciated :)
Have a nice day!
解决方案
问题很简单,但我想知道为什么 io 库会这样工作。只需要在截断流后将流返回到 0 或搜索到 0,然后简单地调用不带参数的 truncate (所有在你完成打开图像之后)。像这样:
for frame in camera.capture_continuous(stream, format = "jpeg", use_video_port = True):
stream.seek(0)
image = Image.open(stream)
#Do stuff with image
stream.seek(0)
stream.truncate()
基本上,当您打开图像并对其进行一些操作时,BytesIO 的指针可以四处移动并最终到达零位置以外的其他位置。之后,当您调用 truncate(0) 时,它不会像我想的那样将指针移回零(对我来说,将指针移回发生截断的位置似乎是合乎逻辑的)。当代码再次运行时,捕获写入流中,但这次它没有从头开始写入,之后一切都中断了。
希望这可以帮助将来的人:)
推荐阅读
- monitoring - 是否可以使用移动平均法在 Prometheus Alertmanager 上创建规则?
- react-native - 在 windows 和 expo 上编写 e2e 测试的最佳方法是什么
- php - Filemaker API 是否为 _find 请求或 portalData 请求实现缓存?
- html - WhatsApp 不显示网站的图像缩略图
- javascript - 导出不同文件中不同路由的实际功能
- python - 如何使用 pytest 基于服务器输出测试客户端-服务器交互?
- r - 根据另一个数据帧上的键值重新编码变量
- java - 如何将 3rd 方 JAR 添加到 Maven 项目
- python - 如何从熊猫数据框中只选择几列
- assembly - 在汇编Linux中将浮点值打印到STDOUT