How to use OpenCV In Python
OpenCV library is compatible with the Linux and windows both operating system. Users need to install the OpenCV library on their local computer using the below command before they go ahead.
Install command - pip install opencv-python
Approach
1. Import OpenCV library
2. Initialize the camera using the VideoCapture() method.
Syntax:
Python3
cam = VideoCapture( 0 ) |
3. Read input using the camera using the cam.read() method.
Syntax:
Python3
result, image = cam.read() |
4. If input image detected without any error, show output
Syntax:
If result: # show the image imshow("w3wiki", image) # save the image imwrite("w3wiki.png", image) else: Move to this part is input image has some error
Example:
Python3
# program to capture single image from webcam in python # importing OpenCV library from cv2 import * # initialize the camera # If you have multiple camera connected with # current device, assign a value in cam_port # variable according to that cam_port = 0 cam = VideoCapture(cam_port) # reading the input using the camera result, image = cam.read() # If image will detected without any error, # show result if result: # showing result, it take frame name and image # output imshow( "w3wiki" , image) # saving image in local storage imwrite( "w3wiki.png" , image) # If keyboard interrupt occurs, destroy image # window waitKey( 0 ) destroyWindow( "w3wiki" ) # If captured image is corrupted, moving to else part else : print ( "No image detected. Please! try again" ) |
Output:
How to capture a image from webcam in Python?
In this article, we will discuss how to capture an image from the webcam using Python.
Contact Us