Last active
May 4, 2023 11:56
-
-
Save tedmiston/6060034 to your computer and use it in GitHub Desktop.
Display the webcam in Python using OpenCV (cv2)
This file contains hidden or 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
""" | |
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() |
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.
@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.
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
/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?