Search code examples
pythonvideoimage-resizingopencv

how to resize frame from video and then retrieve the final size?


I want to read a video file, break it into separate frames, resize each frame to a max width and then retrieve width and height of final image.

I've tried this:

while True:

vs = cv2.VideoCapture(args["video"])
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
frame = imutils.resize(frame, width=400)

# grab the frame dimensions and convert it to a blob
w, h = cv.GetSize(frame)

but am getting:

Traceback (most recent call last):
  File "real_time_object_detection.py", line 52, in <module>
    frame = imutils.resize(frame, width=400)
  File "/home/pi/.virtualenvs/cv/lib/python3.5/site-packages/imutils/convenience.py", line 69, in resize
    (h, w) = image.shape[:2]
AttributeError: 'tuple' object has no attribute 'shape'

why does it complain about a line in imutils/? How can I do the required?


Solution

  • The read method returns two variables, first is the success variables which is a boolean (True if a frame is captured else False) and the second is the frame. You're likely reading a video with 3 channel frames and the frame is usually a numpy array so you can use the shape attribute.

    I would suggest using cv2.resize for resizing.

    vs = cv2.VideoCapture(args["video"])
    # grab the frame from the threaded video stream and resize it
    # to have a maximum width of 400 pixels
    
    _, frame = vs.read()
    (w, h, c) = frame.shape
    
    #syntax: cv2.resize(img, (width, height))
    img = cv2.resize(frame,(400, h))
    
    print(w, h)
    print(img.shape)
    >> 480 640
     (640, 400, 3) #rows(height), columns(width), channels(BGR)
    

    w and h store the original width and height of your video frame and img.shape has the resized width and height