Search code examples
pythonopencvpafy

How to resize output frame from live stream from youtube using opencv


It's my beginning with coding and this site. I'm working on project, where I want to use openCV, but I've got an issue with that. I need to resize output frame, for recognizing object. I have read, that frame should be in size 416x416, but when I'm trying to release the frame, it's still in regular size. Here's the code:

import pafy
import youtube_dl
import cv2
import numpy as np


url = "https://www.youtube.com/watch?v=WOn7m0_aYBw"
video = pafy.new(url)
best = video.getbest(preftype="mp4")

cap = cv2.VideoCapture()
cap.open(best.url)

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers =[layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))


while True:
    ret, frame = cap.read()
 #   if ret == True:
    img = cv2.imshow('frame',frame)
    #cap.set(cv2.CAP_PROP_FRAME_WIDTH, 416)
    #cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 416)
    width = 416
    height = 416
    dim = (width, height)
    img = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
    print(img.shape)

    if cv2.waitKey(20) & 0xFF == ord('q'):
        break

blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)

print(img.shape) returns correct size, but I think I'm releasing wrong window. How to change this code to releasing window in correct size?


Solution

  • You were showing the frame before resizing

    while True:
        ret, frame = cap.read()
    
        width = 416
        height = 416
        dim = (width, height)
        img = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
        print(img.shape)
    
        cv2.imshow('frame',img)
        if cv2.waitKey(20) & 0xFF == ord('q'):
            break