其他分享
首页 > 其他分享> > cv2.VideoWriter类 将图片帧写入视频

cv2.VideoWriter类 将图片帧写入视频

作者:互联网

# encoding: utf-8
# module cv2.cv2
# from D:\20191031_tensorflow_yolov3\python\lib\site-packages\cv2\cv2.cp36-win_amd64.pyd
# by generator 1.147
""" Python wrapper for OpenCV. """

# imports
import cv2.cv2 as  # D:\20191031_tensorflow_yolov3\python\lib\site-packages\cv2\cv2.cp36-win_amd64.pyd
import cv2.Error as Error # <module 'cv2.Error'>
import cv2.cuda as cuda # <module 'cv2.cuda'>
import cv2.detail as detail # <module 'cv2.detail'>
import cv2.dnn as dnn # <module 'cv2.dnn'>
import cv2.fisheye as fisheye # <module 'cv2.fisheye'>
import cv2.flann as flann # <module 'cv2.flann'>
import cv2.ipp as ipp # <module 'cv2.ipp'>
import cv2.ml as ml # <module 'cv2.ml'>
import cv2.ocl as ocl # <module 'cv2.ocl'>
import cv2.ogl as ogl # <module 'cv2.ogl'>
import cv2.samples as samples # <module 'cv2.samples'>
import cv2.utils as utils # <module 'cv2.utils'>
import cv2.videoio_registry as videoio_registry # <module 'cv2.videoio_registry'>
import cv2 as __cv2


from .object import object

class VideoWriter(object):
    # no doc
    def fourcc(self, c1, c2, c3, c4): # real signature unknown; restored from __doc__
        """
        fourcc(c1, c2, c3, c4) -> retval
        .   @brief Concatenates 4 chars to a fourcc code
        .   
        .       @return a fourcc code
        .   
        .       This static method constructs the fourcc code of the codec to be used in the constructor
        .       VideoWriter::VideoWriter or VideoWriter::open.
        """
        pass

    def get(self, propId): # real signature unknown; restored from __doc__
        """
        get(propId) -> retval
        .   @brief Returns the specified VideoWriter property
        .   
        .        @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY)
        .        or one of @ref videoio_flags_others
        .   
        .        @return Value for the specified property. Value 0 is returned when querying a property that is
        .        not supported by the backend used by the VideoWriter instance.
        """
        pass

    def getBackendName(self): # real signature unknown; restored from __doc__
        """
        getBackendName() -> retval
        .   @brief Returns used backend API name
        .   
        .        @note Stream should be opened.
        """
        pass

    def isOpened(self): # real signature unknown; restored from __doc__
        """
        isOpened() -> retval
        .   @brief Returns true if video writer has been successfully initialized.
        """
        pass

    def open(self, filename, fourcc, fps, frameSize, isColor=None): # real signature unknown; restored from __doc__
        """
        open(filename, fourcc, fps, frameSize[, isColor]) -> retval
        .   @brief Initializes or reinitializes video writer.
        .   
        .       The method opens video writer. Parameters are the same as in the constructor
        .       VideoWriter::VideoWriter.
        .       @return `true` if video writer has been successfully initialized
        .   
        .       The method first calls VideoWriter::release to close the already opened file.
        
        
        
        open(filename, apiPreference, fourcc, fps, frameSize[, isColor]) -> retval
        .   @overload
        
        
        
        open(filename, fourcc, fps, frameSize, params) -> retval
        .   @overload
        
        
        
        open(filename, apiPreference, fourcc, fps, frameSize, params) -> retval
        .   @overload
        """
        pass

    def release(self): # real signature unknown; restored from __doc__
        """
        release() -> None
        .   @brief Closes the video writer.
        .   
        .       The method is automatically called by subsequent VideoWriter::open and by the VideoWriter
        .       destructor.
        """
        pass

    def set(self, propId, value): # real signature unknown; restored from __doc__
        """
        set(propId, value) -> retval
        .   @brief Sets a property in the VideoWriter.
        .   
        .        @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY)
        .        or one of @ref videoio_flags_others
        .   
        .        @param value Value of the property.
        .        @return  `true` if the property is supported by the backend used by the VideoWriter instance.
        """
        pass

    def write(self, image): # real signature unknown; restored from __doc__
        """
        write(image) -> None
        .   @brief Writes the next video frame
        .   
        .       @param image The written frame. In general, color images are expected in BGR format.
        .   
        .       The function/method writes the specified image to video file. It must have the same size as has
        .       been specified when opening the video writer.
        """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass



MP4有许多编码格式
  XviD一直是世界上最流行的视频编码器。估计在BT(BitTorrent)和eMule上至少90%的电影、电视剧是用XviD压制的。但是在中国的情况有些特殊,因为中国的影视发布者喜欢用RMVB格式。XviD的文件扩展名可以是AVI、MKV、MP4等。需要说明的是,仅从扩展名并不能看出这个视频的编码格式。
  H.263是特别面向低码率的视频编码而设定的(通常只有20-30kbps或更高) H.263标准指明了对于视频编码和解码器的需求。
  H.264是一种高性能的视频编解码技术。其最大的优势是具有很高的数据压缩比率,在同等图像质量的条件下,H.264能提供连续、流畅的高质量图象同H.263等标准的特率效率相比,能够平均节省大于50%的码率。
  MPEG4是一种编码标准,DIVX格式的AVI是MPEG4的一种,XVID格式的AVI也是MPEG4的一种,WMV9格式的AVI,微软自己推出的MPEG4编码标准。
  手机所能支持的视频格式有限,主要是H.263和Xvid编码,H.264编码目前不支持,如果是智能机的话,用播放软件可能能播放。
  对于转换视频,个人推荐“格式工厂”,转换时要注意:
  1、原视频要清晰,视频的清晰度取决于码率
  2、转换时要适当调整视频的分辨率,码率,每秒帧数,确保手机支持。 码率太大播放时会卡


1、意思不一

X264:是ITU和MPEG联合制定的视频编码器。

H264:是MPEG-4第十部分,是由高度压缩数字视频编解码格式。

2、功能不一

X264:包含有一些心理视觉增强技术,以增强编码视频的主观质量。

H264:能提供连续、流畅的高质量图像。

3、容量不一

X264:同等清晰度下,X264的容量大于H264。

H264:影视文件中容量最小的RAW,同等清晰度下,H264的容量小于X264。

4、压缩比率不一

X264:能实现压缩比,有广泛的适用码率。

H264:具有很高的数据压缩比率。

5、特点不一

X264:自适应空间域转换、预测性的无损编码。

H264:高的编码效率、提高网络适应能力、采用混合编码结构。

python opencv生成 html5 支持的mp4

FOURCC四字符码对照表

示例

# 保存障碍物视频
class SaveVideo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global mice_or_not
        while True:
            if color_image is None:
                print('SaveVideo还没好:{}'.format(time.time()))
                time.sleep(1)
                continue
            else:
                if mice_or_not:
                    name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                    buffer_path = 'static/buffer/{}.mp4'.format(name)
                    video_path = 'static/obstacle_videos/{}.mp4'.format(name)
                    # 分辨率必须要跟摄像头输出的一致
                    # video_writer = cv2.VideoWriter(buffer_path, cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'), 10,
                    #                                (color_image.shape[1], color_image.shape[0]))
                    # video_writer = cv2.VideoWriter(buffer_path, cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), 10,
                    #                                (color_image.shape[1], color_image.shape[0]))
                    video_writer = cv2.VideoWriter(buffer_path, cv2.VideoWriter_fourcc(*'avc1'), 10,
                                                   (color_image.shape[1], color_image.shape[0]))
                    i = 0
                    # 设置视频
                    video_cover = color_image
                    data_initial = video_cover
                    # 将快照写入文件夹
                    cv2.imwrite(
                        'static/obstacle_snapshots/{}.jpg'.format(name),
                        data_initial)
                    # 判断obstacle_snapshots文件夹文件是否超出,超出就删除最久的文件
                    remove_old_file('static/obstacle_snapshots/', 12)
                    # 判断color_image是不是同一帧图片,是同一帧就跳过,不是就写入缓存buffer(不能产生大数组会卡住??)
                    while True:
                        if not (color_image == data_initial).all():
                            i += 1
                            print('i = ', i)
                            # 30秒视频,每秒30帧
                            # Dontla20210409:30秒视频,每秒10帧
                            # if 1 <= i <= 900:
                            if 1 <= i <= 300:
                                # 也不知道写入成功的标志是什么?怎么解除占用?应该是release()函数
                                video_writer.write(color_image)
                                data_initial = color_image
                            else:
                                # 释放占用(否则显示文件被其他应用使用中)
                                video_writer.release()
                                # 将视频封面图写入文件夹(尽量在生成视频前并贴在一起)
                                cv2.imwrite('static/obstacle_videos_front_cover/{}.jpg'.format(name), video_cover)
                                # 转移视频……
                                print('开始转移视频……')
                                shutil.move(buffer_path, video_path)
                                # 视频转移完成
                                print('视频转移成功')
                                # 清空buffer文件夹
                                del_list = os.listdir('static/buffer/')
                                for _ in del_list:
                                    file_path = os.path.join('static/buffer/', _)
                                    if os.path.exists(file_path):  # 需要判断一下防止出错
                                        os.remove(file_path)
                                # 判断obstacle_videos文件夹文件是否超出,超出就删除最久的文件以及在obstacle_videos_front_cover中它的封面图
                                remove_old_file('static/obstacle_videos/', 12)
                                remove_old_file('static/obstacle_videos_front_cover/', 12)
                                # 重置mice_or_not
                                mice_or_not = False
                                break

在这里插入图片描述

标签:__,cv2,image,写入,video,import,VideoWriter
来源: https://blog.csdn.net/Dontla/article/details/116169590