Skip to content

Instantly share code, notes, and snippets.

@johzzy
Forked from tedmiston/webcam-cv2.py
Last active July 8, 2019 06:02
Show Gist options
  • Save johzzy/25474491b9eaafb1c3a8daf4672903d3 to your computer and use it in GitHub Desktop.
Save johzzy/25474491b9eaafb1c3a8daf4672903d3 to your computer and use it in GitHub Desktop.
Display the webcam in Python using OpenCV (cv2)
"""
Simply display the contents of the webcam with optional mirroring using OpenCV
via the new Pythonic cv2 interface. Press <esc> to quit.
"""
import cv2
def show(img):
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
titles = ['img', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i, (title, image) in enumerate(zip(titles, images)):
cv2.imshow(title, image)
def show_webcam(mirror=False):
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
if mirror:
img = cv2.flip(img, 1)
#cv2.imshow('webcam', img)
show(img)
if cv2.waitKey(1) == 27:
break # esc to quit
cv2.destroyAllWindows()
def main():
show_webcam(mirror=True)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment