Skip to content

Instantly share code, notes, and snippets.

@danielballan
Forked from mrakitin/laptop_camera.py
Last active February 7, 2018 03:39
Show Gist options
  • Save danielballan/912d50f3ae6d3f449d5feb66d9cfe43c to your computer and use it in GitHub Desktop.
Save danielballan/912d50f3ae6d3f449d5feb66d9cfe43c to your computer and use it in GitHub Desktop.
Trigger laptop camera
import cv2
import matplotlib.pyplot as plt
from ophyd import DeviceStatus
import queue
import weakref
class LaptopCamera:
def __init__(self, cam_id=0):
self.cam_id = cam_id
# There must be some "lazy" way to initialize it
self.cap = cv2.VideoCapture(cam_id)
self.cap.release()
self.image = None
# This loop will run on a thread for the lifetime of the
# instance, waiting for the device to be triggered and processing
# each trigger in the background.
self._status_queue = queue.Queue()
def capture_loop():
while True:
status = self.status_queue.get()
if status == 'POISON_PILL':
break
self.cap.open(self.cam_id)
self.image = self.cap.read()[1]
self.cap.release()
status._finished()
threading.Thread(target=capture_loop).start()
def trigger(self):
status = DeviceStatus(self)
self._status_queue.put(status)
return status
def __del__(self):
# Kill the capture_loop thread.
self._status_queue.put('POISON_PILL')
if __name__ == '__main__':
lc = LaptopCamera()
lc.trigger()
lc.show()
@mrakitin
Copy link

mrakitin commented Feb 6, 2018

import threading should be added.
lc.show() does not exist anymore, which is OK.

@mrakitin
Copy link

mrakitin commented Feb 6, 2018

There is an issue:

(video) mrakitin@mrakitin-mac:~/src/mrakitin/work $ python laptop_camera_Dan.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Users/mrakitin/anaconda3/envs/video/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/mrakitin/anaconda3/envs/video/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "laptop_camera_Dan.py", line 23, in capture_loop
    status = self.status_queue.get()
AttributeError: 'LaptopCamera' object has no attribute 'status_queue'

(video) mrakitin@mrakitin-mac:~/src/mrakitin/work $

@mrakitin
Copy link

mrakitin commented Feb 7, 2018

@danielballan, can we discuss it tomorrow?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment