Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import io
  2. import time
  3. import threading
  4. import picamera
  5. from PIL import Image
  6. from PIL import ImageOps
  7.  
  8. # Create a pool of image processors
  9. done = False
  10. lock = threading.Lock()
  11. pool = []
  12.  
  13. class ImageProcessor(threading.Thread):
  14. def __init__(self):
  15. super(ImageProcessor, self).__init__()
  16. self.stream = io.BytesIO()
  17. self.event = threading.Event()
  18. self.terminated = False
  19. self.start()
  20.  
  21. def run(self):
  22. # This method runs in a separate thread
  23. global done
  24. while not self.terminated:
  25. # Wait for an image to be written to the stream
  26. if self.event.wait(1):
  27. try:
  28. self.stream.seek(0)
  29. # Read the image and do some processing on it
  30.  
  31. image = Image.open(self.stream)
  32. inverted_image = ImageOps.invert(image)
  33. image.save("captured.jpg")
  34.  
  35. self.stream.seek(0)
  36. inverted_image.save(self.stream, format="JPEG")
  37. inverted_image.save("processed.jpg")
  38.  
  39. # Set done to True if you want the script to terminate
  40. # at some point
  41. #done=True
  42. finally:
  43. # Reset the stream and event
  44. self.stream.seek(0)
  45. self.stream.truncate()
  46. self.event.clear()
  47. # Return ourselves to the pool
  48. with lock:
  49. pool.append(self)
  50.  
  51. def streams():
  52. while not done:
  53. with lock:
  54. if pool:
  55. processor = pool.pop()
  56. else:
  57. processor = None
  58. if processor:
  59. yield processor.stream
  60. processor.event.set()
  61. else:
  62. # When the pool is starved, wait a while for it to refill
  63. time.sleep(0.1)
  64.  
  65. with picamera.PiCamera() as camera:
  66. pool = [ImageProcessor() for i in range(4)]
  67. camera.resolution = (640, 480)
  68. camera.framerate = 30
  69. camera.start_preview()
  70. time.sleep(2)
  71. camera.capture_sequence(streams(), use_video_port=True)
  72.  
  73. # Shut down the processors in an orderly fashion
  74. while pool:
  75. with lock:
  76. processor = pool.pop()
  77. processor.terminated = True
  78. processor.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement