How to capture a frame from real-time camera video using OpenCV
What is OpenCV?
OpenCV is a library containing predefined functions for real-time computer vision tasks like object detection, processing of images captured, etc.
What is a frame?
A frame is an image that forms a single instance of a video. A video consists of a lot of frames running per second (also known as frames per second). For example, a video streaming at 30
Steps
We will be using Python language for this purpose, but the OpenCV library is available in most of the high-level languages, e.g., C++, Java, Kotlin, etc.
- As we have to use OpenCV methods, they have to be included in our code file. Use the following line of code to include OpenCV library functions in Python
import cv2.
import cv2
- The above code will include all the libraries defined in
cv2library (OpenCV library in Python). Now, the next step is to create a variable that will hold the video capturing object. In this case, the variable isvidcap, which will hold the reference returned by theVideoCapturefunction of thecv2library. The below code demonstrates this:
vidcap = cv2.VideoCapture(0)
- The
vidcapobject created will now have the reference to the integrated webcam (for laptops) or any other portable webcam attached via input ports. The next step is to check ifcv2.VideoCaptureis successfully used. Usevidcap.isOpened(). It will returntrueif the connection with the camera was successful. Otherwise,falsewill be returned. Iftrueis returned, we will continue. Otherwise, we will print the error message.
if vidcap.isOpened():
#do something
else:
print("Cannot open camera")
- If our connection with the camera was successful, we’ll capture a frame from the live video. For that, use the following line of code inside the
ifblock from the previous step.
if vidcap.isOpened():
ret, frame = vidcap.read()
else:
print("cannot open camera")
The read() function returns a tuple of size 2. The first element of the tuple is a true or false, depending on whether the frame was captured successfully, and the second element of the tuple contains the actual video frame if it was successfully captured.
After this statement, another if block will be added to the previous if block that will check whether the frame was successfully captured.
if vidcap.isOpened():
ret, frame = vidcap.read()
if ret:
#do something
else:
print("Error : Failed to capture frame")
else:
print("cannot open camera")
- If the frame was successfully captured, we will display the captured frame by using
cv2.imshow(windname, frame). The captured frame will be displayed in a new window. Thewindnameargument is a string for the name you want to give to your frame that will be displayed with the frame window and theframeattribute is an object that holds the frame captured from the previous step. Now, it will look something like this:
if vidcap.isOpened():
ret, frame = vidcap.read()
if ret:
cv2.imshow('Frame', frame)
else:
print("frame not captured")
else:
print("cannot open camera")
If the code runs successfully, a new window is opened and it then immediately closes. To keep the frame in persistent view, we need to use a loop with a condition to break out of the loop. The following lines of code inside the second if block caters to it:
while(True):
cv2.imshow(windowname,frame)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
After adding this code, the window containing the video frame will open, but the program will wait for the 'q' key to be pressed to break out of the loop. Once 'q' is pressed, the window will close.
Below is the complete Python code for the task discussed above.
Code
import cv2 #include opencv library functions in python#Create an object to hold reference to camera video capturingvidcap = cv2.VideoCapture(0)#check if connection with camera is successfullyif vidcap.isOpened():ret, frame = vidcap.read() #capture a frame from live video#check whether frame is successfully capturedif ret:# continue to display window until 'q' is pressedwhile(True):cv2.imshow("Frame",frame) #show captured frame#press 'q' to break out of the loopif cv2.waitKey(1) & 0xFF == ord('q'):break#print error if frame capturing was unsuccessfulelse:print("Error : Failed to capture frame")# print error if the connection with camera is unsuccessfulelse:print("Cannot open camera")