banner



How To Save Multiple Frames Capture From Camera ,code In C++

In this mail service, we will learn how to Read, Write and Brandish a video using OpenCV. Code in C++ and Python is shared for written report and practice.

Before we do that, permit me a digression into a bit of history of video capture.

On June xv, 1898, in Palo Alto, California, a remarkable experiment was conducted to determine whether a galloping horse ever had all iv feet off the basis at the aforementioned time. This celebrated experiment by photographer Eadweard Muybridge was the first time a motion sequence was captured in real time. It was financed by Leland Stanford of the Standford University fame.

Eadweard placed multiple cameras, 27 inches apart along the side of the race track. To every camera's shutter was continued a thread that ran across the track. When the equus caballus ran on the track, it broke 1 thread afterward the other triggering the photographic camera shutters in series and exposing the films for i-thousandth of a second!

Read, Write and Display a video using OpenCV. Horse in Motion : First real time motion sequence captured
The horse in monition animation

This remarkable story well-nigh did not happen. Simply a few years before this achievement, Muybridge shot and killed his wife's lover. The jury acquited him on grounds of "justifiable homicide!" Merely we have digressed a bit as well far.

So, kickoff upwardly, what is a video? A video is a sequence of fast moving images. The obvious question that follows is how fast are the pictures moving? The measure of how fast the images are transitioning is given by a metric called frames per second(FPS).

When someone says that the video has an FPS of forty, it means that twoscore images are being displayed every 2d. Alternatively, afterwards every 25 milliseconds, a new frame is displayed. The other important attributes are the width and peak of the frame.

Reading a Video

In OpenCV, a video can be read either by using the feed from a photographic camera continued to a computer or by reading a video file. The first footstep towards reading a video file is to create a VideoCapture object. Its statement can exist either the device index or the proper noun of the video file to be read.

In most cases, merely one photographic camera is connected to the organisation. So, all nosotros exercise is laissez passer '0' and OpenCV uses the only camera attached to the estimator. When more than one camera is connected to the computer, we can select the second photographic camera by passing '1', the third camera by passing 'ii' then on.

Python

# Create a VideoCapture object and read from input file # If the input is taken from the photographic camera, pass 0 instead of the video file name.  cap = cv2.VideoCapture('chaplin.mp4')                

C++

// Create a VideoCapture object and open the input file // If the input is taken from the camera, pass 0 instead of the video file name  VideoCapture cap("chaplin.mp4");                

Afterwards the VideoCapture object is created, we can capture the video frame by frame.

Displaying a video

After reading a video file, we can display the video frame by frame. A frame of a video is simply an image and we display each frame the same style nosotros display images, i.e., nosotros utilise the function imshow().

Equally in the case of an epitome, we use the waitKey() after imshow() function to pause each frame in the video. In the case of an image, we pass '0' to the waitKey() function, but for playing a video, we need to pass a number greater than '0' to the waitKey() function. This is because '0' would pause the frame in the video for an infinite corporeality of time and in a video we need each frame to exist shown but for some finite interval of fourth dimension. And then, we need to pass a number greater than '0' to the waitKey() function. This number is equal to the time in milliseconds we desire each frame to exist displayed.

While reading the frames from a webcam, using waitKey(1) is appropriate because the brandish frame charge per unit will be express past the frame rate of the webcam fifty-fifty if we specify a delay of i ms in waitKey.

While reading frames from a video that you are processing, it may still exist appropriate to set the time delay to 1 ms so that the thread is freed up to practise the processing nosotros desire to do.

In rare cases, when the playback needs to be at a certain framerate, we may want the delay to be higher than 1 ms.

The Python and C++ implementation of reading and displaying a video file follows.

Download Lawmaking To easily follow along this tutorial, please download code by clicking on the push button below. It'due south FREE!

Python

import cv2 import numpy equally np  # Create a VideoCapture object and read from input file # If the input is the photographic camera, pass 0 instead of the video file proper name cap = cv2.VideoCapture('chaplin.mp4')  # Check if camera opened successfully if (cap.isOpened()== False):    print("Error opening video stream or file")  # Read until video is completed while(cap.isOpened()):   # Capture frame-by-frame   ret, frame = cap.read()   if ret == Truthful:      # Display the resulting frame     cv2.imshow('Frame',frame)      # Press Q on keyboard to  exit     if cv2.waitKey(25) & 0xFF == ord('q'):       pause    # Pause the loop   else:      break  # When everything done, release the video capture object cap.release()  # Closes all the frames cv2.destroyAllWindows()                

C++

#include "opencv2/opencv.hpp" #include <iostream>  using namespace std; using namespace cv;  int main(){    // Create a VideoCapture object and open the input file   // If the input is the spider web camera, laissez passer 0 instead of the video file name   VideoCapture cap("chaplin.mp4");        // Check if camera opened successfully   if(!cap.isOpened()){     cout << "Error opening video stream or file" << endl;     render -1;   } 	   while(1){      Mat frame;     // Capture frame-by-frame     cap >> frame;       // If the frame is empty, suspension immediately     if (frame.empty())       break;      // Brandish the resulting frame     imshow( "Frame", frame );      // Printing  ESC on keyboard to exit     char c=(char)waitKey(25);     if(c==27)       pause;   }     // When everything done, release the video capture object   cap.release();    // Closes all the frames   destroyAllWindows(); 	   return 0; }                

Writing a video

After we are done with capturing and processing the video frame past frame, the next step nosotros would want to do is to save the video.

For images, it is straightforward. We just need to employ cv2.imwrite(). Only for videos, we need to toil a bit harder. We demand to create a VideoWriter object. First, we should specify the output file name with its format (eg: output.avi). And then, we should specify the FourCC code and the number of frames per second (FPS). Lastly, the frame size should be passed.

Python

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file. # Define the fps to be equal to x. Also frame size is passed.  out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('Thou','J','P','G'), 10, (frame_width,frame_height))                

C++

// Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file. // Ascertain the fps to be equal to 10. As well frame size is passed.  VideoWriter video("outcpp.avi",CV_FOURCC('One thousand','J','P','G'),x, Size(frame_width,frame_height));                

FourCC is a 4-byte lawmaking used to specify the video codec. The list of available codes tin can exist institute at fourcc.org. There are many FOURCC codes bachelor, but in this postal service, we will work only with MJPG.

Note: Only a few of the FourCC codes listed higher up will work on your system based on the availability of the codecs on your organisation. Sometimes, even when the specific codec is available, OpenCV may not exist able to use it. MJPG is a safe selection.

The Python and C++ implementation of capturing alive stream from a camera and writing information technology to a file follows.

Python

import cv2 import numpy as np  # Create a VideoCapture object cap = cv2.VideoCapture(0)  # Check if camera opened successfully if (cap.isOpened() == Faux):    print("Unable to read photographic camera feed")  # Default resolutions of the frame are obtained.The default resolutions are system dependent. # We convert the resolutions from float to integer. frame_width = int(cap.get(iii)) frame_height = int(cap.become(iv))  # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file. out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','One thousand'), 10, (frame_width,frame_height))  while(True):   ret, frame = cap.read()    if ret == True:           # Write the frame into the file 'output.avi'     out.write(frame)      # Display the resulting frame         cv2.imshow('frame',frame)      # Press Q on keyboard to terminate recording     if cv2.waitKey(1) & 0xFF == ord('q'):       interruption    # Break the loop   else:     intermission    # When everything washed, release the video capture and video write objects cap.release() out.release()  # Closes all the frames cv2.destroyAllWindows()                

C++

#include "opencv2/opencv.hpp" #include <iostream>  using namespace std; using namespace cv;  int main(){    // Create a VideoCapture object and use camera to capture the video   VideoCapture cap(0);     // Bank check if camera opened successfully   if(!cap.isOpened()){    	cout << "Error opening video stream" << endl;         return -1;   }      // Default resolutions of the frame are obtained.The default resolutions are system dependent.   int frame_width = cap.get(cv::CAP_PROP_FRAME_WIDTH);   int frame_height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);      // Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file.   VideoWriter video("outcpp.avi", cv::VideoWriter::fourcc('M','J','P','G'), 10, Size(frame_width,frame_height));    while(i){      Mat frame;         // Capture frame-past-frame     cap >> frame;       // If the frame is empty, break immediately     if (frame.empty())       break;          // Write the frame into the file 'outcpp.avi'     video.write(frame);         // Display the resulting frame         imshow( "Frame", frame );       // Press  ESC on keyboard to  exit     char c = (char)waitKey(i);     if( c == 27 )        break;   }    // When everything done, release the video capture and write object   cap.release();   video.release();    // Closes all the frames   destroyAllWindows();   return 0; }                

Summary

In this mail we have learned the basic aspects of how to Read, Write and Display a video using OpenCV. These bones steps are the very foundation for many interesting and trouble solving Computer Vision and Machine Learning applications such as Video Classification and Human Action Recognition, and Help robots with a vision to navigate autonomously, grasp different objects or avoid collisions while moving.

Key takeaways:

  1. A video tin be read either by using the feed from a camera connected to a computer or by reading a video file.
  2. Displaying a video is done frame by frame. A frame of a video is just an image and we display each frame the same manner we display images.
  3. To write a video we need to create a VideoWriter object.
    • First, specify the output file name with its format (eg: output.avi).
    • And then, we should specify the FourCC code and the number of frames per second (FPS).
    • Lastly, the frame size should be passed.

Pitfall : If the video file yous are reading is in the same folder as your code, simply specify the correct file name. Else, you would have to specify the complete path to the video file.

Source: https://learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/

Posted by: weinmanndraugh.blogspot.com

0 Response to "How To Save Multiple Frames Capture From Camera ,code In C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel