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.
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()
ret
that returns true
if the frame is available. frame
is an image array vector captured based on the default frames per second defined explicitly or implicitly.cv2.imshow()
method to show the title of the application.cv2.waitkey()
method to get a continuous live video feed from the device camera.cv2.imwrite()
method to save an image to any storage device.cam.release()
function to help release the camera.cam.destoryAllWindows()
function to shut down the windows.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.