Skip to content

Instantly share code, notes, and snippets.

@tedmiston
Last active May 4, 2023 11:56
Show Gist options
  • Star 64 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save tedmiston/6060034 to your computer and use it in GitHub Desktop.
Save tedmiston/6060034 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_webcam(mirror=False):
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
if mirror:
img = cv2.flip(img, 1)
cv2.imshow('my webcam', img)
if cv2.waitKey(1) == 27:
break # esc to quit
cv2.destroyAllWindows()
def main():
show_webcam(mirror=True)
if __name__ == '__main__':
main()
@zBugi
Copy link

zBugi commented Jun 29, 2021

explain this man!!!

I know it's kinda late but:

"""
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_webcam(mirror=False):
    int n = 0 
# use the device /dev/video{n} in this case /dev/video0 
# On windows use the first connected camera in the device tree
    cam = cv2.VideoCapture(n)
    while True:
# read what the camera the images which are comming from the camera
# ret_val idk atm
        ret_val, img = cam.read()
# if mirror is true do flip the image 
        if mirror: 
            img = cv2.flip(img, 1)
# show the image with the title my webcam in a window
        cv2.imshow('my webcam', img)
# if you press ESC break out of the while loop and destroy all windows == free resources <3
        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