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 library import cv2 # intialize the webcam and pass a constant which is 0 cam = cv2.VideoCapture(0) # title of the app cv2.namedWindow('python webcam screenshot app') # let's assume the number of images gotten is 0 img_counter = 0 # while loop while True: # intializing the frame, ret ret, frame = cam.read() # if statement if not ret: print('failed to grab frame') break # the frame will show with the title of test cv2.imshow('test', frame) #to get continuous live video feed from my laptops webcam k = cv2.waitKey(1) # if the escape key is been pressed, the app will stop if k%256 == 27: print('escape hit, closing the app') break # if the spacebar key is been pressed # screenshots will be taken elif k%256 == 32: # the format for storing the images scrreenshotted img_name = f'opencv_frame_{img_counter}' # saves the image as a png file cv2.imwrite(img_name, frame) print('screenshot taken') # the number of images automaticallly increases by 1 img_counter += 1 # release the camera cam.release() # stops the camera window cam.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.
RELATED TAGS
CONTRIBUTOR
View all Courses