Python Video Recording using OpenCV

Python Video Recording Tutorial

Beginners Code Walk-through:

Imports:

Illustration 1: These are the libraries we will be using in our Video Recording program to call definitions stored in the class. For Example: “VideoCapture()” is a definitions that can’t be access with out first importing your cv2 library. See Illustration 1: for more details. This applies for all library you want to use in your project which include “cv2, datetime, os, and numpy”.

Firstly, the CV2 library in this tutorial allows use to access the default web camera attached to your laptop or desktop. Secondly, the Datetime library allows you to access the formatting and data structure of how python retrieves the date and the time from the system clock. Thirdly, Os library allow us to access to create cross-platform decision making programs. if you wanted your program to know if it on a Linux base system, Mac base system, or Windows base system the os library system got you covered.

Let me know what your output was in the commits of the YouTube Video Below.

Fourthly, Numpy library allows you access to scientific computing in python. cv2 capture images as array data and send that array data to use to modify as we see fit for our projects. Since this is a beginner tutorial using numpy would beyond the scope of this beginner tutorial. We will import numpy as np because it is the standard name for numpy seeing a we are using builtin and non builtin library sticking to the standard is key.

Illustration 1:

Now that our imports are complete we can move on to creating a definitions. These definitions will be to core of our program for this tutorial. We will break the code down and explain each step in more detail so you are not lost. Don’t worry, if you are hear and reading this we where in the same boat when I first started learning python and opencv as well.

Definition:

In Illustration 2: we will create our definition. A definition can be any name you like but, for clarity and consistency you will want to stick with a pattern that will be easy to you and or other to read in the future. Example: def Video_Capture(): can be, def video_capture(): or, def VIDEO_CAPTURE(): just make sure you pick a style and try to stick with it. Another style you can use is the PEP 8 – Style Guide for Python Code.

Since any definition can be the entry point into you program. Therefore this tutorial we will be using Video_Capture as our definition name of choice. We need to create a variable to hold the date that will be passed to us from cv2.VideoCapture() function. Think of a variable as a container. Overall In programming we use containers to store data. In this tutorial we will use the variable webcam to hold our data. Now lets define our new variable. We define variables by placing an equal sign(=) next to it. Then we tell python what we want to put into the webcam container.

Lets put the data received from cv2 function VideoCapture into our webcam variable. We need to tell the VideoCapture function what camera we want it to see out of and return data to us from. Like in a numpy array all indexes start at 0 and increase from there. Since the VideoCapture function captures data in an array. It looks for camera in the same fashion. We will choose zero in this tutorial to access your default camera. If you have multiple camera install on your PC you will have to play with the number 0,1,2,3,4,5,6,7,8,9 etc… to find the camera you want to record from.

Illustration 2:

In Illustration 3: we will define our output path definition. This part is not in the Recording Video with Python using OpenCV, YouTube Video. So you will have to Follow, Like, and Subscribe so you can stay up to date on our latest projects: CryoEnterprise, TikTok, Twitter, YouTube, and GitHub.

Our next variable is VideoOutPutPath. Let define this variable to a physical location on our hard drive. This can also be anywhere you want on your hard drive but for this tutorial we will send the output to a path inside our project folder that will be created when you run the program. Now I’m using a Linux system so my path rules will be slightly different then yours if you are using a different operation system. Don’t worry, I’ve got you covered. Window user will need to place two back slashes(\\) in place of the forward slash (/) that Linux uses. Example: “Output\\Videos\\”. Mac is a flavor of Unix so it uses the forward slash (/). If you have any question you can let me a comment on YouTube video below or send me a message through Contact US.

Now for our if statement. An if statement is how a program makes a decision on what to do next depending on if the results are True or False. What we are saying in this instant is, if the path (directory) we defined is not present (FALSE): then make all (directory) that you see along our variable path definition in the order you see them. Also, if the if statement is True then the nested code inside of the if statement will be skipped. This check is done by calling os.path.isdir() and passing our input variable VideoOutPutPath to the isdir() function. We do this because the isdir() function takes a input argument to execute properly. The makedirs() function allows us to create multiple directories. While the mkdir() allows us to make one directory at a time.

Illustration 3:

Update to the YouTube Video Code is located on our CryoEnterprise LLC GitHub page.

Tip: Creating a variable to store your input data makes it easier to manage changes in your program for that input. Sure, right now we have a bit of code on one page that’s less than one hundred lines. But, what happens when you have thousands of lines of code and multiple pages with the same input and that one input is used across different pages and hundreds of time on each page. You will thank me when its only one input location you have to change instead of thousands.

In Illustration 4: we begin to create our image file container. We will start by declaring our camera frame height and our camera frame width. This is very important due to the program not running correctly if the arguments are not set. 480 pixels is the default height. 640 pixels is the default width. These pixels are the default pixels used by opencv ishow() function to create a display window to show the camera output. These pixels can be changed but, you will have to push that pixel size to cv2 to inform the library of the new default pixels size you want. But in this tutorial we will stick with the default pixel sizes.

Illustration 4:

In Illustration 5: we will define our time stamp. We will use now() function to return to us the current date and time of our system. Then use that data as the name of our Image File Container. You can name the variable anything you like but I like to know what purpose each one of my variable has at a glance by giving them full names. Again you can name you variable anything you like to keep up with them. We use datetime.datetime twice because at our imports we imported the whole datetime library.

Illustration 5:

In Illustration 6: we define the filename of our image container. At this point we will pass in the current datetime and the formatting we want datetime to use. The curly braces {}, are a place holder for the formatting data. The .avi, is the video format we want a video to have once the recording process is complete. The .format, allows use to customize the format of the datetime output from camera1_recorder_time_stamp. The strftime, allow us to convert the integer data from datetime to string data that is needed by our curly braces {}. strftime takes a string with formatting. These are the defaults for Year, Month, Day, Hour, Minute, Second.

Illustration 6:

In Illustration 7: we define our codex for the video. We call the VideoWriter_fourcc() function to tell opencv what type of encoding we would like to use. This is determined by what format you want to save the video in. Here is a great source of information for the many types of CODEX. This is where I went to find the information I needed. If you have question Contact US.

Illustration 7:

In Illustration 8: we define our full file path and filename for our VideoWriter. We will call on OS again to join both our output path and filename which we defined earlier. This will allow us to feed this new full one string input to the VideoWriter which take a string argument in the first slot.

Illustration 8:

In Illustration 9: we define our image container output. We use VideoWriter to write our data to the image container. We will pass it our full VideoPath, Codex, Frames Per Second (How fast our video will play back.), Width, Height. This will complete our image container. And allow us to record multiple videos and time in seconds pass. Be sure to watch the whole YouTube Video for more detail. We print put recording because this will the start of opencv opening the camera and streaming in our feed.

Illustration 9:

While Loop:

In Illustration 10: we create our while loop. A while loop will loop through itself until the condition Is False.

Example: While the sky is (blue), run the code below. Once the sun sets the sky will not be blue so the while loop will be false and exit the loop.

In the tutorial we will set the while loop to True. This means that the while loop will run forever because while run on a True condition. By setting the while loop to True it will never see False. So now while True we tell cv2 to capture the feed from our webcam by calling our variable webcam and have it call the read() function from cv2. This will give us a constant stream of data which we will store in two new variable frame_captured and camera_status. The read() function send back two outputs. One for frames it sees, and one for the status of the camera which is ether True or False. This also allows you to place a if function check over all the code below to avoid error.

Illustration 10:

In Illustration 11: we will write the data received from the read() function to the our finished output variable. To do this we will use the VideoWriter from cv2 and call its write() function to allow use to write image data to our image container. The write () takes an input argument. We will pass in the data from frame_captured which webcam.read is supplying us with a live feed of data.

Illustration 11:

In Illustration 12: we will display whats being seen and recorded by our camera. We will use the imshow() function from cv2. The imshow() function has two arguments we will be using. The first argument is a string. This string will be the title of our window, “OpenCV Video Recording Training”. The second argument will be the source of our frame data coming in. This we will pass frame_captured because as webcam.read() is reading the data from the data stream the frame_captured container is use to store all current image data after reading.

Illustration 12:

In Illustration 13: Now we are all set to lock in our recording functionality. If you do not set a wait key for cv2 you will be able to record the video but you will not have control over when the program stops and you would be missing out on a clean way to perform the clean you necessary for cv2 resources.

So let now set up our wait key and our clean up functionality. We will start with creating a new if statement to contain our clean up code, this way we can control when our cleanup code runs and termination our program in one area. From cv2 we will call the waitkey() function and the keyboard. The waitkey() function will wait for (int) milliseconds for a keyboard key to be pressed on our imshow() display window. Once it detects that keyboard press it will continue with the code below. In this tutorial we will use 1 millisecond and the keyboard press q.

So If the waitkey duration is met and the keyboard key is press only then will we move on to the code below else we run the code above forever. Now that we are done with our clean up/termination trigger we can work on the actual clean up/termination. Clean up consist of releasing the Camera resource, the VideoWriter resource, and the Display Window resource. We will also print status updates to tell use at what stage of the clean up our program is.

We perform the Camera clean up by calling the webcam.release() function. The release() function removes the lock we acquired on the default so a different program can acquired it. We could have used threading or multiprocessing to grab an instance of the camera and only close our instance making the camera acquirable by other processes at the same time. But that would beyond the scope of the beginner tutorial.

For now we will just release the camera fully. Next we will call the release() function on the VideoWriter. This will do the same as the camera and release it fully. Lastly we will call the destroyallwindows() function. The will clean up the display window we were using from imshow() to view our image data feed. Now we call our Break. This will allow us to exit our while loop and continue to the end of our program successfully terminating because there is no more code to run.

Illustration 13:

In Illustration 13: Pass is use as a filler when you don’t have code written yet for a if statement or definition. I like to leave the in because they give me a indicator of where my blocks of code end visually. You can remove them if you wish its up to you.

Conclusion:

In Illustration 14: Now we are at the beginning of our program. I know that seems weird do to the top of the page being above us that’s programming for you lol, bare with me. We will create our entry point here after our definition above. Since definitions are not called automatically the interpreter will ignore the definition and hit our if statement below first.

To explain If name = main, since we are calling the interpreter from this module the variable name is set to main. Which is the name of our module(our program). Then from within this module we want to call VideoCapture() and return the results of the definition. You can ask the interpreter to return the results my using the () parentheses at the end of your definition name. If you remove the () parentheses at the end you are ask the interpreter to only run the definition but don’t return anything back to you. Try It.

Illustration 14:

Idea Behind Cryo Enterprise LLC:

I wanted to help anyone looking to get stated with python and opencv and didn’t know where to start. I hoped that this will be a start to building a great project that does amazing things. The upgrade potential for this and your projects are limitless. Never let your imagination become small. If You Can Dream It, Then Your Dreams Can Become Reality.Never Give Up Trying To Learn Something New.Always Strive To Improve And Get Better In What You Believe In.You Are Great, You Are Amazing And All Of Us At Cryo Enterprise LLC Believe In You.

Thank You For Reading:

Remember to:

Follow, Like, and Subscribe

So you can stay up to date on our latest projects. Let me know if this video help you? How did it help you? Did you learn something new? Comment and let us know at:

Website: CryoEnterprise

TikTok: TikTok

Twitter: Twitter

YouTube: YouTube

GitHub: GitHub

Thank You,

For Your Time Spent With Us At Cryo Enterprise LLC

We Appreciate You Reading Our Tech Blog

We Hope You Enjoy Your Time At CryoEnterprise.com

Have A Wonderful Day

Leave a Reply

Your email address will not be published. Required fields are marked *

18 − five =

Subscribe

Sign up with your email address to receive our weekly news


Categories


Search