Thursday 4 April 2024

Resize the video in OpenCV

We can resize the video by resizing the video frame by frame.

Following snippet resize the frame or image.

def resize_frame(frame, scale_width=0.5, scale_height=0.5):
    width = int(frame.shape[1] * scale_width)
    height = int(frame.shape[0] * scale_height)
    new_dimensions = (width, height)
    return cv.resize(frame, new_dimensions, interpolation=cv.INTER_AREA)

Find the below working application.

 

resize_video.py

import cv2 as cv

def resize_frame(frame, scale_width=0.5, scale_height=0.5):
    width = int(frame.shape[1] * scale_width)
    height = int(frame.shape[0] * scale_height)
    new_dimensions = (width, height)
    return cv.resize(frame, new_dimensions, interpolation=cv.INTER_AREA)

video_capture = cv.VideoCapture('videos/bird.mp4')

while True:
    # Read the video frame by frame
    # is_true says whether the frame is successfully read or not
    is_true, frame = video_capture.read()

    # You can skip this if you want
    if is_true == False:
        break

    frame = resize_frame(frame, 1.4, 0.7)
    # Show the frame
    cv.imshow('bird video', frame)

    # If the letter x is pressed then come out of video
    if (cv.waitKey(20) & 0xFF) == ord('x'):
        break

video_capture.release()

# Close the OpenCV windows
cv.destroyAllWindows()

How to resize the live video?

Above example works for an existing video. But what about a video stream or capturing video from a device (like a webcam). Following lines are used to set the desired frame width and height for video capture.

 

video_capture.set(3, width)

video_capture.set(4, height)

 

First line sets the width property of the video capture object to the value specified in the width variable. Second line sets the height property of the video capture object to the value specified in the height variable.


Previous                                                    Next                                                    Home

No comments:

Post a Comment