Python编写 利用OpenCV将多组图像拼接后制作成视频

参考OpenCV制作视频,自己加了一些图像拼接的代码段。

from os.path import isfile, join
from imutils import paths
import numpy as np
import random
import imutils
import cv2
import os
import matplotlib.pyplot as plt

# define the aspect aware prepeocessor class
class AspectAwarePreprocessor:
    def __init__(self, width, height, inter=cv2.INTER_AREA):
        # store the target image width, height, and interpolation
        # method used when resizing
        self.width = width
        self.height = height
        self.inter = inter

    def preprocess(self, image):
        # grab the dimensions of the image and then initialize
        # the deltas to use when cropping
        (h, w) = image.shape[:2]
        dW = 0
        dH = 0
        # if the width is smaller than the height, then resize
        # along the width (i.e., the smaller dimension) and then
        # update the deltas to crop the height to the desired
        # dimension
        if w < h:
            image = imutils.resize(image, width=self.width,
                                   inter=self.inter)
            dH = int((image.shape[0] - self.height) / 2.0)

        # otherwise, the height is smaller than the width so
        # resize along the height and then update the deltas
        # crop along the width
        else:
            image = imutils.resize(image, height=self.height,
                                   inter=self.inter)
            dW = int((image.shape[1] - self.width) / 2.0)

        # now that our images have been resized, we need to
        # re-grab the width and height, followed by performing
        # the crop

        (h, w) = image.shape[:2]
        image = image[dH:h - dH, dW:w - dW]

        # finally, resize the image to the provided spatial
        # dimensions to ensure our output image is always a fixed
        # size
        return cv2.resize(image, (self.width, self.height),
                          interpolation=self.inter)


def convert_frames_to_video(pathIn, pathOut, fps):
    # initialize the frame, width, and height array
    frame_array = []
    width_array = []
    height_array = []
    left_files = list(paths.list_images(pathIn+'left/'))  # 待拼接图像1
    left_files.sort()
    right_files = list(paths.list_images(pathIn + 'right/'))  # 待拼接图像2  
    right_files.sort()
    predicted_files = list(paths.list_images(pathIn + 'predicted/'))  # 待拼接图像3
    predicted_files.sort()

    assert len(left_files)==len(right_files)
    assert len(left_files) == len(predicted_files)

    print('length of files is ', len(left_files))

    # initialize the image preprocessor and the target size
    aap = AspectAwarePreprocessor(1500, 2500)
    size = (1500, 2500)
    for i in range(len(left_files)):
        # filename=pathIn + files[i]
        # reading each files
        left_img = cv2.cvtColor(cv2.imread(left_files[i]), cv2.COLOR_BGR2RGB)
        right_img = cv2.cvtColor(cv2.imread(right_files[i]), cv2.COLOR_BGR2RGB)
        predicted_img = cv2.cvtColor(cv2.imread(predicted_files[i]), cv2.COLOR_BGR2RGB)

        plt.figure(figsize=(25, 15))

        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        # plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
        plt.subplots_adjust(hspace=0, wspace=0)
        plt.margins(0, 0)

        plt.subplot(311)
        plt.axis('off')
        plt.imshow(left_img)
        plt.title('NJUST on Cityscapes left image')

        plt.subplot(312)
        plt.axis('off')
        plt.imshow(right_img)
        plt.title('NJUST on Cityscapes right image')

        plt.subplot(313)
        plt.axis('off')
        plt.imshow(predicted_img)
        plt.title('NJUST on Cityscapes predicted image')

        plt.tight_layout()  # 去掉空白区域
        # plt.savefig('./NJUST_Experiments.png', bbox_inches='tight')
        plt.savefig('./NJUST_Experiments.png')
        plt.clf()
        plt.cla()
        plt.close("all")

        img = cv2.imread('./NJUST_Experiments.png')  # 暂存临时图片

        height, width, channels = img.shape

        # resize the image
        img = aap.preprocess(img)

        # save image to a certain directory
        f = left_files[i]
        file_name, file_ext = os.path.splitext(f)
        file_num = '{}'.format(i)
        file_num = file_num.zfill(5)
        new_name = 'demo' + file_num + file_ext

        path = '/data/zd/video_images/'

        cv2.imwrite(os.path.join(path, new_name), img)

        if i % 10 == 0:
            print("[INFO] Processing {}th image".format(i))

        # inserting the frames into an image array

        frame_array.append(img)
        height_array.append(height)
        width_array.append(width)

    print('pathOut is ', pathOut)
    out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'mp4v'), fps, size)

    print('Process finished, begin writing ...')
    for i in range(len(frame_array)):
        # writing to a image array
        out.write(frame_array[i])
    out.release()
    print('Done!')


def main():
    pathIn = '/data/zd/binocular-seg/val_results/'  # 输入图像的路径
    pathOut = '/data/zd/binocular-seg/binocular_seg_video.mp4'  # 输出视频的路径

    fps = 2.0
    convert_frames_to_video(pathIn, pathOut, fps)


if __name__ == "__main__":
    main()

效果示意:

### 回答1: 您好,以下是利用OpenCVPython实现多张图片拼接一个视频的代码示例: ```python import cv2 import os # 设置要拼接的图片路径和输出视频路径 img_path = 'image_folder/' video_path = 'output_video.avi' # 获取图片列表 img_list = os.listdir(img_path) # 获取第一张图片的大小 img = cv2.imread(os.path.join(img_path, img_list[])) height, width, layers = img.shape # 创建视频对象 video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'XVID'), 24, (width, height)) # 遍历图片列表,将每张图片写入视频 for img_name in img_list: img = cv2.imread(os.path.join(img_path, img_name)) video.write(img) # 释放视频对象 video.release() ``` 以上代码将会把指定文件夹中的所有图片按照文件名的顺序拼接一个视频,并保存到指定路径下。 ### 回答2: 要利用OpenCVPython实现多张图片拼接一个视频,可以按照以下步骤编写代码: 1. 导入所需的库: ```python import cv2 import os ``` 2. 指定图片文件夹路径和视频输出路径: ```python image_folder = '图片文件夹路径' video_name = '视频输出路径/视频名称.mp4' ``` 3. 获取图片文件夹中所有图片的文件名列表: ```python images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")] images.sort() # 按文件名排序 ``` 4. 获取第一张图片的尺寸作为视频帧的尺寸: ```python frame = cv2.imread(os.path.join(image_folder, images[0])) height, width, layers = frame.shape ``` 5. 初始化视频编码器: ```python fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 可根据视频格式进行修改 video = cv2.VideoWriter(video_name, fourcc, 30, (width, height)) ``` 6. 遍历图片列表,将每张图片写入视频: ```python for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) ``` 7. 释放资源: ```python cv2.destroyAllWindows() video.release() ``` 完以上步骤后,运行代码即可将指定文件夹中的多张图片拼接一个视频并保存在指定路径。 ### 回答3: 要使用OpenCVPython来将多张图片拼接一个视频,可以按照以下步骤实现: 1. 导入必要的库:导入OpenCV库和Python库。 ```python import cv2 import os ``` 2. 设置输入的图片路径和输出视频的路径。 ```python image_folder = '图片文件夹路径' video_name = '视频输出路径/视频名字.mp4' ``` 3. 获取图片列表并按文件名排序。 ```python images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")] images.sort(key=lambda x: int(x.split('.')[0])) ``` 4. 获取第一张图片的尺寸,并创建一个视频写入对象。 ```python frame = cv2.imread(os.path.join(image_folder, images[0])) height, width, layers = frame.shape video = cv2.VideoWriter(video_name, 0, 1, (width, height)) ``` 5. 将每张图片读取并写入视频。 ```python for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) ``` 6. 释放资源。 ```python cv2.destroyAllWindows() video.release() ``` 完整的代码如下: ```python import cv2 import os image_folder = '图片文件夹路径' video_name = '视频输出路径/视频名字.mp4' images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")] images.sort(key=lambda x: int(x.split('.')[0])) frame = cv2.imread(os.path.join(image_folder, images[0])) height, width, layers = frame.shape video = cv2.VideoWriter(video_name, 0, 1, (width, height)) for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) cv2.destroyAllWindows() video.release() ``` 将以上代码中的"图片文件夹路径"替换为包含要拼接为视频的多张图片的文件夹路径,并将"视频输出路径/视频名字.mp4"替换为期望输出的视频路径和名称。运行代码后,即可生拼接后的视频
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值