[python] Finally solved the problem that the video file is always 1KB and cannot be played after cv2.VideoWriter generates the video

Combine a sequence of images into a video:

import cv2
import imageio
import os

path = r'D:\dataset\images'
dir_name = os.listdir(path)
for dir in dir_name:
    dir_path = os.path.join(path, dir)
    img = imageio.imread(os.path.join(dir_path, os.listdir(dir_path)[0]))
    vid_writer = cv2.VideoWriter(path + rf'\{dir}.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 24, (img.shape[1], img.shape[0]))
    for i in os.listdir(dir_path):
        vid_writer.write(imageio.imread(os.path.join(dir_path, i)))

Result:

Opening shows:

I have used this program before, and it can synthesize video normally, but this time it doesn’t work. I think it may be a problem with the picture, so I compared the picture I used before with the picture this time, and found that the format of the picture read in before is (w, h, 3), and this time the format is (w, h), which means that the grayscale image is read in this time. I guess the reason for the video generation failure may be that cv2.VideoWriter is not suitable for grayscale pictures, so convert the pictures to BGR format.

import cv2
import imageio
import os

path = r'D:\dataset\images'
dir_name = os.listdir(path)
for dir in dir_name:
    dir_path = os.path.join(path, dir)
    img = imageio.imread(os.path.join(dir_path, os.listdir(dir_path)[0]))
    vid_writer = cv2.VideoWriter(path + rf'\{dir}.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 24, (img.shape[1], img.shape[0]))
    for i in os.listdir(dir_path):
        # vid_writer.write(imageio.imread(os.path.join(dir_path, i)))  ### 这行改为以下三行
        img = imageio.imread(os.path.join(dir_path, i))
        img2 = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        vid_writer.write(img2)

Now it's normal:

Supplement:
cv2.COLOR_GRAY2RGB converts the grayscale image into a BGR image, and replaces all B, G, and R channels with the grayscale value Y, so B=Y, G=Y, R=Y. (Source: What does cv2.COLOR_GRAY2RGB do? )

Guess you like

Origin blog.csdn.net/zylooooooooong/article/details/121535422