How to save an image read via camera.capture_continuous (format rgb) and save it to a file

Question:

I read the raspi camera via camera.capture_continuous(stream,format='rgb', use_video_port=True, resize=(width, height) to feed it to the Coral Edge USB Accelerator. This works perfectly. But now I want to save certain images (depending on the analysis) to the harddrive.

I’m a python beginner… file.write didn’t work. I assume it is because I get some kind of raw rgb image data and not a jpg.

I’d like to be able to store the image as jpg. Can anyone suggest what function to use?

Update:


I tried the following

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")

But only got an error:

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

what am I doing wrong?

Asked By: Michael

||

Answers:

You can use the Pillow library to save images to disk. Something like:

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')
Answered By: Inquisitive

Solved it with the following line

image = Image.frombuffer('RGB', (width,height), streamValue)
Answered By: Michael