【问题标题】:How to save an image read via camera.capture_continuous (format rgb) and save it to a file如何保存通过camera.capture_continuous(格式rgb)读取的图像并将其保存到文件中
【发布时间】:2019-08-26 20:19:00
【问题描述】:

我通过 camera.capture_continuous(stream,format='rgb', use_video_port=True, resize=(width, height) 读取 raspi 相机以将其馈送到珊瑚边缘 USB 加速器。这非常有效。但现在我想要将某些图像(取决于分析)保存到硬盘。

我是 python 初学者... file.write 不起作用。我假设是因为我得到了某种原始 rgb 图像数据而不是 jpg。

我希望能够将图像存储为 jpg。谁能建议使用什么功能?

更新

我尝试了以下

import argparse
import os
import io
import time
from collections import deque
import numpy as np
import picamera
from PIL import Image
import edgetpu.classification.engine

def main():

  stream = io.BytesIO()
  engine = edgetpu.classification.engine.ClassificationEngine(args.model)

  for foo in camera.capture_continuous(stream,
                                       format='rgb',
                                       use_video_port=True,
                                       resize=(width, height)):
      stream.truncate()
      stream.seek(0)
      input = np.frombuffer(stream.getvalue(), dtype=np.uint8)
      results = engine.ClassifyWithInputTensor(input, top_k=3)

      ...

      image = Image.fromarray(input.astype('uint8'), 'RGB')
      image.save("imgs/image_" + str(i) + ".jpg")

但只报错:

Traceback (most recent call last):
  File "mio.py", line 85, in <module>
    main()
  File "mio.py", line 75, in main
    image = Image.fromarray(input.astype('uint8'), 'RGB')
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2529, in fromarray
    size = shape[1], shape[0]
IndexError: tuple index out of range

我做错了什么?

【问题讨论】:

  • 假设您正在录制 640x480 像素的 RGB 图像,并且您将一张 921,600 字节的图像保存到磁盘。您可以稍后使用 ImageMagick 轻松地将其转换为 JPEG 或 PNG,例如 convert -depth 8 -size 640x480 RGB:yourfile result.jpg
  • 什么是可能的——但如果可能的话,我更喜欢直接以正确的格式保存
  • 请确保您的代码具有所有必要的import 语句以及使其最小完成和可验证所需的一切,符合 StackOverflow 的要求。

标签: python python-3.x camera raspberry-pi google-coral


【解决方案1】:

您可以使用Pillow 库将图像保存到磁盘。比如:

pip install Pillow numpy

import numpy as np
from PIL import Image
pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 0]]])
image = Image.fromarray(pixels.astype('uint8'), 'RGB')
image.save('out.jpg')

【讨论】:

  • for foo in camera.capture_continuous(stream, format='rgb', use_video_port=True, resize=(w,h)): stream.truncate() stream.seek(0) input = np.frombuffer(stream.getvalue(), dtype=np.uint8) results = engine.ClassifyWithInputTensor(input, top_k=3) image = Image.fromarray(input.astype('uint8'), 'RGB') 导致以下错误:IndexError: tuple index out of range
  • 请添加此代码以及完整的回溯到问题末尾的“更新”标题。
  • 对不起.. 对我没有帮助.. 我读了 rgb 并写了从 rgb 创建图像.. 为什么它不能工作?
  • 很高兴您找到了解决方案 :) 您可以在此处将其作为答案发布并接受。如果将来对某人有帮助,他们会支持您的回答。
【解决方案2】:

用下面这行解决了

image = Image.frombuffer('RGB', (width,height), streamValue)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多