Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

opencv
camera
communitycreator

How to capture a frame from real-time camera video using OpenCV

Faizan Tanveer

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 fpsframes per second means that it displays 30 images in a second.

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.

  1. 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
  1. The above code will include all the libraries defined in cv2 library (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 is vidcap, which will hold the reference returned by the VideoCapture function of the cv2 library. The below code demonstrates this:
vidcap = cv2.VideoCapture(0)
  1. The vidcap object 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 if cv2.VideoCapture is successfully used. Use vidcap.isOpened(). It will return true if the connection with the camera was successful. Otherwise, false will be returned. If true is returned, we will continue. Otherwise, we will print the error message.
if vidcap.isOpened():
   #do something
else:
   print("Cannot open camera")
  1. 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 if block 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")
  1. 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. The windname argument is a string for the name you want to give to your frame that will be displayed with the frame window and the frame attribute 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 capturing
vidcap = cv2.VideoCapture(0)

#check if connection with camera is successfully
if vidcap.isOpened():
    ret, frame = vidcap.read()  #capture a frame from live video

    #check whether frame is successfully captured
    if ret:
        # continue to display window until 'q' is pressed
        while(True):
            cv2.imshow("Frame",frame)   #show captured frame
            
            #press 'q' to break out of the loop
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    #print error if frame capturing was unsuccessful
    else:
        print("Error : Failed to capture frame")

# print error if the connection with camera is unsuccessful
else:
    print("Cannot open camera")
    

RELATED TAGS

opencv
camera
communitycreator
RELATED COURSES

View all Courses

Keep Exploring