Last active
March 19, 2019 08:32
-
-
Save ken-itakura/0e566713796a52ecfbdee9f48676ef4d to your computer and use it in GitHub Desktop.
Capture image by web cam and get data (python3.6, OpenCV, JupyterLab)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import matplotlib.pyplot as plt | |
import ipywidgets as widgets | |
# from IPython.core.debugger import set_trace | |
# To run in JuptyerLab, you need to run following in console to enable interactive | |
# jupyter labextension install @jupyter-widgets/jupyterlab-manager | |
class PhotoCapture(): | |
""" | |
Catpture image by camera | |
usage: | |
pc = PhotoCapture() | |
# Click "Take Photo" button some times to take picture that you want to use | |
# Then | |
pc.get_photo_data() | |
# This returns the data of the image | |
""" | |
def __init__(self): | |
self.phot_frame = None | |
self.button = widgets.Button(description='Take Photo') | |
display(self.button) | |
self.out_widget = widgets.Output(layout={'border': '1px solid black'}) | |
display(self.out_widget) | |
self.button.on_click(self.take_photo_and_show) | |
def capture_camera(self): | |
cap = cv2.VideoCapture(0) | |
ret, frame = cap.read() | |
self.phot_frame = cv2.resize(frame, (800,600)) | |
cap.release() | |
cv2.destroyAllWindows() | |
# on_click callback of the button | |
def take_photo_and_show(self, b): | |
self.capture_camera() | |
self.out_widget.clear_output() | |
with self.out_widget: | |
fig, ax = plt.subplots() | |
ax.imshow(self.phot_frame) | |
plt.show(fig) | |
def get_photo_data(self): | |
return self.phot_frame | |
pc = PhotoCapture() | |
pc.get_photo_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment