3

I want to get an image from the pi camera module and use the pillow imaging library to modify the image. The way I have been doing it up to now is to take a picture with the camera and then open that file using:

from PIL import Image

Im = Image.open("the file path")

That has worked well, but I don't want to save the image until I have modified it. is there a way of doing:

Im = camera.capture() #where Im is a PIL image

print(Im.width) # or any other PIL.Image property / method

Thanks

  • For any particular reason? If it's to reduce SD card wear then save the file to a small RAM disc initially. – joan Aug 11 '15 at 22:20
  • I thought it would be quicker. I have to take a lot of images and writing each one to disk ,and then reading it back into memory seems like a waste of time. – Jonathan Aug 12 '15 at 7:20
  • A RAM disk is just memory, and will minimise the overhead, plus it'll save wear and tear on the SD card. – joan Aug 12 '15 at 7:21
  • 1
    There's a recipe precisely for that in the docs (uses an in-memory stream and opens the result in PIL) – Dave Jones Aug 12 '15 at 17:35
6

From the picamera docs (Section 4.3. Capturing to a PIL Image):

import io
import time
import picamera
from PIL import Image

# Create the in-memory stream
stream = io.BytesIO()
with picamera.PiCamera() as camera:
    camera.start_preview()
    time.sleep(2)
    camera.capture(stream, format='jpeg')
# "Rewind" the stream to the beginning so we can read its content
stream.seek(0)
image = Image.open(stream)
0

Another way i do it is with OpenCv, you can also modify images with OpenCv such as draw images,

import cv2
import numpy as np
from PIL import Image

def cv2_to_pil(img): #Since you want to be able to use Pillow (PIL)
    return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

def pil_to_cv2(img):
    return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)

cam = cv2.VideoCapture(0) #Define the camera, 0 is which camera, if you have more than 1
ret_val, img = cam.read() #cam.read() returns ret (0/1 if the camera is working) and img, 
#the actual image of the camera in a numpy array

cv2.imshow("Camera", img) #if you wanted to open a window to see this picture
cv2.waitKey(0) #waits for the enter key to continue, change to
#0 to X milliseconds to stop for a certain amount of time.

pil_img = cv2_to_pil(img) #convert the image to PIL so you can use it that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.