Signup/Sign In

Capture Videos and Images with Python (Part-2)

Posted in Programming   LAST UPDATED: MAY 26, 2023

    Welcome to Part 2 of our series on capturing videos and images with Python! In this article, we will delve deeper into the fascinating world of multimedia manipulation and explore advanced techniques for capturing videos and images using Python.

    In our previous article, we got the basic intuition about Computer Vision and a brief introduction to the OpenCV library. If you are new to OpenCV, learn the basics from the first part of this series here: Introduction to OpenCV using Python Part-1.

    In the previous article, we covered all the basics, and by the end of this article, you will be able to write Python programs that can Capture Images from your device's webcam and also capture videos.

    Get ready to discover how to handle real-time video streams, apply image processing techniques, and even build your own custom camera applications using Python. We'll dive into popular libraries like OpenCV and explore their powerful features for capturing, processing, and analyzing multimedia.

    By the end of this article, you'll have the knowledge and tools to capture videos and images like a pro. So, let's continue our multimedia adventure and unlock the endless possibilities Python offers!

    Requirements:

    1. Python 3.6 or higher
    2. OpenCV library (Installed)

    If you need information regarding the installations refer to the article Introduction to OpenCV using Python Part-1

    How to Capture Videos and Images with Python (Part-2)

    use openCV to capture video and image using python


    Capture Video Stream

    Let's begin with a program to access your web camera and display its Live Feed.

    As always import the library using the following statement,

    import cv2

    This statement includes the OpenCV library in our program/script, now we can access all the methods and properties available in this library.

    In OpenCV, to capture/create an Image or Video we use the VideoCapture() method which allows us to capture the video stream from our webcam.

    The VideoCapture() method is accessed using the cv2 namespace as follows:

    videoStreamObject = cv2.VideoCapture(0)

    You can see in the above code statement that, the VideoCapure() method accepts an integer value as an argument. This integer value represents the camera connected to the device. In almost every laptop, the integrated web camera is the first camera and can be accessed by passing the value as 0(zero). If your desktop/laptop has any other camera connected you can change the value to 1.

    Basically, it’s an array with indices pointing to the different available cameras.

    Thus the above statement will create an VideoCapture object and will return it, hence we are storing the value in a variable (here our variable name is videoStreamObject). Since a video is a stream of picture frames, using this VideoCapture object we will access the camera and retrieve each frame and display it on the screen.

    cap, frame = videoStreamObject.read()

    The VideoCapture object has a method read(), which when executed starts accessing the camera stream and returns a tuple. The first value is a Boolean value representing whether a frame is captured correctly or not. With this, you can know at the end of a video capture whether all the frames are captured correctly or not.

    The second value is the captured frame, which is basically a numpy array.

    Now to display this frame on a window we use the OpenCV library’s imshow() method. The imshow() method takes in two arguments, the first one is the Title to be displayed on the window, this argument is a string and the second argument is the frame to be displayed.

    cv2.imshow('Capturing Video',frame)

    With this code, we can only capture a single frame, but a video is a stream of frames, hence this whole code should be placed in an indefinite loop like while loop.

    To stop displaying a video stream, we use the cv2.waitKey() method which is method that waits for the user's response through a key press. When the user presses a specific key we have to stop displaying the imshow() window and also stop accessing the video capture.

    This waitKey() method takes an argument of type integer denoting the number of seconds to wait for the key press.

    cv2.waitKey(1) & 0xFF == ord(‘q’)

    This is the condition we will be using to know when the user wants to stop the video capture. The second part of the above statement specifies that the value captured is compared with the ASCII value of the letter ‘q’ using the ord() function.

    Whenever we meet this condition we will release the web camera from which we are capturing the frames and destroy the window that is created earlier using the imshow() method.

    videoCaptureObject.release()

    The above code will release the camera.

    cv2.destroyAllWindows()

    And the above code will destroy all the windows that were created during this process.

    Python Program:

    Here’s the complete code for you,

    import cv2
    
    videoCaptureObject = cv2.VideoCapture(0)
    while(True):
        ret,frame = videoCaptureObject.read()
        cv2.imshow('Capturing Video',frame)
        if(cv2.waitKey(1) & 0xFF == ord('q')):
            videoCaptureObject.release()
            cv2.destroyAllWindows()


    Capture the Image and Save it

    Capturing an Image and saving it is very simple because we can use the VideoCapture object to start accessing the web camera's stream, but in this case, after reading the first frame we will simply store that image using the cv2.imwrite() method which accepts two arguments, the first one is the location where the image is to be stored(the complete path with the name of the image also), and the second argument is the frame that is being saved.

    import cv2
    
    videoCaptureObject = cv2.VideoCapture(0)
    result = True
    while(result):
        ret,frame = videoCaptureObject.read()
        cv2.imwrite("NewPicture.jpg",frame)
        result = False
    videoCaptureObject.release()
    cv2.destroyAllWindows()

    When the above snippet is executed an image with the name "NewPicture.jpg" is stored in your current working directory. After reading the frame and storing the image, we just changed the Boolean variable result to False to stop reading the frames continuously.

    Conclusion

    In this second installment of our series on capturing videos and images with Python, we've delved into advanced techniques and libraries for multimedia manipulation. We've explored real-time video streaming, image processing, and even building custom camera applications using Python.

    With the knowledge gained from this article, you're now equipped to take on exciting projects involving video and image capturing. Whether you're interested in computer vision, data analysis, or building multimedia applications, Python provides the tools you need.

    In the next part of this series, we'll harness the power of the OpenCV library to detect human faces in a live feed.

    Happy coding!!

    Frequently Asked Questions(FAQs)

    1. Can I capture videos from a webcam using Python?

    Absolutely! Python provides libraries like OpenCV, which allow you to access and capture video streams from webcams. With a few lines of code, you can start capturing video frames and processing them as needed.

    2. Is it possible to save the captured videos and images to a file using Python?

    Yes, you can save the captured videos and images to a file using Python. Libraries like OpenCV provide functions to write frames to video files, and you can use standard file I/O operations to save images in various formats, such as JPEG or PNG.

    3. Can I apply image processing techniques to captured frames in real time?

    Absolutely! With libraries like OpenCV, you can apply a wide range of image-processing techniques to the captured frames in real time. This includes tasks like image filtering, edge detection, object recognition, and much more.

    You may also like:

    About the author:
    Software Engineer| AI | ML | Geek
    Tags:python
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS