Avi Files That Can Be Read by Opencv
In this mail service, nosotros volition acquire how to Read, Write and Display a video using OpenCV. Code in C++ and Python is shared for report and exercise.
Before we do that, allow me a digression into a scrap of history of video capture.
On June 15, 1898, in Palo Alto, California, a remarkable experiment was conducted to determine whether a galloping equus caballus ever had all four feet off the ground at the same time. This historic experiment by photographer Eadweard Muybridge was the get-go time a motion sequence was captured in existent 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 connected a thread that ran across the rails. When the horse ran on the rail, it broke i thread afterwards the other triggering the camera shutters in series and exposing the films for one-thousandth of a 2nd!
This remarkable story almost did not happen. Merely a few years before this accomplishment, Muybridge shot and killed his wife's lover. The jury acquited him on grounds of "justifiable homicide!" Only we have digressed a chip also far.
So, starting time up, 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 out of how fast the images are transitioning is given by a metric called frames per 2d(FPS).
When someone says that the video has an FPS of xl, it means that xl images are being displayed every second. Alternatively, later on every 25 milliseconds, a new frame is displayed. The other of import attributes are the width and height of the frame.
Reading a Video
In OpenCV, a video tin be read either past using the feed from a photographic camera connected to a estimator or by reading a video file. The first footstep towards reading a video file is to create a VideoCapture object. Its statement tin be either the device index or the name of the video file to be read.
In most cases, only 1 photographic camera is continued to the arrangement. Then, all we do is pass '0' and OpenCV uses the only photographic camera fastened to the figurer. When more than i camera is connected to the calculator, nosotros tin can select the 2d camera by passing 'ane', the third camera by passing '2' and and then on.
Python
# Create a VideoCapture object and read from input file # If the input is taken from the camera, pass 0 instead of the video file proper name. cap = cv2.VideoCapture('chaplin.mp4') C++
// Create a VideoCapture object and open the input file // If the input is taken from the photographic camera, pass 0 instead of the video file name VideoCapture cap("chaplin.mp4"); After the VideoCapture object is created, nosotros can capture the video frame by frame.
Displaying a video
Later reading a video file, nosotros can display the video frame by frame. A frame of a video is simply an image and we display each frame the aforementioned way we display images, i.e., nosotros apply the function imshow().
As in the example of an epitome, we employ the waitKey() later on imshow() office to interruption each frame in the video. In the case of an image, we pass '0' to the waitKey() role, but for playing a video, nosotros demand to pass a number greater than '0' to the waitKey() part. This is because '0' would intermission the frame in the video for an infinite amount of time and in a video we need each frame to be shown simply for some finite interval of time. So, we need to laissez passer a number greater than '0' to the waitKey() office. This number is equal to the time in milliseconds nosotros want each frame to be displayed.
While reading the frames from a webcam, using waitKey(one) is appropriate because the display frame rate will be limited by the frame rate of the webcam fifty-fifty if nosotros specify a delay of 1 ms in waitKey.
While reading frames from a video that you are processing, it may withal be appropriate to set the time filibuster to 1 ms and then that the thread is freed upwards to do the processing we want to do.
In rare cases, when the playback needs to exist at a certain framerate, we may want the delay to be college than 1 ms.
The Python and C++ implementation of reading and displaying a video file follows.
Download Code To easily follow along this tutorial, please download code past clicking on the push beneath. It'south Complimentary!
Python
import cv2 import numpy as 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 photographic camera opened successfully if (cap.isOpened()== False): print("Error opening video stream or file") # Read until video is completed while(cap.isOpened()): # Capture frame-past-frame ret, frame = cap.read() if ret == True: # Display the resulting frame cv2.imshow('Frame',frame) # Press Q on keyboard to get out if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything washed, 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 chief(){ // Create a VideoCapture object and open the input file // If the input is the web camera, pass 0 instead of the video file name VideoCapture cap("chaplin.mp4"); // Check if camera opened successfully if(!cap.isOpened()){ cout << "Fault opening video stream or file" << endl; return -i; } while(one){ Mat frame; // Capture frame-by-frame cap >> frame; // If the frame is empty, interruption immediately if (frame.empty()) break; // Display the resulting frame imshow( "Frame", frame ); // Press ESC on keyboard to exit char c=(char)waitKey(25); if(c==27) suspension; } // When everything washed, release the video capture object cap.release(); // Closes all the frames destroyAllWindows(); return 0; } Writing a video
After nosotros are done with capturing and processing the video frame by frame, the side by side step we would want to do is to save the video.
For images, information technology is straightforward. Nosotros just demand to use cv2.imwrite(). Simply for videos, we need to toil a bit harder. We need to create a VideoWriter object. First, nosotros should specify the output file name with its format (eg: output.avi). 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 exist equal to 10. Too frame size is passed. out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height)) C++
// Ascertain the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file. // Define the fps to be equal to 10. Also frame size is passed. VideoWriter video("outcpp.avi",CV_FOURCC('M','J','P','G'),ten, Size(frame_width,frame_height)); FourCC is a 4-byte code used to specify the video codec. The list of available codes can exist constitute at fourcc.org. At that place are many FOURCC codes available, just in this mail, we will work only with MJPG.
Note: Only a few of the FourCC codes listed above will piece of work on your system based on the availability of the codecs on your system. Sometimes, even when the specific codec is available, OpenCV may not exist able to utilise it. MJPG is a prophylactic choice.
The Python and C++ implementation of capturing live stream from a camera and writing it to a file follows.
Python
import cv2 import numpy as np # Create a VideoCapture object cap = cv2.VideoCapture(0) # Bank check if photographic camera opened successfully if (cap.isOpened() == False): print("Unable to read camera feed") # Default resolutions of the frame are obtained.The default resolutions are system dependent. # We catechumen the resolutions from float to integer. frame_width = int(cap.get(3)) frame_height = int(cap.go(4)) # 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','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) # Brandish the resulting frame cv2.imshow('frame',frame) # Press Q on keyboard to terminate recording if cv2.waitKey(1) & 0xFF == ord('q'): break # Break the loop else: pause # When everything done, 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); // Check if camera opened successfully if(!cap.isOpened()){ cout << "Fault opening video stream" << endl; return -1; } // Default resolutions of the frame are obtained.The default resolutions are system dependent. int frame_width = cap.become(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','Yard'), ten, Size(frame_width,frame_height)); while(i){ Mat frame; // Capture frame-by-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); // Brandish the resulting frame imshow( "Frame", frame ); // Printing ESC on keyboard to exit char c = (char)waitKey(ane); if( c == 27 ) suspension; } // When everything washed, release the video capture and write object cap.release(); video.release(); // Closes all the frames destroyAllWindows(); return 0; } Summary
In this post we have learned the basic aspects of how to Read, Write and Display a video using OpenCV. These basic steps are the very foundation for many interesting and trouble solving Computer Vision and Automobile Learning applications such every bit Video Classification and Human being Activity Recognition, and Help robots with a vision to navigate autonomously, grasp different objects or avoid collisions while moving.
Subscribe & Download Lawmaking
If you liked this article and would like to download code (C++ and Python) and case images used in this mail service, please click here. Alternately, sign upwards to receive a gratis Estimator Vision Resources Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Calculator Vision and Car Learning algorithms and news.
Cardinal takeaways:
- A video can be read either by using the feed from a camera continued to a computer or by reading a video file.
- Displaying a video is washed frame by frame. A frame of a video is merely an image and nosotros display each frame the same way we brandish images.
- To write a video nosotros need to create a VideoWriter object.
- First, specify the output file name with its format (eg: output.avi).
- Then, we should specify the FourCC code and the number of frames per 2d (FPS).
- Lastly, the frame size should exist passed.
Pitfall : If the video file you are reading is in the same folder as your code, but specify the right file proper noun. Else, you would have to specify the complete path to the video file.
parkerbedeencion1994.blogspot.com
Source: https://learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/
Post a Comment for "Avi Files That Can Be Read by Opencv"