Created
July 18, 2018 15:47
-
-
Save RodrigoCMoraes/d7b8eca5a5acd70c68ffb28f49da4edc to your computer and use it in GitHub Desktop.
Get frame from webcam and display it in real time
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
""" | |
Get frame from webcam and display it in real time | |
OpenCv version: 3.4.1 | |
Installed with command: pip install opencv-python | |
Python version: 3.6.5 :: Anaconda, Inc. | |
""" | |
import cv2 | |
""" | |
config(dict): configuration window and camera to display frames in real time | |
Param: | |
window | |
name(string): string title of window that frames are displayed | |
width(int): initial window width | |
height(int): initial window height | |
x0(int): initial window x position on screen(display reference is corner left) | |
y0(int): initial window y position on screen(display reference is corner left) | |
camera | |
index(int): usb camera index | |
width(int): frame width acquired from camera | |
height(int): frame height acquired from camera | |
fps(int): frame rate acquisition | |
""" | |
config = { | |
'window': { | |
'name': 'live webcam', | |
'width': 640, | |
'height': 480, | |
'x0': 0, | |
'y0': 0 | |
}, | |
'camera': { | |
'index': 0, | |
'width': 640, | |
'height': 480, | |
'fps': 60 | |
} | |
} | |
# open camera | |
camera = cv2.VideoCapture(config['camera']['index']) | |
# check camera is open | |
if not camera.isOpened(): | |
print("Error when try to open camera") | |
exit(-1) | |
# set frame width and height acquired from camera | |
camera.set(cv2.CAP_PROP_FRAME_WIDTH, config['camera']['width']) | |
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, config['camera']['height']) | |
# set initial window size and position | |
cv2.namedWindow(config['window']['name'], cv2.WINDOW_NORMAL) | |
cv2.resizeWindow(config['window']['name'], config['window'] | |
['width'], config['window']['height']) | |
cv2.moveWindow(config['window']['name'], config['window'] | |
['x0'], config['window']['y0']) | |
# real time frame display on window | |
while True: | |
# acquire image | |
ret, frame = camera.read() | |
# check if acquisition is OK | |
if not ret: | |
print("Error when try to capture frame from webcam") | |
break | |
# display image | |
cv2.imshow(config['window']['name'], frame) | |
# check if key 'q' are pressed | |
if cv2.waitKey(1000//config['camera']['fps']) & 0xFF == ord('q'): | |
break | |
# destroy created window | |
cv2.destroyWindow(config['window']['name']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment