camera.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python
  2. # 1. Basic image capturing and displaying using the camera module
  3. import pygame
  4. import pygame.camera
  5. from pygame.locals import *
  6. class VideoCapturePlayer(object):
  7. size = ( 640, 480 )
  8. def __init__(self, **argd):
  9. self.__dict__.update(**argd)
  10. super(VideoCapturePlayer, self).__init__(**argd)
  11. # create a display surface. standard pygame stuff
  12. self.display = pygame.display.set_mode( self.size, 0 )
  13. self.init_cams(0)
  14. def init_cams(self, which_cam_idx):
  15. # gets a list of available cameras.
  16. self.clist = pygame.camera.list_cameras()
  17. print (self.clist)
  18. if not self.clist:
  19. raise ValueError("Sorry, no cameras detected.")
  20. try:
  21. cam_id = self.clist[which_cam_idx]
  22. except IndexError:
  23. cam_id = self.clist[0]
  24. # creates the camera of the specified size and in RGB colorspace
  25. self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")
  26. # starts the camera
  27. self.camera.start()
  28. self.clock = pygame.time.Clock()
  29. # create a surface to capture to. for performance purposes, you want the
  30. # bit depth to be the same as that of the display surface.
  31. self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
  32. def get_and_flip(self):
  33. # if you don't want to tie the framerate to the camera, you can check and
  34. # see if the camera has an image ready. note that while this works
  35. # on most cameras, some will never return true.
  36. if 0 and self.camera.query_image():
  37. # capture an image
  38. self.snapshot = self.camera.get_image(self.snapshot)
  39. if 0:
  40. self.snapshot = self.camera.get_image(self.snapshot)
  41. #self.snapshot = self.camera.get_image()
  42. # blit it to the display surface. simple!
  43. self.display.blit(self.snapshot, (0,0))
  44. else:
  45. self.snapshot = self.camera.get_image(self.display)
  46. #self.display.blit(self.snapshot, (0,0))
  47. pygame.display.flip()
  48. def main(self):
  49. going = True
  50. while going:
  51. events = pygame.event.get()
  52. for e in events:
  53. if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
  54. going = False
  55. if e.type == KEYDOWN:
  56. if e.key in range(K_0, K_0+10) :
  57. self.init_cams(e.key - K_0)
  58. self.get_and_flip()
  59. self.clock.tick()
  60. print (self.clock.get_fps())
  61. def main():
  62. pygame.init()
  63. pygame.camera.init()
  64. VideoCapturePlayer().main()
  65. pygame.quit()
  66. if __name__ == '__main__':
  67. main()