Skip to content

Instantly share code, notes, and snippets.

@neotheicebird
Last active April 10, 2019 23:13
Show Gist options
  • Save neotheicebird/6731bb2849b344f230377770118bac0c to your computer and use it in GitHub Desktop.
Save neotheicebird/6731bb2849b344f230377770118bac0c to your computer and use it in GitHub Desktop.
Access Webcam in iPython notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2016-11-01T17:33:15.254949",
"start_time": "2016-11-01T17:33:12.700730"
},
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib notebook\n",
"\n",
"import cv2\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"ExecuteTime": {
"end_time": "2016-11-01T17:34:08.855183",
"start_time": "2016-11-01T17:34:08.716191"
},
"collapsed": false
},
"outputs": [],
"source": [
"vc = cv2.VideoCapture(0)\n",
"\n",
"plt.ion()\n",
"\n",
"if vc.isOpened(): # try to get the first frame\n",
" is_capturing, frame = vc.read()\n",
" frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # makes the blues image look real colored\n",
" webcam_preview = plt.imshow(frame) \n",
"else:\n",
" is_capturing = False\n",
"\n",
"while is_capturing:\n",
" try: # Lookout for a keyboardInterrupt to stop the script\n",
" is_capturing, frame = vc.read()\n",
" frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # makes the blues image look real colored\n",
" webcam_preview.set_data(frame)\n",
" plt.draw()\n",
"\n",
" try: # Avoids a NotImplementedError caused by `plt.pause`\n",
" plt.pause(0.05)\n",
" except Exception:\n",
" pass\n",
" except KeyboardInterrupt:\n",
" vc.release()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment