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()
@tonyfrost007
Copy link

explain this man!!!

@johnrees
Copy link

while True: shouldn't be indented here

@shreyas77
Copy link

along with capturing image I also want to access gpio pins. But problem is that CV environment is not allowing to access the gpio. whenever i come out of the cv environment then only i can access the gpio.

is there any solution to access the gpio in cv environment??

@Anupama-S-D
Copy link

Im getting this error (-215) size.width>0 && size.height>0 in function imshow
Please help me in this.

@AdithyaMpn
Copy link

shreyas77 use execfile('ur filename of gpio')

@tab0r
Copy link

tab0r commented Jun 3, 2017

@Anupama-S-D Me too, let me know if you find a workaround?

@oarriaga
Copy link

oarriaga commented Jun 21, 2017

@thetabor @AdithyaMpn
If you installed using
pip install opencv-python
It will not work as stated in the un/official module documentation

video related functionality is not supported (not compiled with FFmpeg)

@officialrobosense
Copy link

thank you very much

@yaswanth789
Copy link

Anupama and Thetabor ,I also faced the same error.
Please let me know if you solved it.

@Nicolas1203
Copy link

Nicolas1203 commented Jan 11, 2019

@yaswanth789 @Anupama-S-D @thetabor
This just means the frame given to imshow() is empty. So either your webcam is not detected by your computer, either the webcam index is not correct. You can try different webcam indexes, for example by changing cam = cv2.VideoCapture(0) to cam = cv2.VideoCapture(1).
Under linux you can see webcam entries with this command :
» ls /dev/ | grep video
video0 video1
This means I have two webcams entries, with index 0 and 1.

You can also find more answers here : https://stackoverflow.com/questions/27953069/opencv-error-215size-width0-size-height0-in-function-imshow

@Guohao91
Copy link

Guohao91 commented Apr 1, 2020

hi,@taylor D.Edmiston @Nicolas1203
does any of you know how to set the window's size (e.g. width&height) along this posted code? I am not familiat with cv2 SDK, please help!
And, does anyone how to make up this code into an online webapp just over local network?
Huge appreciate it in advance!

@Nicolas1203
Copy link

Hi @Guohao91,
you could do something like this

def show_webcam(mirror=False, width=600, height=600):
    cam = cv2.VideoCapture(0)
    while True:
        ret_val, img = cam.read()
        if mirror: 
            img = cv2.flip(img, 1)
        cv2.imshow('my webcam', img)
        cv2.namedWindow('my webcam',cv2.WINDOW_NORMAL)
        cv2.resizeWindow('my webcam', width, height)
        if cv2.waitKey(1) == 27: 
            break  # esc to quit
    cv2.destroyAllWindows()

Hope this helps.

@Guohao91
Copy link

Guohao91 commented Apr 3, 2020

@Nicolas1203
Thanks Prof.!

@AryanSethi
Copy link

Please explain the 12th line. I think I'm having a problem with the syntax. How are we using 2 variables (ret_val and image) as output of read() function. Please help

@yosekeiree
Copy link

Please explain the 12th line. I think I'm having a problem with the syntax. How are we using 2 variables (ret_val and image) as output of read() function. Please help

that function returns a tuple which contains two elements and python can work with multiple assignment (just try, well, a, b = 1, 2)

@m-namitha
Copy link

/usr/local/lib/python3.6/dist-packages/google/colab/patches/init.py in cv2_imshow(a)
20 image.
21 """
---> 22 a = a.clip(0, 255).astype('uint8')
23 # cv2 stores colors as BGR; convert to RGB
24 if a.ndim == 3:

AttributeError: 'NoneType' object has no attribute 'clip'
How to fix this error?

@noobcodess
Copy link

I tried running this in Pycharm and I got qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

but then I just ran it in the terminal and It worked perfectly so incase anybody else gets that error, try that.

@AryanSethi
Copy link

@m-namitha if you are trying to run the script on Google Colab which I'm guessing you are, it won't work and google says that loud and clear. They instead suggest you to use the code snippet provided by colab itself to run such scripts.

@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