1

I'm trying to put a non-widescreen video frame image into a 16:9 black frame, for example: if my project is set to 720p (1280 * 720) and the size of my video frame is 640 * 480, first I calculate the zoom ratio, resize its height to 720 (and the width correspondingly) then I put it on a black 1280 * 720 image.

Tried this method but it doesn't work for me for some reason.

import cv2
import numpy as np

project_width, project_height = 1280, 720
video_file = "any_path/whatever.mp4"
black_image = np.zeros((project_height,project_width,3), np.uint8)
vidcap = cv2.VideoCapture(video_file)

while(vidcap.isOpened()):
    ret, frame = vidcap.read()

    if ret==True:
        frame_height, frame_width, channels = frame.shape

        if frame_height < project_height or frame_width < project_width:
            zoom_ratio = project_height/frame_height
            desired_width = int(frame_width * zoom_ratio)
            desired_height = project_height
            frame = cv2.resize(frame, (desired_width, desired_height))
            border_width = int((project_width-desired_width) / 2)
            black_image[0:, border_width:] = frame

At this point I got an error: TypeError: slice indices must be integers or None or have an index method

EDIT: my bad, I forgot to convert border_width to an int, but now I face another problem:

ValueError: could not broadcast input array from shape (720,1152,3) into shape (720,1216,3)

(my source video is 1152*720 in this actual case)

EDIT2 - I suddenly realized the solution: on the last line I must specify the end pixel of the image so it works. In case of someone has this problem, too:

black_image[0:, border_width:project_width - border_width] = frame
  • where is `border_offset` defined/initialized? Since that is the offending line, it'd be helpful to provide as much context around the line as possible. – vasia Jan 28 '19 at 19:08
  • Sorry, it was just uncosistent translation of my original variable names, now I fixed it – Gergely Tomanovics Jan 28 '19 at 19:24
  • You need to make the shape (dimensions) of `frame` match with the shape of `black_image`. Are you sure you are using the `c2v.resize` method correctly? Or, should you make your `black_image` have a shape of `(desired_width, desired_height)` ? – vasia Jan 28 '19 at 19:54
  • Yes, I checked the syntax of the resize method, width and height needs to be reversed here: https://stackoverflow.com/questions/4195453/how-to-resize-an-image-with-opencv2-0-and-python2-6 'project_width' (the size of the black box) is not the same as 'desired_width'. For example if I have a 640*480 (NTSC SD standard 4:3) video, the 'zoom_ratio' needs to be 720/480 = 1.5, the "desired_width" (of the video) is 640*1.5 = 960 pixels, so the 'border_width' should be (1280-960) / 2 = 160 pixels. 160+960+160 pixels (border, image, border) gives the total of 1280 pixels which I want. – Gergely Tomanovics Jan 28 '19 at 20:06

0 Answers0