如何在Python中保存由OpenCV图片制作的电影

时间:2018-08-26 09:31:43

标签: python python-3.x opencv

我用 OpenCV 编写了一个 Python 程序,该程序:

  1. 扫描包含图像的文件夹
  2. 对其订单进行一些操作
  3. 返回已处理图像的列表 IMG

现在我要做的是将新图片的列表 IMG 保存为例如 .avi 电影。怎么做这样的手术?我故意要在过滤等整个过程后从列表中保存图片。

import os
import cv2
import numpy as np

folder_name = 'trial1'
extension = '.bmp'
path = os.getcwd()

GB_kernel = (13,13)

""" List all .bmp images names from a folder """ 
def folder_content(folder_name, extension):

    dir_content = os.listdir(folder_name)
    folder_content_ext = []
    for file in dir_content:
        if file.endswith(extension):
            folder_content_ext.append(file)

    return folder_content_ext

IMG_names = folder_content(folder_name, extension)

""" Some OpenCV operations on images """
""" Loop over all images. Iterator i is important in the future """
IMGs = []
for i in range(len(IMG_names)):

    """ Define path to basic image """ 
    img = path + '\\' + folder_name + '\\' + IMG_names[i]
    """ read this image """ 
    image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
    """ some operation - gaussian blur """ 
    pre_filt = cv2.GaussianBlur(image, GB_kernel, 0)
    """ contain blurred img in a list """ 
    IMGs.append(pre_filt)

    cv2.imshow('Gaussian Blur', pre_filt)
    WKey = 1
    if cv2.waitKey(WKey) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

""" HOW?? """
save_list_of_matrix_as_movie(IMGs)

感谢您的帮助和提示。

1 个答案:

答案 0 :(得分:1)

您可以尝试下面的代码。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

Create video from images in a list.

Idea from:
http://tsaith.github.io/combine-images-into-a-video-with-python-3-and-opencv-3.html

"""

import os
import time
import cv2

folder_name = 'trial1'
extension = '.bmp'
video_file = 'out.avi'
path = os.getcwd()

GB_kernel = (13, 13)


# %%
def folder_content():
    """
    List all images names with given extension from a folder.
    """
    dir_content = os.listdir(folder_name)
    folder_content_ext = []
    for file in dir_content:
        if file.endswith(extension):
            folder_content_ext.append(file)

    return folder_content_ext


# %%
def img_2_matrix(img_names):
    """
    Some OpenCV operations on images
    Loop over all images. Iterator i is important in the future
    """
    imgs = []
    for i in range(len(img_names)):

        # Define path to basic image
        img = os.path.join(path, folder_name, img_names[i])
        # read this image
        image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
        # some operation - gaussian blur
        pre_filt = cv2.GaussianBlur(image, GB_kernel, 0)
        # contain blurred img in a list
        imgs.append(pre_filt)

        cv2.imshow('Gaussian Blur', pre_filt)
        wkey = 1
        if cv2.waitKey(wkey) & 0xFF == ord('q'):
            break

    return imgs


# %%
def save_list_of_matrix_as_movie(imgs):
    """

    """
    shape = (imgs[0].shape[1], imgs[0].shape[0])
    fourcc = cv2.VideoWriter_fourcc(*"XVID")  # XVID for avi, mp4v for mp4
    out = cv2.VideoWriter(video_file, fourcc, 20.0, shape, 0)

    print("\nHit 'q' to exit")
    for frame in imgs:
        pre_filt = cv2.GaussianBlur(frame, GB_kernel, 0)
        out.write(pre_filt)  # Write out frame to video
        cv2.imshow("video", pre_filt)
        if(cv2.waitKey(1) & 0xFF) == ord("q"):  # Hit `q` to exit
            break

    return out


# %%
def release(out):
    """
    Release everything if job is finished
    """
    cv2.destroyAllWindows()
    out.release()


# %%
if __name__ == "__main__":

    # %%
    TIC = time.time()

    # %%
    img_names = folder_content()
    imgs = img_2_matrix(img_names)
    out = save_list_of_matrix_as_movie(imgs)
    release(out)

    # %%
    print("Time elapsed: %0.2f s" % (time.time() - TIC))