How to Capture Live Video Stream from an IP Camera Using Python

Connect with me on LinkedIn to network, and visit my Github for my latest projects. In this article, we will walk through how to capture and display a live video feed from an IP camera using Python. We’ll use libraries like requests for fetching images from a URL, OpenCV for processing the images, and imutils for resizing the images. We’ll write a Python script to continuously retrieve the video feed from a camera and display it on the screen. By the end of this article, you’ll understand how to capture and display video frames from a network camera in real-time, and how to adapt this setup for various IP camera streams. Objective The goal of this tutorial is to demonstrate how to: Fetch video frames from an IP camera using HTTP. Process the frames using OpenCV for display. Continuously retrieve and display images in real-time from the camera feed. Set up a loop to display the stream until the user decides to exit by pressing a key. The final result will be a live video stream displayed on your screen, with the ability to exit by pressing the Esc key. Prerequisites Before we dive into the code, you need to have the following libraries installed: requests: To send HTTP requests and retrieve the image data. opencv-python: To process and display the images. imutils: A set of convenience functions to make OpenCV easier to use. You can install these libraries using the following commands: pip3 install requests pip3 install opencv-python pip3 install imutils Additionally, you’ll need access to an IP camera or any device streaming video via an HTTP feed (for example, a webcam streaming via MJPEG on port 8080). Approach Using IP Webcam App on Your Mobile Device: Download and install the IP Webcam application on your mobile phone. This app turns your phone into an IP camera. Ensure that both your PC and phone are connected to the same network. **3. **Launch the IP Webcam application on your phone. Tap on the “Start Server” option. This will start the camera stream on your phone. A URL will appear on your phone screen. It will look something like http://192.168.0.101:8080/video. You’ll use this URL to fetch the video stream in your Python script. On your PC, open the URL in your web browser to verify that the camera feed is working. Under the Video Renderer section, select Javascript to render the stream in the browser. Now that we have set up the camera, let’s dive into the Python code. Code Explanation Here’s the complete Python script that retrieves and displays the video stream from an IP camera: # Import essential libraries import requests import cv2 import numpy as np import imutils # Replace the below URL with your own. Make sure to add "/shot.jpg" at last. url = "http://:8080/shot.jpg" url = "http://192.168.0.101:8080/shot.jpg" # While loop to continuously fetch data from the URL while True: # Request the image from the camera URL img_resp = requests.get(url) # Convert the content of the response to a NumPy array img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8) # Decode the image from the NumPy array into an image format that OpenCV can display img = cv2.imdecode(img_arr, -1) # Resize the image for better display (optional) img = imutils.resize(img, width=1000, height=1800) # Display the image in a window named "Android_cam" cv2.imshow("Android_cam", img) # Wait for a key press to exit the loop (Esc key code is 27) if cv2.waitKey(1) == 27: break # Close all OpenCV windows after the loop ends cv2.destroyAllWindows() Step-by-Step Explanation 1. Importing Libraries: requests: For making HTTP requests to fetch the image data from the camera. cv2: OpenCV, used for image processing and displaying the frames. numpy: For handling arrays, which is required for converting the image data into a format that OpenCV can use. imutils: A library to simplify common OpenCV tasks, like resizing images. 2. Setting the Camera URL: The URL of the camera stream is defined. In this example, the URL http://:8080/shot.jpg represents the endpoint for the camera feed. Replace this with your phone’s actual IP address and the correct endpoint for the video feed. 3. Fetching the Image: Inside a while True loop, we continuously request the image from the specified URL using requests.get(url). The content of the response (img_resp.content) is converted into a NumPy array using np.array(). This allows us to pass the raw image bytes into OpenCV for decoding. 4. Decoding and Resizing: cv2.imdecode() is used to decode the image into a format that OpenCV can process (essentially converting the raw byte array into an image object). The image is resized using imutils.resize(), which ensures the image fits nicely into the window. This is particularly helpful for large images that may otherwise not fit on the screen. 5. Displaying the Image: We use c

Jan 16, 2025 - 12:23
How to Capture Live Video Stream from an IP Camera Using Python

Connect with me on LinkedIn to network, and visit my Github for my latest projects.

In this article, we will walk through how to capture and display a live video feed from an IP camera using Python. We’ll use libraries like requests for fetching images from a URL, OpenCV for processing the images, and imutils for resizing the images. We’ll write a Python script to continuously retrieve the video feed from a camera and display it on the screen.
By the end of this article, you’ll understand how to capture and display video frames from a network camera in real-time, and how to adapt this setup for various IP camera streams.

Objective

The goal of this tutorial is to demonstrate how to:

  • Fetch video frames from an IP camera using HTTP.
  • Process the frames using OpenCV for display.
  • Continuously retrieve and display images in real-time from the camera feed.
  • Set up a loop to display the stream until the user decides to exit by pressing a key.

The final result will be a live video stream displayed on your screen, with the ability to exit by pressing the Esc key.

Prerequisites

Before we dive into the code, you need to have the following libraries installed:

  • requests: To send HTTP requests and retrieve the image data.
  • opencv-python: To process and display the images.
  • imutils: A set of convenience functions to make OpenCV easier to use.

You can install these libraries using the following commands:

pip3 install requests
pip3 install opencv-python
pip3 install imutils

Additionally, you’ll need access to an IP camera or any device streaming video via an HTTP feed (for example, a webcam streaming via MJPEG on port 8080).

Approach

Using IP Webcam App on Your Mobile Device:

  1. Download and install the IP Webcam application on your mobile phone. This app turns your phone into an IP camera.
  2. Ensure that both your PC and phone are connected to the same network. **3. **Launch the IP Webcam application on your phone. Tap on the “Start Server” option. This will start the camera stream on your phone.
  3. A URL will appear on your phone screen. It will look something like http://192.168.0.101:8080/video. You’ll use this URL to fetch the video stream in your Python script.
  4. On your PC, open the URL in your web browser to verify that the camera feed is working. Under the Video Renderer section, select Javascript to render the stream in the browser.

https://192.168.0.101:8080 Browser on Video Renderer

Now that we have set up the camera, let’s dive into the Python code.

Code Explanation

Here’s the complete Python script that retrieves and displays the video stream from an IP camera:

# Import essential libraries 
import requests 
import cv2 
import numpy as np 
import imutils 

# Replace the below URL with your own. Make sure to add "/shot.jpg" at last. 
url = "http://:8080/shot.jpg"
url = "http://192.168.0.101:8080/shot.jpg"

# While loop to continuously fetch data from the URL
while True:
    # Request the image from the camera URL
    img_resp = requests.get(url) 

    # Convert the content of the response to a NumPy array
    img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8) 

    # Decode the image from the NumPy array into an image format that OpenCV can display
    img = cv2.imdecode(img_arr, -1)

    # Resize the image for better display (optional)
    img = imutils.resize(img, width=1000, height=1800)

    # Display the image in a window named "Android_cam"
    cv2.imshow("Android_cam", img) 

    # Wait for a key press to exit the loop (Esc key code is 27)
    if cv2.waitKey(1) == 27: 
        break

# Close all OpenCV windows after the loop ends
cv2.destroyAllWindows()

Step-by-Step Explanation

1. Importing Libraries:

  • requests: For making HTTP requests to fetch the image data from the camera.
  • cv2: OpenCV, used for image processing and displaying the frames.
  • numpy: For handling arrays, which is required for converting the image data into a format that OpenCV can use.
  • imutils: A library to simplify common OpenCV tasks, like resizing images.

2. Setting the Camera URL:

  • The URL of the camera stream is defined. In this example, the URL http://:8080/shot.jpg represents the endpoint for the camera feed. Replace this with your phone’s actual IP address and the correct endpoint for the video feed.

3. Fetching the Image:

  • Inside a while True loop, we continuously request the image from the specified URL using requests.get(url).
  • The content of the response (img_resp.content) is converted into a NumPy array using np.array(). This allows us to pass the raw image bytes into OpenCV for decoding.

4. Decoding and Resizing:

  • cv2.imdecode() is used to decode the image into a format that OpenCV can process (essentially converting the raw byte array into an image object).
  • The image is resized using imutils.resize(), which ensures the image fits nicely into the window. This is particularly helpful for large images that may otherwise not fit on the screen.

5. Displaying the Image:

  • We use cv2.imshow() to display the image in a window called "Android_cam".
  • The loop continues indefinitely, fetching and displaying frames from the camera. 6. Exiting the Loop: The cv2.waitKey(1) function waits for a key press. If the user presses the Esc key (key code 27), the loop breaks, and the video display window is closed.

7. Cleaning Up:

Finally, cv2.destroyAllWindows() ensures that all OpenCV windows are closed when the loop ends.

How to Run the Script

  1. Ensure your IP camera (or mobile device) is up and running.
  2. Update the URL in the script to point to your camera’s image stream (from your IP Webcam app).
  3. Save the script as video.py.
  4. Run the script using the following command:
python video.py

The video stream should start displaying in a new window.

Conclusion
In this article, we’ve successfully implemented a Python script that fetches and displays a live video stream from an IP camera. By using libraries like requests, OpenCV, and imutils, we were able to easily handle HTTP requests, process image data, and display it in real-time.
This script can be adapted for various use cases, such as:

  • Real-time video surveillance systems.
  • IP camera integration with other Python-based applications.
  • Live video streaming analysis or processing.

By modifying the script, you can integrate more advanced functionalities, such as motion detection, image processing, and saving the video stream for later use.