Video Streaming With Python in Just 10 Lines of Code!
Hello Everyone and Welcome to the Python AI Series 🧠
One of the minimum requirements you'd need to run any real-time Computer Vision application is getting live camera feed into the computer, that is, video streaming🎥
I'm Sai Ashish and today, we are going to write our very own program for live video streaming using the OpenCV library of Python using just 10 lines of code🤯
Are you geared up? Let's go 🚀
In this article, we are going to explore:
1. What is Video Streaming? 2. Applications of Video Streaming 3. The OpenCV library 4. How to read frame from camera using OpenCV
1. What is Video Streaming?
Video is a series of moving images played in a loop. Streaming is a way via which we can listen or view a form of media without downloading it. In technical terms, video streaming is the continuous transmission of video files from a server(the host computer) to a client (the recipient computer).
2. Applications of Video Streaming
Video Streaming is the preliminary step that one has to perform to implement any live computer vision applications such as
- Face detection & recognition
- Moving object detection & tracking
- Emotion Recognition
- Face Mask Detection
- Traffic Management
Commonly, Video Streaming has other applications such as:
- CCTV Surveillance
- Video Conferences
- Online content such as movies, tv series etc.
3. Video Streaming with Python
To obtain the live feed from camera, we will use the OpenCV library of Python.
What is OpenCV?
For Computer Vision, we have a library in Python called OpenCV. OpenCV is open source, used by over 9 million people, and is funded by companies like Google, Intel and AMD. Moreover, you can use it for commercial applications without making your project open source.
4. Time To Code:
To install OpenCV in your system, you've to install Numpy as OpenCV uses it in the background. We will also install matplotlib for features of image display. Go your terminal and enter:
pip install numpy pip install opencv-python pip install matplotlib
This will install the required libraries into your environment.
The first step to our build is to import cv2. cv2 is an interface of OpenCV that we need to load in our environment to access its features. We do that using the
#importing the required library import cv2
To capture the video, we use the VideoCapture() function of OpenCV.
We implement it as:
#initialise the primary camera for video capture vs = cv2.VideoCapture(0)
0 in VideoCapture(0) signifies to use the primary camera of your device. It is the device index. If you have more than one camera attached to your system, you may have to change this number to 1 or 2 depending on which camera you want to use.
As discussed earlier, a video is nothing but a series of images or frames. To continuously capture these frames, we initialise an infinite while loop.
To read an image, we use the function for video, we use the read() function as:
#obtain the frame from the camera image = vs.read()
The vs.read() returns 2 objects,
- A Boolean object which gives True if frame is read from the camera and false if not
- The Frame captured
As we are interested only in the frame, we use the , indicating the second parameter.
You can also write the above statement as:
#obtain the frame from the camera _,img = vs.read()
Both perform the exact same operation.
Next, we would like to display the Video Captured on our screen. To do that, we use the imshow() function as:
#display the video stream cv2.imshow("VideoStream", img)
We give the title of the window as VideoStream and pass the frame obtained above for display.
As we saw in the The Easiest Guide to Get You Started on Computer Vision article, to view an image for a particular duration, we use the waitKey() function.
We want each frame obtained from the camera to be displayed for 1 millisecond.
key = cv2.waitKey(1)
What I didn't mention in the guide was that when you initialise waitKey(1) it returns a 32 bit integer value of the key pressed. If no key on the keyboard is pressed, it returns -1. This is going to be useful in terminating our video stream.
We perform the logical AND operation of this value obtained in
key variable with 0xFF( hexadecimal constant which is basically 11111111 in binary, i.e. a 8-bit integer). By performing AND, we effectively get the last 8 digits of the 32-bit integer, as the other 24 bits are set to 0.
#masking the values and obtaining the key key = cv2.waitKey(1) & 0xFF
We perform masking as the values in the keyboard range from 0 - 255, i.e. 8 bits.
#terminate the loop if user presses 'q' if key == ord("q"): break
The ord() function returns the Unicode code of any character. In the above snippet, we compare if the key pressed is q we want the control to break out of the loop.
Once, the loop is terminated, we want to release the camera we held as an object, else you won't be able to access your camera for other applications. To do that, we use the release() function.
#release the camera and stop streaming vs.release()
For good coding practice, we will use
destroyAllWindows() function. This destroys all the open windows when you exit the program.
#destroy all windows cv2.destroyAllWindows()
The Final Source Code Looks Like This:
You can directly download the source code for the project from my Github Repository. And while you're at it, don't forget to twinkle the star in my repository🌟
Let's recollect the steps for video streaming using python:
1. Initialise the camera using VideoCapture() 2. Set an infinite loop 3. Read the frame from the camera using read() 4. Display the frame obtained for 1ms using imshow() and waitKey() 5. If user presses q on the keyboard terminate the loop 6. Release the camera and stop streaming using release()
And that's it 💯 If this article provided value to you, smash the like button and share this article with as many friends as possible because the wait is finally over🔥 In the very next article of this series, we would be building our very own program for Face Detection using Python 🐍 Until then, take care 🙋🏻♂️
Bonus Insights by The Insightful Coder :
Interested in Building Creative Beginner-Level Python Projects🐍?: Check out the Python Projects for Beginners Series😍
Wanna Discover Some Valuable Tech-Hacks 🛠?: Check out the Tech-Hacks for Everybody Series😎
I'm also dropping daily value bombs and development insights on my Instagram Page. Make sure to follow me up 💯
Find and Download All My Project Source Codes at My Github Repository 🎁