Rich's Wordpress

又一个WordPress站点

OpenCV 2: Rescale Images and Videos

The size or scale of the image or video may sometimes be too big not as desired, we can fix the problem by changing the width and height of the file.

import cv2 as cv

def rescaleFrame(frame, scale = 0.75):

    # Images, Videos and Live Videos

    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)

    demension = (width, height)

    return cv.resize(frame, demension, interpolation=cv.INTER_AREA)

To rescale an image or video, we need to create a function which I named it rescaleFrame. Two parameters need to be passed in, they are the frame and the scale. Next, we need to multiply the width and height of the frame read in by the computer by the scale to achieve the desired size, “frame.shape[1]” gives me the width of the frame and “frame.shape[0]” gives me the height of the frame. Note that after the multiplication, the width and height become floating point values, we need to convert them to an integer. Finally, we can return the resized image using the cv.resize method by passing in the necessary parameters.

Resizing Images

# Resize in Images:
img = cv.imread('Image/Image.png')
cv.imshow('Image', img)

resized_img = rescaleFrame(img)
cv.imshow('Resized Image', resized_img)

cv.waitKey(0)

These lines of code together with the function mentioned above will create two windows one displaying the original image, and the other displaying the resized image.

Resizing Videos / Live Videos

# Resize in Videos:
capture = cv.VideoCapture('/Users/richzha/Desktop/CV/Video/OLED.mp4')

while True:
    isTrue, frame = capture.read()

    resized_frame = rescaleFrame(frame)

    cv.imshow('Video', frame)
    cv.imshow('Video Resized', resized_frame)

    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

These lines of code together with the function mentioned above will create two windows one displaying the original video, and the other displaying the resized video. This can work for both video files or live video captured by a camera. It can resize videos because each frame read in by the computer are all rescaled to a certain size and then displayed to us frame by frame.

OpenCV 2: Rescale Images and Videos
Scroll to top