How to save captured image to disk, using Pygame
Question:
This is my code, which starts the webcam :
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print "Using camera %s ..." % cameras[0]
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()
I want to know how to capture an image and store it to the current directory. Please suggest the changes required.
Answers:
When you call webcam.get_image it returns an RGB Surface. So just call pygame.image.save(), the file type is determined by the extension and defaults to TGA. Options are BMP, TGA, PNG, and JPEG. In this case you could append this line to your file.
pygame.image.save(img, "image.jpg")
Check out http://www.pygame.org/docs/ref/image.html and http://www.pygame.org/docs/ref/camera.html
If the saved image is black it may be cause there is no delay between starting and capturing the image.
delay the pygame so that camera could properly capture the image and then capture the image.
pygame.time.delay(1000)
webcam.get_image()
This is my code, which starts the webcam :
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print "Using camera %s ..." % cameras[0]
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()
I want to know how to capture an image and store it to the current directory. Please suggest the changes required.
When you call webcam.get_image it returns an RGB Surface. So just call pygame.image.save(), the file type is determined by the extension and defaults to TGA. Options are BMP, TGA, PNG, and JPEG. In this case you could append this line to your file.
pygame.image.save(img, "image.jpg")
Check out http://www.pygame.org/docs/ref/image.html and http://www.pygame.org/docs/ref/camera.html
If the saved image is black it may be cause there is no delay between starting and capturing the image.
delay the pygame so that camera could properly capture the image and then capture the image.
pygame.time.delay(1000)
webcam.get_image()