One way to do this might be to start a separate thread that reads the video file at its normal speed and stuffs each frame in a global variable. The main thread then just grabs that frame when it's ready.

So, if we use a video that just displays the time and the frame counter, we can grab a frame here and there as the fake camera updates the frame:

#!/usr/bin/env python3

import cv2
import sys
import time
import logging
import numpy as np
import threading, queue

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s %(message)s')

# This is shared between main and the FakeCamera
currentFrame = None

def FakeCamera(Q, filename):
    """Reads the video file at its natural rate, storing the frame in a global called 'currentFrame'"""
    logging.debug(f'[FakeCamera] Generating video stream from {filename}')

    # Open video
    video = cv2.VideoCapture(filename)
    if (video.isOpened()== False):
       logging.critical(f'[FakeCamera] Unable to open video {filename}')
       Q.put('ERROR')
       return

    # Get height, width and framerate so we know how often to read a frame
    h   = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    w   = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    fps = video.get(cv2.CAP_PROP_FPS)
    logging.debug(f'[FakeCamera] h={h}, w={w}, fps={fps}')

    # Initialise currentFrame
    global currentFrame
    currentFrame = np.zeros((h,w,3), dtype=np.uint8)

    # Signal main that we are ready
    Q.put('OK')

    while True:
        ret,frame = video.read()
        if ret == False:
            break
        # Store video frame where main can access it
        currentFrame[:] = frame[:]
        # Try and read at appropriate rate
        time.sleep(1.0/fps)

    logging.debug('[FakeCamera] Ending')
    Q.put('DONE')

if __name__ == '__main__':

    #  Create a queue for synchronising and communicating with our fake camera
    Q = queue.Queue()

    # Create a fake camera thread that reads the video in "real-time"
    fc = threading.Thread(target=FakeCamera, args=(Q,'video.mov'))
    fc.start()

    # Wait for fake camera to intialise
    logging.debug(f'[main] Waiting for camera to power up and initialise')
    msg = Q.get()
    if msg != 'OK':
        sys.exit()

    # Main processing loop should go here - we'll just grab a couple frames at different times
    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(2000)

    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(5000)

    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(2000)

    # Wait for buddy to finish
    fc.join()

Sample Output

DEBUG [FakeCamera] Generating video stream from video.mov
DEBUG [main] Waiting for camera to power up and initialise
DEBUG [FakeCamera] h=240, w=320, fps=25.0
DEBUG [FakeCamera] Ending

Keywords: Python, image processing, OpenCV, multi-thread, multi-threaded, multithread, multithreading, video, fake camera.

Answer from Mark Setchell on Stack Overflow
🌐
OpenCV
opencv.org › home › news › reading and writing videos using opencv
Reading and Writing Videos using OpenCV
March 28, 2025 - Reading a video file requires processing each frame individually, and then displaying or storing it as needed. OpenCV provides the VideoCapture() function for this purpose, allowing users to load video files and access webcam streams in real-time.
🌐
OpenCV
forum.opencv.org › uncategorized
OpenCV. How do you catch a real time frame from OpenCV Video Capture - Uncategorized - OpenCV
October 16, 2023 - Hello, I have a question about the following OpenCV code for reading videos. I’m working on a project that involves processing frames from a video using this code. From what I understand, when the video capture input is a video file, it processes the first frame before moving to the next one, resulting in a delay between frames.
Discussions

python - How to simulate a video in real time and be able to extract its frames? - Stack Overflow
But he wanted a solution that was more real. Thank you very much for helping! ... Save this answer. ... Show activity on this post. One way to do this might be to start a separate thread that reads the video file at its normal speed and stuffs each frame in a global variable. The main thread then just grabs that frame when it's ready. So, if we use a video that just displays the time ... More on stackoverflow.com
🌐 stackoverflow.com
How to display and read a live camera video in Python OpenCV - Stack Overflow
I've been working on a code from the Roboflow team that is suppose to display a live video capture and give it's predictions from the model that I trained, but I encounter an error. Get webcam inte... More on stackoverflow.com
🌐 stackoverflow.com
How to display and read a live camera video in Python OpenCV
That usually means you’re getting an error back from the server. Likely due to wrong model endpoint or API Key. First glance looks like you might not have included the dataset version. Should look something like “your-project/1” (or whatever version you’re on). You’ll also want to revoke the api key you included in this post. More on reddit.com
🌐 r/roboflow
3
1
August 7, 2022
OpenCV and Video Capture with Python
Change every ** to \\ on line 13. More on reddit.com
🌐 r/learnpython
5
9
August 27, 2015
🌐
Reddit
reddit.com › r/opencv › [question] how to read livestream video from web server?
r/opencv on Reddit: [Question] How to read livestream video from web server?
May 9, 2024 -

Recently I'm interested in doing video processing on video live-streamed by ESP32-CAM on web server.

I knew how to read image and video from computer folder, but I don't know how to read video from web server.

Is there any example project or tutorial that teaches how to read and process live video from web server by ESP32-CAM using OpenCV, preferably in C++ language?

🌐
LearnOpenCV
learnopencv.com › home › read, write and display a video using opencv
Read, Write and Display a video using OpenCV | LearnOpenCV
July 31, 2026 - A tutorial on how to read, write and display a video using OpenCV. OpenCV-Python and OpenCV-C++ Code is provided for practice and understanding.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-play-a-video-using-opencv
Python | Play a video using OpenCV - GeeksforGeeks
December 4, 2025 - import cv2 # Load the video file cap = cv2.VideoCapture("video.mp4") # Check if the video opened correctly if not cap.isOpened(): print("Error: Could not open video file.") exit() # Read and display video frames while True: ret, frame = cap.read() if not ret: break # No more frames -> exit loop cv2.imshow("Video", frame) # Press Q to quit if cv2.waitKey(25) & 0xFF == ord('q'): break # Release resources cap.release() cv2.destroyAllWindows() ... Note : Video file should have in same directory where program is executed. ... VideoCapture() loads the video. ... Pressing Q exits the loop. After the video ends, OpenCV releases the video and closes all windows.
Top answer
1 of 1
3

One way to do this might be to start a separate thread that reads the video file at its normal speed and stuffs each frame in a global variable. The main thread then just grabs that frame when it's ready.

So, if we use a video that just displays the time and the frame counter, we can grab a frame here and there as the fake camera updates the frame:

#!/usr/bin/env python3

import cv2
import sys
import time
import logging
import numpy as np
import threading, queue

logging.basicConfig(level=logging.DEBUG, format='%(levelname)s %(message)s')

# This is shared between main and the FakeCamera
currentFrame = None

def FakeCamera(Q, filename):
    """Reads the video file at its natural rate, storing the frame in a global called 'currentFrame'"""
    logging.debug(f'[FakeCamera] Generating video stream from {filename}')

    # Open video
    video = cv2.VideoCapture(filename)
    if (video.isOpened()== False):
       logging.critical(f'[FakeCamera] Unable to open video {filename}')
       Q.put('ERROR')
       return

    # Get height, width and framerate so we know how often to read a frame
    h   = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    w   = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    fps = video.get(cv2.CAP_PROP_FPS)
    logging.debug(f'[FakeCamera] h={h}, w={w}, fps={fps}')

    # Initialise currentFrame
    global currentFrame
    currentFrame = np.zeros((h,w,3), dtype=np.uint8)

    # Signal main that we are ready
    Q.put('OK')

    while True:
        ret,frame = video.read()
        if ret == False:
            break
        # Store video frame where main can access it
        currentFrame[:] = frame[:]
        # Try and read at appropriate rate
        time.sleep(1.0/fps)

    logging.debug('[FakeCamera] Ending')
    Q.put('DONE')

if __name__ == '__main__':

    #  Create a queue for synchronising and communicating with our fake camera
    Q = queue.Queue()

    # Create a fake camera thread that reads the video in "real-time"
    fc = threading.Thread(target=FakeCamera, args=(Q,'video.mov'))
    fc.start()

    # Wait for fake camera to intialise
    logging.debug(f'[main] Waiting for camera to power up and initialise')
    msg = Q.get()
    if msg != 'OK':
        sys.exit()

    # Main processing loop should go here - we'll just grab a couple frames at different times
    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(2000)

    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(5000)

    cv2.imshow('Video',currentFrame)
    res = cv2.waitKey(2000)

    # Wait for buddy to finish
    fc.join()

Sample Output

DEBUG [FakeCamera] Generating video stream from video.mov
DEBUG [main] Waiting for camera to power up and initialise
DEBUG [FakeCamera] h=240, w=320, fps=25.0
DEBUG [FakeCamera] Ending

Keywords: Python, image processing, OpenCV, multi-thread, multi-threaded, multithread, multithreading, video, fake camera.

🌐
Note.nkmk.me
note.nkmk.me › home › python › opencv
Capture video from camera/file with OpenCV in Python | note.nkmk.me
October 19, 2022 - In Python, you can read, capture, and display video files and camera stream using the VideoCapture class with OpenCV. Note that Video I/O must be enabled in OpenCV to process video. OpenCV: cv::VideoC ...
🌐
OpenCV
docs.opencv.org › 4.13.0 › dd › d43 › tutorial_py_video_display.html
OpenCV: Getting Started with Videos
Class for video capturing from video files, image sequences or cameras. ... Displays an image in the specified window. ... Waits for a pressed key. ... Destroys all of the HighGUI windows. ... void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0, AlgorithmHint hint=cv::ALGO_HINT_DEFAULT) Converts an image from one color space to another. cap.read() returns a bool (True/False).
Find elsewhere
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 209740 › reading-captured-video-data-using-opencv-in-real-time
Reading captured video data using OpenCV in real-time - OpenCV Q&A Forum
March 3, 2019 - If you capture data using your camera at 30 or 60 fps and you would like to run an algorithm on it using OpenCV, you can load it and read it frame by frame using the VideoCapture() class. You will process every frame and the Total processing time = Avg. processing time of a frame * Number of frames.
🌐
Stack Overflow
stackoverflow.com › questions › 73147343 › how-to-display-and-read-a-live-camera-video-in-python-opencv
How to display and read a live camera video in Python OpenCV - Stack Overflow
I've been working on a code from the Roboflow team that is suppose to display a live video capture and give it's predictions from the model that I trained, but I encounter an error. ... cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' I've seen online saying that my image file location is wrong and that's why I get this error, but I'm confused as it is suppose to be showing a live camera constantly instead of just a still image.
🌐
YouTube
youtube.com › watch
Power Up Your CV Projects: Real-Time Camera and Video Streaming with OpenCV and Sockets - YouTube
If you’re looking for courses and to extend your knowledge even more, check out this link here: 👉 https://www.nicos-school.com/ ➡️ get 20% OFF with the cod...
Published: March 26, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-opencv-capture-video-from-camera
Python OpenCV: Capture Video from Camera - GeeksforGeeks
July 12, 2025 - Create a VideoWriter object to save captured frames as a video in the computer. Set up an infinite while loop and use the read() method to read the frames using the above created object.
🌐
YouTube
youtube.com › watch
Live Video Processing with OpenCV - YouTube
This Introduction to the Live Video Processing with OpenCV training video explains how to capture live video, perform face detection in real time using OpenC...
Published: March 12, 2019
Views: 49K
Starred by 59 users
Forked by 17 users
Languages: Java
🌐
Towards Data Science
towardsdatascience.com › home › latest › video streaming in web browsers with opencv & flask
Video Streaming in Web Browsers with OpenCV & Flask | Towards Data Science
March 5, 2025 - Most IP cameras are RTSP (Real Time Streaming Protocol) based and is therefore "not supported**" natively in internet browsers. ... In this article we will learn how to do that using Computer Vision. Computer Vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding from digital images or videos. For implementing the computer vision part we will use the OpenCV module in Python and to display the live stream in the web browser we will use the Flask web framework.
🌐
Educative
educative.io › answers › how-to-capture-a-frame-from-real-time-camera-video-using-opencv
How to capture a frame from real-time camera video using OpenCV
The read() function returns a tuple of size 2. The first element of the tuple is a true or false, depending on whether the frame was captured successfully, and the second element of the tuple contains the actual video frame if it was successfully ...
🌐
Medium
arshren.medium.com › read-and-write-videos-using-opencv-7f92548afcba
Read and Write Videos using OpenCV | by Renu Khandelwal | Medium
April 19, 2022 - Create a video capture object to stream a video from the camera or read the video from a prerecorded video using VideoCapture().The VideoCapture() needs the device index or the video file's name as its input parameter.
🌐
Medium
medium.com › @betul.gurbuz.dev › video-basics-with-opencv-d130d56f9add
Video Basics with OpenCV. Connect OpenCV to a WebCam, Write a… | by Betul Gurbuz | Medium
March 23, 2024 - The project captures real-time images from a webcam using the OpenCV library and YOLOv8 model. It performs object detection on these images, applies various analytic processes, and displays the results on the screen.
🌐
LearnOpenCV
learnopencv.com › home › image processing › reading and writing videos using opencv
Reading and Writing Videos using OpenCV | LearnOpenCV
October 15, 2025 - Reading a video stream from a web camera is also very similar to the examples discussed above. How’s that possible? It’s all thanks to the flexibility of the video capture class in OpenCV, which has several overloaded functions for convenience that accept different input arguments.
🌐
Medium
medium.com › nerd-for-tech › live-streaming-using-opencv-c0ef28a5e497
Live Streaming using OpenCV. At least once we have used live… | by Abhishek Prasad Kesare | Medium
June 11, 2021 - Here first we have imported required libraries for socket and OpenCV and ‘s’ stores the address of the socket.AF_INET represents the IP family v4 and socket.SOCK_DGRAM this keyword is for UDP protocol, And the third line will create a buffer size so that we can store a buffer of data to transmit it continuously. “serveip” and “serverport” hold the IP address and port number of the server. cap = cv2.VideoCapture(0) while True: ret,photo = cap.read() cv2.imshow('streaming', photo) ret, buffer = cv2.imencode(".jpg", photo,[int(cv2.IMWRITE_JPEG_QUALITY),30]) x_as_bytes = pickle.dumps(buffer) s.sendto(x_as_bytes,(serverip , serverport)) if cv2.waitKey(10) == 13: break cv2.destroyAllWindows()cap.release()