How to capture a single photo with webcam using OpenCV in Python
Overview
OpenCV stands for “Open Source Computer Vision Library”. It is used to process image processing and perform computer vision tasks.
In this shot, we’ll learn to capture a single photo with a webcam using OpenCV in Python.
Installation
pip install pipenv
pipenv shell
pipenv install opencv-python
After the installation, let’s create a file and name it app.py.
app.py
# importing the python open cv libraryimport cv2# intialize the webcam and pass a constant which is 0cam = cv2.VideoCapture(0)# title of the appcv2.namedWindow('python webcam screenshot app')# let's assume the number of images gotten is 0img_counter = 0# while loopwhile True:# intializing the frame, retret, frame = cam.read()# if statementif not ret:print('failed to grab frame')break# the frame will show with the title of testcv2.imshow('test', frame)#to get continuous live video feed from my laptops webcamk = cv2.waitKey(1)# if the escape key is been pressed, the app will stopif k%256 == 27:print('escape hit, closing the app')break# if the spacebar key is been pressed# screenshots will be takenelif k%256 == 32:# the format for storing the images scrreenshottedimg_name = f'opencv_frame_{img_counter}'# saves the image as a png filecv2.imwrite(img_name, frame)print('screenshot taken')# the number of images automaticallly increases by 1img_counter += 1# release the cameracam.release()# stops the camera windowcam.destoryAllWindows()
Explanation
- Line 16: We use a Boolean variable
retthat returnstrueif the frame is available.frameis an image array vector captured based on the default frames per second defined explicitly or implicitly. - Line 22: We use the
cv2.imshow()method to show the title of the application. - Line 24: We use the
cv2.waitkey()method to get a continuous live video feed from the device camera. - Line 26: We check if the escape key is pressed. If it is, then the application shuts down.
- Line 31: We check if the spacebar is pressed. If it is, then a screenshot is taken.
- Line 35: We use the
cv2.imwrite()method to save an image to any storage device. - Line 41: We use the
cam.release()function to help release the camera. - Line 44: We use the
cam.destoryAllWindows()function to shut down the windows.
Running the code
After writing the code, go to the terminal and type this to start the application:
python app.py
A window pops up and we can press the spacebar to take a screenshot or press the escape button to exit the application.