7. API Reference

This package primarily provides the PiCamera class which is a pure Python interface to the Raspberry Pi’s camera module.

7.1. PiCamera

class picamera.PiCamera

Provides a pure Python interface to the Raspberry Pi’s camera module.

Upon construction, this class initializes the camera. As there is only a single camera supported by the Raspberry Pi, this means that only a single instance of this class can exist at any given time (it is effectively a singleton class although it is not implemented as such).

No preview or recording is started automatically upon construction. Use the capture() method to capture images, the start_recording() method to begin recording video, or the start_preview() method to start live display of the camera’s input.

Several attributes are provided to adjust the camera’s configuration. Some of these can be adjusted while a recording is running, like brightness. Others, like resolution, can only be adjusted when the camera is idle.

When you are finished with the camera, you should ensure you call the close() method to release the camera resources (failure to do this leads to GPU memory leaks):

camera = PiCamera()
try:
    # do something with the camera
    pass
finally:
    camera.close()

The class supports the context manager protocol to make this particularly easy (upon exiting the with statement, the close() method is automatically called):

with PiCamera() as camera:
    # do something with the camera
    pass
capture(output, format=None, use_video_port=False, resize=None, **options)

Capture an image from the camera, storing it in output.

If output is a string, it will be treated as a filename for a new file which the image will be written to. Otherwise, output is assumed to a be a file-like object and the image data is appended to it (the implementation only assumes the object has a write() method - no other methods will be called).

If format is None (the default), the method will attempt to guess the required image format from the extension of output (if it’s a string), or from the name attribute of output (if it has one). In the case that the format cannot be determined, a PiCameraValueError will be raised.

If format is not None, it must be a string specifying the format that you want the image written to. The format can be a MIME-type or one of the following strings:

  • 'jpeg' - Write a JPEG file
  • 'png' - Write a PNG file
  • 'gif' - Write a GIF file
  • 'bmp' - Write a Windows bitmap file
  • 'yuv' - Write the raw image data to a file in YUV420 format
  • 'rgb' - Write the raw image data to a file in 24-bit RGB format
  • 'rgba' - Write the raw image data to a file in 32-bit RGBA format
  • 'raw' - Deprecated option for raw captures; the format is taken from the deprecated raw_format attribute

The use_video_port parameter controls whether the camera’s image or video port is used to capture images. It defaults to False which means that the camera’s image port is used. This port is slow but produces better quality pictures. If you need rapid capture up to the rate of video frames, set this to True.

If resize is not None (the default), it must be a two-element tuple specifying the width and height that the image should be resized to.

Certain file formats accept additional options which can be specified as keyword arguments. Currently, only the 'jpeg' encoder accepts additional options, which are:

  • quality - Defines the quality of the JPEG encoder as an integer ranging from 1 to 100. Defaults to 85.
  • thumbnail - Defines the size and quality of the thumbnail to embed in the Exif data. Specifying None disables thumbnail generation. Otherwise, specify a tuple of (width, height, quality). Defaults to (64, 48, 35).

Changed in version 1.0: The resize parameter was added, and raw capture formats can now be specified directly

capture_continuous(output, format=None, use_video_port=False, resize=None, **options)

Capture images continuously from the camera as an infinite iterator.

This method returns an infinite iterator of images captured continuously from the camera. If output is a string, each captured image is stored in a file named after output after substitution of two values with the format() method. Those two values are:

  • {counter} - a simple incrementor that starts at 1 and increases by 1 for each image taken
  • {timestamp} - a datetime instance

The table below contains several example values of output and the sequence of filenames those values could produce:

output Value Filenames Notes
'image{counter}.jpg' image1.jpg, image2.jpg, image3.jpg, ...  
'image{counter:02d}.jpg' image01.jpg, image02.jpg, image03.jpg, ...  
'image{timestamp}.jpg' image2013-10-05 12:07:12.346743.jpg, image2013-10-05 12:07:32.498539, ...
'image{timestamp:%H-%M-%S-%f}.jpg' image12-10-02-561527.jpg, image12-10-14-905398.jpg  
'{timestamp:%H%M%S}-{counter:03d}.jpg' 121002-001.jpg, 121013-002.jpg, 121014-003.jpg, ...
  1. Note that because timestamp’s default output includes colons (:), the resulting filenames are not suitable for use on Windows. For this reason (and the fact the default contains spaces) it is strongly recommended you always specify a format when using {timestamp}.
  2. You can use both {timestamp} and {counter} in a single format string (multiple times too!) although this tends to be redundant.

If output is not a string, it is assumed to be a file-like object and each image is simply written to this object sequentially. In this case you will likely either want to write something to the object between the images to distinguish them, or clear the object between iterations.

The format, use_video_port, resize, and options parameters are the same as in capture().

For example, to capture 60 images with a one second delay between them, writing the output to a series of JPEG files named image01.jpg, image02.jpg, etc. one could do the following:

import time
import picamera
with picamera.PiCamera() as camera:
    camera.start_preview()
    try:
        for i, filename in enumerate(camera.capture_continuous('image{counter:02d}.jpg')):
            print(filename)
            time.sleep(1)
            if i == 59:
                break
    finally:
        camera.stop_preview()

Alternatively, to capture JPEG frames as fast as possible into an in-memory stream, performing some processing on each stream until some condition is satisfied:

import io
import time
import picamera
with picamera.PiCamera() as camera:
    stream = io.BytesIO()
    for foo in camera.capture_continuous(stream, format='jpeg'):
        # Truncate the stream to the current position (in case
        # prior iterations output a longer image)
        stream.truncate()
        stream.seek(0)
        if process(stream):
            break

Changed in version 1.0: The resize parameter was added, and raw capture formats can now be specified directly

capture_sequence(outputs, format='jpeg', use_video_port=False, resize=None, **options)

Capture a sequence of consecutive images from the camera.

This method accepts a sequence or iterator of outputs each of which must either be a string specifying a filename for output, or a file-like object with a write method. For each item in the sequence or iterator of outputs, the camera captures a single image as fast as it can.

The format, use_video_port, resize, and options parameters are the same as in capture(), but format defaults to 'jpeg'. The format is not derived from the filenames in outputs by this method.

For example, to capture 3 consecutive images:

import time
import picamera
with picamera.PiCamera() as camera:
    camera.start_preview()
    time.sleep(2)
    camera.capture_sequence([
        'image1.jpg',
        'image2.jpg',
        'image3.jpg',
        ])
    camera.stop_preview()

If you wish to capture a large number of images, a list comprehension or generator expression can be used to construct the list of filenames to use:

import time
import picamera
with picamera.PiCamera() as camera:
    camera.start_preview()
    time.sleep(2)
    camera.capture_sequence([
        'image%02d.jpg' % i
        for i in range(100)
        ])
    camera.stop_preview()

More complex effects can be obtained by using a generator function to provide the filenames or output objects.

Changed in version 1.0: The resize parameter was added, and raw capture formats can now be specified directly

close()

Finalizes the state of the camera.

After successfully constructing a PiCamera object, you should ensure you call the close() method once you are finished with the camera (e.g. in the finally section of a try..finally block). This method stops all recording and preview activities and releases all resources associated with the camera; this is necessary to prevent GPU memory leaks.

split_recording(output)

Continue the recording in the specified output; close existing output.

When called, the video encoder will wait for the next appropriate split point (an inline SPS header), then will cease writing to the current output (and close it, if it was specified as a filename), and continue writing to the newly specified output.

If output is a string, it will be treated as a filename for a new file which the video will be written to. Otherwise, output is assumed to be a file-like object and the video data is appended to it (the implementation only assumes the object has a write() method - no other methods will be called).

Note that unlike start_recording(), you cannot specify format or options as these cannot be changed in the middle of recording. Only the new output can be specified. Furthermore, the format of the recording is currently limited to H264, inline_headers must be True, and bitrate must be non-zero (CBR mode) when start_recording() is called (this is the default).

start_preview()

Displays the preview window.

This method starts a new preview running at the configured resolution (see resolution). Most camera properties can be modified “live” while the preview is running (e.g. brightness). The preview typically overrides whatever is currently visible on the display. To stop the preview and reveal the display again, call stop_preview(). The preview can be started and stopped multiple times during the lifetime of the PiCamera object.

start_recording(output, format=None, resize=None, **options)

Start recording video from the camera, storing it in output.

If output is a string, it will be treated as a filename for a new file which the video will be written to. Otherwise, output is assumed to be a file-like object and the video data is appended to it (the implementation only assumes the object has a write() method - no other methods will be called).

If format is None (the default), the method will attempt to guess the required video format from the extension of output (if it’s a string), or from the name attribute of output (if it has one). In the case that the format cannot be determined, a PiCameraValueError will be raised.

If format is not None, it must be a string specifying the format that you want the image written to. The format can be a MIME-type or one of the following strings:

  • 'h264' - Write an H.264 video stream
  • 'mjpeg' - Write an M-JPEG video stream

If resize is not None (the default), it must be a two-element tuple specifying the width and height that the video recording should be resized to. This is particularly useful for recording video using the full area of the camera sensor (which is not possible without down-sizing the output).

Certain formats accept additional options which can be specified as keyword arguments. The 'h264' format accepts the following additional options:

  • profile - The H.264 profile to use for encoding. Defaults to ‘high’, but can be one of ‘baseline’, ‘main’, ‘high’, or ‘constrained’.
  • intra_period - The key frame rate (the rate at which I-frames are inserted in the output). Defaults to 0, but can be any positive 32-bit integer value representing the number of frames between successive I-frames.
  • inline_headers - When True, specifies that the encoder should output SPS/PPS headers within the stream to ensure GOPs (groups of pictures) are self describing. This is important for streaming applications where the client may wish to seek within the stream, and enables the use of split_recording(). Defaults to True if not specified.

All formats accept the following additional options:

  • bitrate - The bitrate at which video will be encoded. Defaults to 17000000 (17Mbps) if not specified. A value of 0 implies VBR (variable bitrate) encoding. The maximum value is 25000000 (25Mbps).

  • quantization - When bitrate is zero (for variable bitrate encodings), this parameter specifies the quality that the encoder should attempt to maintain.

    For the 'h264' format, use values between 10 and 40 where 10 is extremely high quality, and 40 is extremely low (20-25 is usually a reasonable range for H.264 encoding). Note that split_recording() cannot be used in VBR mode.

Changed in version 1.0: The resize parameter was added, and 'mjpeg' was added as a recording format

stop_preview()

Closes the preview window display.

If start_preview() has previously been called, this method shuts down the preview display which generally results in the underlying TTY becoming visible again. If a preview is not currently running, no exception is raised - the method will simply do nothing.

stop_recording()

Stop recording video from the camera.

After calling this method the video encoder will be shut down and output will stop being written to the file-like object specified with start_recording(). If an error occurred during recording and wait_recording() has not been called since the error then this method will raise the exception.

wait_recording(timeout=0)

Wait on the video encoder for timeout seconds.

It is recommended that this method is called while recording to check for exceptions. If an error occurs during recording (for example out of disk space), an exception will only be raised when the wait_recording() or stop_recording() methods are called.

If timeout is 0 (the default) the function will immediately return (or raise an exception if an error has occurred).

ISO

Retrieves or sets the apparent ISO setting of the camera.

When queried, the ISO property returns the ISO setting of the camera, a value which represents the sensitivity of the camera to light. Lower ISO speeds (e.g. 100) imply less sensitivity than higher ISO speeds (e.g. 400 or 800). Lower sensitivities tend to produce less “noisy” (smoother) images, but operate poorly in low light conditions.

When set, the property adjusts the sensitivity of the camera. Valid values are between 0 (auto) and 800. The actual value used when ISO is explicitly set will be one of the following values (whichever is closest): 100, 200, 320, 400, 500, 640, 800.

ISO can be adjusted while previews or recordings are in progress. The default value is 0 which means the ISO is automatically set according to image-taking conditions.

Note

With ISO settings other than 0 (auto), the exposure_mode property becomes non-functional.

awb_mode

Retrieves or sets the auto-white-balance mode of the camera.

When queried, the awb_mode property returns a string representing the auto-white-balance setting of the camera. The possible values can be obtained from the PiCamera.AWB_MODES attribute.

When set, the property adjusts the camera’s auto-white-balance mode. The property can be set while recordings or previews are in progress. The default value is 'auto'.

brightness

Retrieves or sets the brightness setting of the camera.

When queried, the brightness property returns the brightness level of the camera as an integer between 0 and 100. When set, the property adjusts the brightness of the camera. Brightness can be adjusted while previews or recordings are in progress. The default value is 50.

closed

Returns True if the close() method has been called.

color_effects

Retrieves or sets the current color effect applied by the camera.

When queried, the color_effects property either returns None which indicates that the camera is using normal color settings, or a (u, v) tuple where u and v are integer values between 0 and 255.

When set, the property changes the color effect applied by the camera. The property can be set while recordings or previews are in progress. For example, to make the image black and white set the value to (128, 128). The default value is None.

contrast

Retrieves or sets the contrast setting of the camera.

When queried, the contrast property returns the contrast level of the camera as an integer between -100 and 100. When set, the property adjusts the contrast of the camera. Contrast can be adjusted while previews or recordings are in progress. The default value is 0.

crop

Retrieves or sets the crop applied to the camera’s input.

When queried, the crop property returns a (x, y, w, h) tuple of floating point values ranging from 0.0 to 1.0, indicating the proportion of the image to include in the output (the “Region of Interest” or ROI). The default value is (0.0, 0.0, 1.0, 1.0) which indicates that everything should be included. The property can be set while recordings or previews are in progress.

exif_tags

Holds a mapping of the Exif tags to apply to captured images.

Note

Please note that Exif tagging is only supported with the jpeg format.

By default several Exif tags are automatically applied to any images taken with the capture() method: IFD0.Make (which is set to RaspberryPi), IFD0.Model (which is set to RP_OV5647), and three timestamp tags: IFD0.DateTime, EXIF.DateTimeOriginal, and EXIF.DateTimeDigitized which are all set to the current date and time just before the picture is taken.

If you wish to set additional Exif tags, or override any of the aforementioned tags, simply add entries to the exif_tags map before calling capture(). For example:

camera.exif_tags['IFD0.Copyright'] = 'Copyright (c) 2013 Foo Industries'

The Exif standard mandates ASCII encoding for all textual values, hence strings containing non-ASCII characters will cause an encoding error to be raised when capture() is called. If you wish to set binary values, use a bytes() value:

camera.exif_tags['EXIF.UserComment'] = b'Something containing\x00NULL characters'

Warning

Binary Exif values are currently ignored; this appears to be a libmmal or firmware bug.

You may also specify datetime values, integer, or float values, all of which will be converted to appropriate ASCII strings (datetime values are formatted as YYYY:MM:DD HH:MM:SS in accordance with the Exif standard).

The currently supported Exif tags are:

Group Tags
IFD0, IFD1 ImageWidth, ImageLength, BitsPerSample, Compression, PhotometricInterpretation, ImageDescription, Make, Model, StripOffsets, Orientation, SamplesPerPixel, RowsPerString, StripByteCounts, Xresolution, Yresolution, PlanarConfiguration, ResolutionUnit, TransferFunction, Software, DateTime, Artist, WhitePoint, PrimaryChromaticities, JPEGInterchangeFormat, JPEGInterchangeFormatLength, YcbCrCoefficients, YcbCrSubSampling, YcbCrPositioning, ReferenceBlackWhite, Copyright
EXIF ExposureTime, FNumber, ExposureProgram, SpectralSensitivity, ISOSpeedRatings, OECF, ExifVersion, DateTimeOriginal, DateTimeDigitized, ComponentsConfiguration, CompressedBitsPerPixel, ShutterSpeedValue, ApertureValue, BrightnessValue, ExposureBiasValue, MaxApertureValue, SubjectDistance, MeteringMode, LightSource, Flash, FocalLength, SubjectArea, MakerNote, UserComment, SubSecTime, SubSecTimeOriginal, SubSecTimeDigitized, FlashpixVersion, ColorSpace, PixelXDimension, PixelYDimension, RelatedSoundFile, FlashEnergy, SpacialFrequencyResponse, FocalPlaneXResolution, FocalPlaneYResolution, FocalPlaneResolutionUnit, SubjectLocation, ExposureIndex, SensingMethod, FileSource, SceneType, CFAPattern, CustomRendered, ExposureMode, WhiteBalance, DigitalZoomRatio, FocalLengthIn35mmFilm, SceneCaptureType, GainControl, Contrast, Saturation, Sharpness, DeviceSettingDescription, SubjectDistanceRange, ImageUniqueID
GPS GPSVersionID, GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, GPSLongitude, GPSAltitudeRef, GPSAltitude, GPSTimeStamp, GPSSatellites, GPSStatus, GPSMeasureMode, GPSDOP, GPSSpeedRef, GPSSpeed, GPSTrackRef, GPSTrack, GPSImgDirectionRef, GPSImgDirection, GPSMapDatum, GPSDestLatitudeRef, GPSDestLatitude, GPSDestLongitudeRef, GPSDestLongitude, GPSDestBearingRef, GPSDestBearing, GPSDestDistanceRef, GPSDestDistance, GPSProcessingMethod, GPSAreaInformation, GPSDateStamp, GPSDifferential
EINT InteroperabilityIndex, InteroperabilityVersion, RelatedImageFileFormat, RelatedImageWidth, RelatedImageLength
exposure_compensation

Retrieves or sets the exposure compensation level of the camera.

When queried, the exposure_compensation property returns an integer value between -25 and 25 indicating the exposure level of the camera. Larger values result in brighter images.

When set, the property adjusts the camera’s exposure compensation level. The property can be set while recordings or previews are in progress. The default value is 0.

exposure_mode

Retrieves or sets the exposure mode of the camera.

When queried, the exposure_mode property returns a string representing the exposure setting of the camera. The possible values can be obtained from the PiCamera.EXPOSURE_MODES attribute.

When set, the property adjusts the camera’s exposure mode. The property can be set while recordings or previews are in progress. The default value is 'auto'.

frame

Retrieves information about the current frame recorded from the camera.

When video recording is active (after a call to start_recording()), this attribute will return a PiVideoFrame tuple containing information about the current frame that the camera is recording. Querying this property when the camera is not recording will result in an exception.

Note

There is a small window of time when querying this attribute will return None after calling start_recording(). If this attribute returns None, this means that the video encoder has been initialized, but the camera has not yet returned any frames.

framerate

Retrieves or sets the framerate at which video-port based image captures, video recordings, and previews will run.

When queried, the framerate property returns the rate at which the camera’s video and preview ports will operate as a tuple of (numerator, denominator). The true framerate can be calculated as numerator / denominator.

When set, the property reconfigures the camera so that the next call to recording and previewing methods will use the new framerate. The framerate can be specified as a (numerator, denominator) tuple, or as a simple integer. The camera must not be closed, and no recording must be active when the property is set.

The property defaults to 30fps, except when the resolution property is set to 2592x1944 (the maximum resolution of the camera). At the maximum resolution, framerate is automatically limited to 15fps. Attempting to set higher rates will result in a PiCameraValueError.

hflip

Retrieves or sets whether the camera’s output is horizontally flipped.

When queried, the hflip property returns a boolean indicating whether or not the camera’s output is horizontally flipped. The property can be set while recordings or previews are in progress. The default value is False.

image_effect

Retrieves or sets the current image effect applied by the camera.

When queried, the image_effect property returns a string representing the effect the camera will apply to captured video. The possible values can be obtained from the PiCamera.IMAGE_EFFECTS attribute.

When set, the property changes the effect applied by the camera. The property can be set while recordings or previews are in progress, but only certain effects work while recording video (notably 'negative' and 'solarize'). The default value is 'none'.

led

Sets the state of the camera’s LED via GPIO.

If a GPIO library is available (only RPi.GPIO is currently supported), and if the python process has the necessary privileges (typically this means running as root via sudo), this property can be used to set the state of the camera’s LED as a boolean value (True is on, False is off).

Note

This is a write-only property. While it can be used to control the camera’s LED, you cannot query the state of the camera’s LED using this property.

meter_mode

Retrieves or sets the metering mode of the camera.

When queried, the meter_mode property returns the method by which the camera determines the exposure as one of the following strings:

Value Description
'average' The camera measures the average of the entire scene.
'spot' The camera measures the center of the scene.
'backlit' The camera measures a larger central area, ignoring the edges of the scene.
'matrix' The camera measures several points within the scene.

When set, the property adjusts the camera’s metering mode. The property can be set while recordings or previews are in progress. The default value is 'average'. All possible values for the attribute can be obtained from the PiCamera.METER_MODES attribute.

preview_alpha

Retrieves or sets the opacity of the preview window.

When queried, the preview_alpha property returns a value between 0 and 255 indicating the opacity of the preview window, where 0 is completely transparent and 255 is completely opaque. The default value is 255. The property can be set while recordings or previews are in progress.

Note

If the preview is not running, the property will not reflect changes to it, but they will be in effect next time the preview is started. In other words, you can set preview_alpha to 128, but querying it will still return 255 (the default) until you call start_preview() at which point the preview will appear semi-transparent and preview_alpha will suddenly return 128. This appears to be a firmware issue.

preview_fullscreen

Retrieves or sets full-screen for the preview window.

The preview_fullscreen property is a bool which controls whether the preview window takes up the entire display or not. When set to False, the preview_window property can be used to control the precise size of the preview display. The property can be set while recordings or previews are active.

Note

The preview_fullscreen attribute is afflicted by the same issue as preview_alpha with regards to changes while the preview is not running.

preview_layer

Retrieves of sets the layer of the preview window.

The preview_layer property is an integer which controls the layer that the preview window occupies. It defaults to 2 which results in the preview appearing above all other output.

Warning

Operation of this attribute is not yet fully understood. The documentation above is incomplete and may be incorrect!

preview_window

Retrieves or sets the size of the preview window.

When the preview_fullscreen property is set to False, the preview_window property specifies the size and position of the preview window on the display. The property is a 4-tuple consisting of (x, y, width, height). The property can be set while recordings or previews are active.

Note

The preview_window attribute is afflicted by the same issue as preview_alpha with regards to changes while the preview is not running.

previewing

Returns True if the start_preview() method has been called, and no stop_preview() call has been made yet.

raw_format

Retrieves or sets the raw format of the camera’s ports.

Deprecated since version 1.0: Please use 'yuv' or 'rgb' directly as a format in the various capture methods instead.

recording

Returns True if the start_recording() method has been called, and no stop_recording() call has been made yet.

resolution

Retrieves or sets the resolution at which image captures, video recordings, and previews will be captured.

When queried, the resolution property returns the resolution at which the camera will operate as a tuple of (width, height) measured in pixels. This is the resolution that the capture() method will produce images at, the resolution that start_recording() will produce videos at, and the resolution that start_preview() will capture frames at.

When set, the property reconfigures the camera so that the next call to these methods will use the new resolution. The resolution must be specified as a (width, height) tuple, the camera must not be closed, and no recording must be active when the property is set.

The property defaults to the Pi’s currently configured display resolution.

Note

Setting the resolution to 2592x1944 (the maximum) will automatically cause previews to run at a reduced frame rate of 15fps (resolutions below use 30fps). This is due to GPU processing limits.

rotation

Retrieves or sets the current rotation of the camera’s image.

When queried, the rotation property returns the rotation applied to the image. Valid values are 0, 90, 180, and 270.

When set, the property changes the color effect applied by the camera. The property can be set while recordings or previews are in progress. The default value is 0.

saturation

Retrieves or sets the saturation setting of the camera.

When queried, the saturation property returns the color saturation of the camera as an integer between -100 and 100. When set, the property adjusts the saturation of the camera. Saturation can be adjusted while previews or recordings are in progress. The default value is 0.

sharpness

Retrieves or sets the sharpness setting of the camera.

When queried, the sharpness property returns the sharpness level of the camera (a measure of the amount of post-processing to reduce or increase image sharpness) as an integer between -100 and 100. When set, the property adjusts the sharpness of the camera. Sharpness can be adjusted while previews or recordings are in progress. The default value is 0.

shutter_speed

Retrieves or sets the shutter speed of the camera in microseconds.

When queried, the shutter_speed property returns the shutter speed of the camera in microseconds, or 0 which indicates that the speed will be automatically determined according to lighting conditions. Faster shutter times naturally require greater amounts of illumination and vice versa.

When set, the property adjusts the shutter speed of the camera, which most obviously affects the illumination of subsequently captured images. Shutter speed can be adjusted while previews or recordings are running. The default value is 0 (auto).

vflip

Retrieves or sets whether the camera’s output is vertically flipped.

When queried, the vflip property returns a boolean indicating whether or not the camera’s output is vertically flipped. The property can be set while recordings or previews are in progress. The default value is False.

video_stabilization

Retrieves or sets the video stabilization mode of the camera.

When queried, the video_stabilization property returns a boolean value indicating whether or not the camera attempts to compensate for motion.

When set, the property activates or deactivates video stabilization. The property can be set while recordings or previews are in progress. The default value is False.

Note

The built-in video stabilization only accounts for vertical and horizontal motion, not rotation.

7.2. PiCameraCircularIO

class picamera.PiCameraCircularIO(camera, size=None, seconds=None, bitrate=17000000)

A derivative of CircularIO which tracks camera frames.

PiCameraCircularIO provides an in-memory stream based on a ring buffer. It is a specialization of CircularIO which associates video frame meta-data with the recorded stream, accessible from the frames property.

Warning

The class makes a couple of assumptions which will cause the frame meta-data tracking to break if they are not adhered to:

  • the stream is only ever appended to - no writes ever start from the middle of the stream
  • the stream is never truncated (from the right; being ring buffer based, left truncation will occur automatically)

The camera parameter specifies the PiCamera instance that will be recording video to the stream. If specified, the size parameter determines the maximum size of the stream in bytes. If size is not specified (or None), then seconds must be specified instead. This provides the maximum length of the stream in seconds, assuming a data rate in bits-per-second given by the bitrate parameter (which defaults to 17000000, or 17Mbps, which is also the default bitrate used for video recording by PiCamera). You cannot specify both size and seconds.

frames

Returns an iterator over the frame meta-data.

As the camera records video to the stream, the class captures the meta-data associated with each frame (in the form of a PiVideoFrame tuple), discarding meta-data for frames which are no longer fully stored within the underlying ring buffer. You can use the frame meta-data to locate, for example, the first keyframe present in the stream in order to determine an appropriate range to extract.

7.3. CircularIO

class picamera.CircularIO(size)

A thread-safe stream which uses a ring buffer for storage.

CircularIO provides an in-memory stream similar to the io.BytesIO class. However, unlike BytesIO its underlying storage is a ring buffer with a fixed maximum size. Once the maximum size is reached, writing effectively loops round to the beginning to the ring and starts overwriting the oldest content.

The size parameter specifies the maximum size of the stream in bytes. The read(), tell(), and seek() methods all operate equivalently to those in io.BytesIO whilst write() only differs in the wrapping behaviour described above. A read1() method is also provided for efficient reading of the underlying ring buffer in write-sized chunks (or less).

A re-entrant threading lock guards all operations, and is accessible for external use via the lock attribute.

The performance of the class is geared toward faster writing than reading on the assumption that writing will be the common operation and reading the rare operation (a reasonable assumption for the camera use-case, but not necessarily for more general usage).

getvalue()

Return bytes containing the entire contents of the buffer.

read(n=-1)

Read up to n bytes from the stream and return them. As a convenience, if n is unspecified or -1, readall() is called. Fewer than n bytes may be returned if there are fewer than n bytes from the current stream position to the end of the stream.

If 0 bytes are returned, and n was not 0, this indicates end of the stream.

read1(n=-1)

Read up to n bytes from the stream using only a single call to the underlying object.

In the case of CircularIO this roughly corresponds to returning the content from the current position up to the end of the write that added that content to the stream (assuming no subsequent writes overwrote the content). read1() is particularly useful for efficient copying of the stream’s content.

readable()

Returns True, indicating that the stream supports read().

seek(offset, whence=0)

Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. Values for whence are:

  • SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
  • SEEK_CUR or 1 – current stream position; offset may be negative
  • SEEK_END or 2 – end of the stream; offset is usually negative

Return the new absolute position.

seekable()

Returns True, indicating the stream supports seek() and tell().

tell()

Return the current stream position.

truncate(size=None)

Resize the stream to the given size in bytes (or the current position if size is not specified). This resizing can extend or reduce the current stream size. In case of extension, the contents of the new file area will be NUL (\x00) bytes. The new stream size is returned.

The current stream position isn’t changed unless the resizing is expanding the stream, in which case it may be set to the maximum stream size if the expansion causes the ring buffer to loop around.

writable()

Returns True, indicating that the stream supports write().

write(b)

Write the given bytes or bytearray object, b, to the underlying stream and return the number of bytes written.

lock

A re-entrant threading lock which is used to guard all operations.

size

Return the maximum size of the buffer in bytes.

7.4. PiVideoFrame

class picamera.PiVideoFrame(index, key, frame_size, video_size, split_size, timestamp)
index

Returns the zero-based number of the frame. This is a monotonic counter that is simply incremented every time the camera returns a frame-end buffer. As a consequence, this attribute cannot be used to detect dropped frames.

position

Returns the zero-based position of the frame in the stream containing it.

keyframe

Returns a bool indicating whether the current frame is a keyframe (an intra-frame, or I-frame in MPEG parlance).

frame_size

Returns the size in bytes of the current frame.

video_size

Returns the size in bytes of the entire video up to the current frame. Note that this is unlikely to match the size of the actual file/stream written so far. Firstly this is because the frame attribute is only updated when the encoder outputs the end of a frame, which will cause the reported size to be smaller than the actual amount written. Secondly this is because a stream may utilize buffering which will cause the actual amount written (e.g. to disk) to lag behind the value reported by this attribute.

split_size

Returns the size in bytes of the video recorded since the last call to either start_recording() or split_recording(). For the reasons explained above, this may differ from the size of the actual file/stream written so far.

timestamp

Returns the presentation timestamp (PTS) of the current frame as reported by the encoder. This is represented by the number of microseconds (millionths of a second) since video recording started. As the frame attribute is only updated when the encoder outputs the end of a frame, this value may lag behind the actual time since start_recording() was called.

Warning

Currently, the video encoder occasionally returns “time unknown” values in this field which picamera represents as None. If you are querying this property you will need to check the value is not None before using it.

header

Contains a bool indicating whether the current frame is actually an SPS/PPS header. Typically it is best to split an H.264 stream so that it starts with an SPS/PPS header.

7.5. Exceptions

exception picamera.PiCameraError

Base class for PiCamera errors

exception picamera.PiCameraValueError

Raised when an invalid value is fed to a PiCamera object

exception picamera.PiCameraRuntimeError

Raised when an invalid sequence of operations is attempted with a PiCamera object