1 min read

Image Capturing from WebCAM using OpenCV and Pygame in Python

I know there a lot of examples of WebCAM image capturing on the net. Mine is one of that but the main difference is that this little script here simply captures frames in a certain fps and simply saves those images. There numerous usages for such a thing. One usage could be a script that uploads this image to a certain FTP site so you can display it on your web page. I needed this little script to follow a moving object. I did not write the whole script. You may think this as a little upgrade from the one on the internet. The script uses OpenCV and Pygame libs. Without further ado the script :

import pygame
import Image
from pygame.locals import *
import sys

import opencv
import cv

#this is important for capturing/displaying images
from opencv import highgui

camera = highgui.cvCreateCameraCapture(0)
i=0
def get_image():
    im = highgui.cvQueryFrame(camera)
    # Add the line below if you need it (Ubuntu 8.04+)
    #im = opencv.cvGetMat(im)
    #convert Ipl image to PIL image
    return opencv.adaptors.Ipl2PIL(im)

fps = 25.0
pygame.init()
window = pygame.display.set_mode((640,480))
pygame.display.set_caption("WebCAM Demo")
screen = pygame.display.get_surface()

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == QUIT or event.type == KEYDOWN:
            sys.exit(0)
    im = get_image()
    if i>100:
	#allowing the camera to focus
	#auto focus is really annoying
        im.save("image_"+str(i)+"", "JPEG")
    i=i+1
    pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)

    screen.blit(pg_img, (0,0))
    pygame.display.flip()
    pygame.time.delay(int(1000 * 1.0/fps))