How to capture a image from webcam in Python?
Last Updated :
03 Jan, 2023
In this article, we will discuss how to capture an image from the webcam using Python.
We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to capture an image.
Method 1: Using OpenCV
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:
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("GeeksForGeeks", image)
# save the image
imwrite("GeeksForGeeks.png", image)
else:
Move to this part is input image has some error
Example:
Python3
from cv2 import *
cam_port = 0
cam = VideoCapture(cam_port)
result, image = cam.read()
if result:
imshow( "GeeksForGeeks" , image)
imwrite( "GeeksForGeeks.png" , image)
waitKey( 0 )
destroyWindow( "GeeksForGeeks" )
else :
print ( "No image detected. Please! try again" )
|
Output:
Method 2: Using PyGame
PyGame.camera() camera initializer supports only Linux operating system and Currently, It is not compatible with Windows. To install PyGame in Linux, Enter the below command on the Linux terminal.
Approach:
1. Import pygame.camera module
2. Initialize the camera using the camera.init() method.
3. Detect all available cameras using the list_cameras() method.
Python3
camlist = pygame.camera.list_cameras()
|
4. check if the camera is detected or not
Syntax:
if camlist:
# Initialize and start camera
cam = pygame.camera.Camera(camlist[0], (640, 480))
cam.start()
# capturing the single image
image = cam.get_image()
# saving the image
pygame.image.save(image, "filename.jpg")
else:
if camera is not detected the moving to this part
Example:
Python3
import pygame
import pygame.camera
pygame.camera.init()
camlist = pygame.camera.list_cameras()
if camlist:
cam = pygame.camera.Camera(camlist[ 0 ], ( 640 , 480 ))
cam.start()
image = cam.get_image()
pygame.image.save(image, "filename.jpg" )
else :
print ( "No camera on current device" )
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...