当前位置: 首页>>代码示例>>Python>>正文


Python cv2.VideoWriter_fourcc方法代码示例

本文整理汇总了Python中cv2.VideoWriter_fourcc方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.VideoWriter_fourcc方法的具体用法?Python cv2.VideoWriter_fourcc怎么用?Python cv2.VideoWriter_fourcc使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.VideoWriter_fourcc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: encode

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def encode(self, video_in, data, video_out):
        assert len(data) == self.data_dim

        video_in = cv2.VideoCapture(video_in)
        width = int(video_in.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(video_in.get(cv2.CAP_PROP_FRAME_HEIGHT))
        length = int(video_in.get(cv2.CAP_PROP_FRAME_COUNT))

        data = torch.FloatTensor([data]).cuda()
        video_out = cv2.VideoWriter(
            video_out, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (width, height))

        for i in tqdm(range(length)):
            ok, frame = video_in.read()
            frame = torch.FloatTensor([frame]) / 127.5 - 1.0      # (L, H, W, 3)
            frame = frame.permute(3, 0, 1, 2).unsqueeze(0).cuda()  # (1, 3, L, H, W)
            wm_frame = self.encoder(frame, data)                       # (1, 3, L, H, W)
            wm_frame = torch.clamp(wm_frame, min=-1.0, max=1.0)
            wm_frame = (
                (wm_frame[0, :, 0, :, :].permute(1, 2, 0) + 1.0) * 127.5
            ).detach().cpu().numpy().astype("uint8")
            video_out.write(wm_frame)

        video_out.release() 
开发者ID:DAI-Lab,项目名称:RivaGAN,代码行数:26,代码来源:rivagan.py

示例2: enable_videowriter

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def enable_videowriter(self, output_filename, fourcc_string="MJPG",
                           fps=None):
        """ Write images to video file.

        Parameters
        ----------
        output_filename : str
            Output filename.
        fourcc_string : str
            The OpenCV FOURCC code that defines the video codec (check OpenCV
            documentation for more information).
        fps : Optional[float]
            Frames per second. If None, configured according to current
            parameters.

        """
        fourcc = cv2.VideoWriter_fourcc(*fourcc_string)
        if fps is None:
            fps = int(1000. / self._update_ms)
        self._video_writer = cv2.VideoWriter(
            output_filename, fourcc, fps, self._window_shape) 
开发者ID:nwojke,项目名称:deep_sort,代码行数:23,代码来源:image_viewer.py

示例3: loop2

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def loop2(self,text,w=1280,h=720):
        cap = cv2.VideoCapture(int(text))
        cap.set(6 ,cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') );
        global capnum2
        capnum2 = int(text)
        cap.set(3,w);
        cap.set(4,h);
        global update2
        update2 = 1
        global shotmark2

        while (update2 == 1):
            ret, frame = cap.read() 
            if shotmark2 == 1:
                fn = self.lineEdit.text()
                name = "photo/2_"+fn + "video.jpg"
                if os.path.exists(name):
                    name = "photo/2_" + fn + "video"+str(int(time.time()))+".jpg"
                cv2.imwrite(name, frame)
                shotmark2 = 0
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.original2_image.updateImage(frame)
        # cap.release()
        cv_img_rgb = np.zeros((700,700,3))
        self.original2_image.updateImage(cv_img_rgb) 
开发者ID:anonymouslycn,项目名称:bjtu_BinocularCameraRecord,代码行数:27,代码来源:Main.py

示例4: write

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def write(self, filename, frames, fps, show=False):
        fps = max(1, fps)
        out = None

        try:
            for image in frames:
                frame = cv2.imread(image)
                if show:
                    cv2.imshow('video', frame)

                if not out:
                    height, width, channels = frame.shape
                    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
                    out = cv2.VideoWriter(filename, fourcc, 20, (width, height))

                out.write(frame)

        finally:
            out and out.release()
            cv2.destroyAllWindows() 
开发者ID:ManiacalLabs,项目名称:BiblioPixel,代码行数:22,代码来源:mp4.py

示例5: VideoWriter

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def VideoWriter(fn: Path, cc4: str, xypix: tuple, fps: float, usecolor: bool):
    """

    Parameters
    ----------
    fn: pathlib.Path
        output filename to write
    cc4: str
        four character fourcc code e.g. 'FFV1'
    xypix: two-element tuple with x,y pixel count
    usecolor: bool color or bw
    """
    fn.parent.mkdir(parents=True, exist_ok=True)

    ncc4 = cv2.VideoWriter_fourcc(*cc4)

    hv = cv2.VideoWriter(str(fn), ncc4, fps=fps, frameSize=xypix, isColor=usecolor)

    if not hv or not hv.isOpened():
        raise RuntimeError(f'trouble starting video {fn}')

    yield hv

    hv.release() 
开发者ID:scivision,项目名称:pyimagevideo,代码行数:26,代码来源:videowriter.py

示例6: main

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def main(track_log_dir, output_path, videoname):
    track_log_dir = osp.join(track_log_dir)
    te_bboxs = readbbox(osp.join(track_log_dir, 'track_rect.txt'))
    num_frames = len(te_bboxs)

    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    org_img = cv2.imread(osp.join(track_log_dir, 'image_origin{}.jpg'.format(1)))
    out = cv2.VideoWriter(osp.join(output_path, videoname + '.avi'), fourcc, 24.0, (org_img.shape[1], org_img.shape[0]))
    print(org_img.shape)

    for i in range(1, num_frames):
        org_img = cv2.imread(osp.join(track_log_dir, 'image_origin{}.jpg'.format(i)))
        bbox = te_bboxs[i]
        cv2.rectangle(org_img, (int(bbox[0]), int(bbox[1])),
                      (
                          int(bbox[0]) + int(bbox[2]),
                          int(bbox[1]) + int(bbox[3])),
                      (0, 0, 255), 2)
        cv2.imshow('frame', org_img)
        out.write(org_img)
        cv2.waitKey(1)

    out.release()
    cv2.destroyAllWindows() 
开发者ID:lzane,项目名称:SiamFC-tf,代码行数:27,代码来源:save_result_to_video.py

示例7: show

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def show(self):
        img_list=[x for x in os.listdir(self.img_path) if 'jpg' in x or 'JPEG' in x]
        img_list.sort()
        f=open(self.label_path,'r')
        t=time.time()
        im=cv2.imread(os.path.join(self.img_path,img_list[0]))
        fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
        img_h,img_w,_=im.shape
        videoWriter=cv2.VideoWriter(os.path.join('../data/vedio','car2.mp4'),fourcc,30,(img_w,img_h))
        for img in img_list:
            line=f.readline().strip('\n')
            box=line.split(',')
            box=[int(float(box[0])),int(float(box[1])),int(float(box[2])),int(float(box[3]))]
            box[2]=box[0]+box[2]
            box[3]=box[1]+box[3]
            im=cv2.imread(os.path.join(self.img_path,img))
            videoWriter.write(im)
            cv2.rectangle(im,(box[0],box[1]),(box[2],box[3]),(0,0,255),1)

            cv2.imshow('img',im)
            cv2.waitKey(10)
        f.close()
        cv2.destroyAllWindows()
        videoWriter.release()
        print(time.time()-t) 
开发者ID:makalo,项目名称:Siamese-RPN-tensorflow,代码行数:27,代码来源:show.py

示例8: write_video

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def write_video(file_path, frames, fps):
    """
    Writes frames to an mp4 video file
    :param file_path: Path to output video, must end with .mp4
    :param frames: List of PIL.Image objects
    :param fps: Desired frame rate
    """

    w, h = frames[0].size
    fourcc = cv.VideoWriter_fourcc('m', 'p', '4', 'v')
    writer = cv.VideoWriter(file_path, fourcc, fps, (w, h))

    for frame in frames:
        writer.write(pil_to_cv(frame))

    writer.release() 
开发者ID:martkartasev,项目名称:sepconv,代码行数:18,代码来源:utilities.py

示例9: _create_video_writer

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def _create_video_writer(self) -> Optional[cv2.VideoWriter]:
        if not self.output_dir:
            return None
        ext = self.config.demo.output_file_extension
        if ext == 'mp4':
            fourcc = cv2.VideoWriter_fourcc(*'H264')
        elif ext == 'avi':
            fourcc = cv2.VideoWriter_fourcc(*'PIM1')
        else:
            raise ValueError
        output_path = self.output_dir / f'{self._create_timestamp()}.{ext}'
        writer = cv2.VideoWriter(output_path.as_posix(), fourcc, 30,
                                 (self.gaze_estimator.camera.width,
                                  self.gaze_estimator.camera.height))
        if writer is None:
            raise RuntimeError
        return writer 
开发者ID:hysts,项目名称:pytorch_mpiigaze,代码行数:19,代码来源:demo.py

示例10: consume

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def consume(self, item : np.array):
        '''
        Receives the picture frame to append to the video and appends it to the video.
        
        If it is the first frame received, it opens the video file and determines \
            the height and width of the video from the dimensions of that first frame. \
            Every subsequent frame is expected to have the same height and width. If it \
            does not has it, it gets resized to it.
        
        - Arguments:
            - item: np.array of dimension (height, width, 3)
        '''
        if self._out is None:
            self._height = item.shape[0]
            self._width = item.shape[1]
            self._out = cv2.VideoWriter(self._video_file, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), self._fps, (self._width, self._height))
        
        resized = cv2.resize(item, (self._width, self._height), interpolation = cv2.INTER_AREA)
        if self._swap_channels:
            resized = resized[...,::-1]
        self._out.write(resized) 
开发者ID:videoflow,项目名称:videoflow,代码行数:23,代码来源:video.py

示例11: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def __init__(self):
		
		self.open = True
		self.device_index = 0
		self.fps = 6               # fps should be the minimum constant rate at which the camera can
		self.fourcc = "MJPG"       # capture images (with no decrease in speed over time; testing is required)
		self.frameSize = (640,480) # video formats and sizes also depend and vary according to the camera used
		self.video_filename = "temp_video.avi"
		self.video_cap = cv2.VideoCapture(self.device_index)
		self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc)
		self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize)
		self.frame_counts = 1
		self.start_time = time.time()

	
	# Video starts being recorded 
开发者ID:JRodrigoF,项目名称:AVrecordeR,代码行数:18,代码来源:AVrecordeR.py

示例12: save_to_video

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def save_to_video(output_path,output_video_file,frame_rate):
        list_files = sorted([int(i.split('_')[-1].split('.')[0]) for i in get_file_names(output_path)])
        # 拿一张图片确认宽高
        img0 = cv2.imread(os.path.join(output_path,'%s.jpg'%list_files[0]))
        #print(img0)
        height , width , layers =  img0.shape
        # 视频保存初始化 VideoWriter
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        videowriter = cv2.VideoWriter(output_video_file,fourcc, frame_rate, (width,height))
        # 核心,保存的东西
        for f in list_files:
            f = '%s.jpg'%f 
            #print("saving..." + f)
            img = cv2.imread(os.path.join(output_path, f))
            videowriter.write(img)
        videowriter.release()
        cv2.destroyAllWindows()
        print('Success save %s!'%output_video_file)
        pass
    
    # 图片变视频 
开发者ID:mattzheng,项目名称:keras-yolov3-KF-objectTracking,代码行数:23,代码来源:yolov3_object_tracking.py

示例13: initialize

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def initialize(self):
        self.capture = cv2.VideoCapture(self.camera)
        if not self.capture.isOpened():
            print("Error opening video camera")
            return

        # cap.set(cv2.CAP_PROP_FPS, 5)
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
        self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)

        if self.record:
            self.videowriter = cv2.VideoWriter(self.filename,
                                                cv2.VideoWriter_fourcc('m', 'p', '4', 'v'),
                                                10,
                                                (self.width, self.height), 
                                                isColor=True) 
开发者ID:PacktPublishing,项目名称:Advanced-Deep-Learning-with-Keras,代码行数:18,代码来源:video.py

示例14: _startRecording

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def _startRecording(self):
        if self.outputDirectory is None:
            return self.setError("output directory is not specified")

        if None in [self.frameWidth, self.frameHeight]:
            return self.setError("resolution is't specified")

        fourcc = cv.VideoWriter_fourcc(*config.FOURCC_CODEC)
        videoSize = (self.frameWidth, self.frameHeight)

        # calculation output filename
        now = dts.datetime.utcnow()
        fileName = "video_{}{}".format(now.strftime("%Y%m%dT%H%M%S"), config.OUTPUT_FILES_EXTENSION)

        subFolder = self._getSubFolderName(now)
        if subFolder is not None:
            needCreate = ((self.__prevSubFolder is not None) or (subFolder != self.__prevSubFolder))

            dirName = os.path.join(self.outputDirectory, subFolder)
            dirName = os.path.normpath(dirName)

            if (needCreate) and (not os.path.exists(dirName)):
                self.logger.info("adding new directory: {}".format(dirName))
                if not mkdir_p(dirName):
                    return self.setError("can't create sub-directory: {}".format(dirName))

            fileName = os.path.join(dirName, fileName)
        else:
            fileName = os.path.join(self.outputDirectory, fileName)

        self.__output = cv.VideoWriter(fileName, fourcc, config.OUTPUT_FRAME_RATE, videoSize)

        self.__isRecording = True
        return True 
开发者ID:JFF-Bohdan,项目名称:pynvr,代码行数:36,代码来源:motion_driven_recorder.py

示例15: _startRecording

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import VideoWriter_fourcc [as 别名]
def _startRecording(self):
        if self.outputDirectory is None:
            return self.setError("output directory is not specified")

        if None in [self.frameWidth, self.frameHeight]:
            return self.setError("resolution is't specified")

        fourcc = cv.VideoWriter_fourcc(*config.FOURCC_CODEC)
        videoSize = (self.frameWidth, self.frameHeight)

        # calculation output filename
        now = dts.datetime.utcnow()
        fileName = "video_{}{}".format(now.strftime("%Y%m%dT%H%M%S"), config.OUTPUT_FILES_EXTENSION)

        subFolder = self._getSubFolderName(now)
        if subFolder is not None:
            needCreate = ((self._prevSubFolder is not None) or (subFolder != self._prevSubFolder))

            dirName = os.path.join(self.outputDirectory, subFolder)
            dirName = os.path.normpath(dirName)

            if (needCreate) and (not os.path.exists(dirName)):
                self.logger.info("adding new directory: {}".format(dirName))
                if not mkdir_p(dirName):
                    return self.setError("can't create sub-directory: {}".format(dirName))

            fileName = os.path.join(dirName, fileName)
        else:
            fileName = os.path.join(self.outputDirectory, fileName)

        self._output = cv.VideoWriter(fileName, fourcc, config.OUTPUT_FRAME_RATE, videoSize)

        self._isRecording = True
        return True 
开发者ID:JFF-Bohdan,项目名称:pynvr,代码行数:36,代码来源:motion_driven_recorder.py


注:本文中的cv2.VideoWriter_fourcc方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。