dip deb
dip deb

Reputation: 79

why can't I get all different sized images in the video using opencv python?

I want to create video from images using opencv in python. But unfortunately I found that the video doesn't contain all images. Then I check the size and found all images size is not same. So I resized all images before writing it into video file. Then I got error while opening the video file showing "Could not demultiplex stream". What am I missing here? please correct me.

here is my code:

import cv2
import numpy as np
import os
image_list=os.listdir(os.getcwd())
img=[]
i=0
for filename in image_list:
    if(filename.endswith(".jpg")):
        img.append(filename)
        i+=1
frame=cv2.imread(img[0])
height,width,layers=frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video=cv2.VideoWriter('video.avi',fourcc,1,(width,height))

for file in img:

    image=cv2.imread(file)
    resized=cv2.resize(image,(960,720)) #for my image list lowest size.
    print(file,resized.shape)
    video.write(resized)

video.release()
cv2.destroyAllWindows()

Upvotes: 2

Views: 2212

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

The problem is that you are setting the size of the video frame that matches the first image and then you save images with a size that may not match the size of the first image. The following solution should work:

import os
import cv2

dir_path = os.getcwd()
ext = '.jpg'
output = 'video.avi'
shape = 960, 720
fps = 1

images = [f for f in os.listdir(dir_path) if f.endswith(ext)]

fourcc = cv2.VideoWriter_fourcc(*'DIVX')
video = cv2.VideoWriter(output, fourcc, fps, shape)

for image in images:
    image_path = os.path.join(dir_path, image)
    image = cv2.imread(image_path)
    resized=cv2.resize(image,shape) 
    video.write(resized)

video.release()

Upvotes: 2

Related Questions