Search code examples
pythonraspberry-piwebcamraspberry-pi3

how to run webcam through python on rpi3


I am trying to use a MS lifecam with my raspberry-pi-3. It works on the command line, when I type the following command:

$ fswebcam img.jpg
Trying source module v4l2...
/dev/video0 opened.
...
Writing JPEG image to 'img.jpg'  # this works fine

Now I want to run the camera through a python code:

import pygame
import pygame.camera
from pygame.locals import *
DEVICE = '/dev/video0'
SIZE = (640, 480)  # I also tried with img size (384,288), same error
FILENAME = 'capture.jpg'
pygame.init()
pygame.camera.init()
camera = pygame.camera.Camera(DEVICE, SIZE)
camera.start()   # error on executing this line
pygame.image.save(screen, FILENAME)
camera.stop()

The reported error is:

SystemError: ioctl(VIDIOC_S_FMT) failure: no supported formats

I am puzzled here. The camera is supported by rasp-pi, so it looks like my python code has to be updated somewhere. Can you help?


Solution

  • Try use this:

    camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
    camera.start()
    img = camera.get_image()
    pygame.image.save(img, FILENAME)