Python cv2.VideoWriter() Examples

The following are 30 code examples of cv2.VideoWriter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: utilities.py    From sepconv with MIT License 28 votes vote down vote up
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() 
Example #2
Source File: video.py    From videoflow with MIT License 10 votes vote down vote up
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) 
Example #3
Source File: rivagan.py    From RivaGAN with MIT License 9 votes vote down vote up
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() 
Example #4
Source File: tkinter_functions.py    From simba with GNU Lesser General Public License v3.0 8 votes vote down vote up
def clahe(filename):
    os.chdir(os.path.dirname(filename))
    print('Applying CLAHE, this might take awhile...')

    currentVideo = os.path.basename(filename)
    fileName, fileEnding = currentVideo.split('.',2)
    saveName = str('CLAHE_') + str(fileName) + str('.avi')
    cap = cv2.VideoCapture(currentVideo)
    imageWidth = int(cap.get(3))
    imageHeight = int(cap.get(4))
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter(saveName, fourcc, fps, (imageWidth, imageHeight), 0)
    try:
        while True:
            ret, image = cap.read()
            if ret == True:
                im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                claheFilter = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16))
                claheCorrecttedFrame = claheFilter.apply(im)
                out.write(claheCorrecttedFrame)
                if cv2.waitKey(10) & 0xFF == ord('q'):
                    break
            else:
                print(str('Completed video ') + str(saveName))
                break
    except:
        print('clahe not applied')
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    return saveName 
Example #5
Source File: draw_detail_2D.py    From NoiseFace with MIT License 6 votes vote down vote up
def draw_video(prefix1, prefix2, ratio):
    draw_imgs(prefix1, ratio, mode=1)
    draw_imgs(prefix2, ratio, mode=2)

    fps = 25
    size = (2000, 2000) 
    videowriter = cv2.VideoWriter("./figures/demo_2D_distribution_noise-%d%%.avi" % ratio, cv2.cv.CV_FOURCC(*"MJPG"), fps, size)
    for _iter in xrange(1000, 200000+1, 100):
        if not choose_iter(_iter, 100):
            continue
        image_file1 = "./figures/%s_2D_dist_%d.jpg" % (prefix1, _iter)
        img1 = cv2.imread(image_file1)
        h1, w1, c1 = img1.shape

        image_file2 = "./figures/%s_2D_dist_%d.jpg" % (prefix2, _iter)
        img2 = cv2.imread(image_file2)
        h2, w2, c2 = img2.shape

        assert h1 == h2 and w1 == w2
        img = np.zeros((h1, w1+w2, c1), dtype=img1.dtype)

        img[0:h1, 0:w1, :] = img1
        img[0:h1, w1:w1+w2, :] = img2
        videowriter.write(img) 
Example #6
Source File: img_utils.py    From tools_python with Apache License 2.0 6 votes vote down vote up
def one_pic_to_video(image_path, output_video_path, fps, time):
    """
    一张图片合成视频
    one_pic_to_video('./../source/1.jpeg', './../source/output.mp4', 25, 10)
    :param path: 图片文件路径
    :param output_video_path:合成视频的路径
    :param fps:帧率
    :param time:时长
    :return:
    """

    image_clip = ImageClip(image_path)
    img_width, img_height = image_clip.w, image_clip.h

    # 总共的帧数
    frame_num = (int)(fps * time)

    img_size = (int(img_width), int(img_height))

    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')

    video = cv2.VideoWriter(output_video_path, fourcc, fps, img_size)

    for index in range(frame_num):
        frame = cv2.imread(image_path)
        # 直接缩放到指定大小
        frame_suitable = cv2.resize(frame, (img_size[0], img_size[1]), interpolation=cv2.INTER_CUBIC)

        # 把图片写进视频
        # 重复写入多少次
        video.write(frame_suitable)

    # 释放资源
    video.release()

    return VideoFileClip(output_video_path) 
Example #7
Source File: AVrecordeR.py    From AVrecordeR with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #8
Source File: show.py    From Siamese-RPN-tensorflow with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: demo.py    From pytorch_mpiigaze with MIT License 5 votes vote down vote up
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 
Example #10
Source File: images2video.py    From Realtime-Action-Recognition with MIT License 5 votes vote down vote up
def write(self, img):
        self.cnt_img += 1
        if self.cnt_img == 1:  # initialize the video writer
            fourcc = cv2.VideoWriter_fourcc(*'XVID')  # define the codec
            self.width = img.shape[1]
            self.height = img.shape[0]
            self.video_writer = cv2.VideoWriter(
                self.video_path, fourcc, self.framerate, (self.width, self.height))
        self.video_writer.write(img) 
Example #11
Source File: capture_video.py    From pytorch_mpiigaze with MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', '-o', type=str, default='videos')
    parser.add_argument('--cap-size', type=int, nargs=2, default=(640, 480))
    args = parser.parse_args()

    cap = cv2.VideoCapture(0)
    width, height = args.cap_size
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

    output_dir = pathlib.Path(args.output)
    output_dir.mkdir(exist_ok=True, parents=True)
    output_path = output_dir / f'{create_timestamp()}.mp4'
    writer = cv2.VideoWriter(output_path.as_posix(),
                             cv2.VideoWriter_fourcc(*'H264'), 30,
                             (width, height))

    while True:
        key = cv2.waitKey(1) & 0xff
        if key in QUIT_KEYS:
            break

        ok, frame = cap.read()
        if not ok:
            break

        writer.write(frame)
        cv2.imshow('frame', frame[:, ::-1])

    cap.release()
    writer.release() 
Example #12
Source File: lib_images_io.py    From Realtime-Action-Recognition with MIT License 5 votes vote down vote up
def write(self, img):
        self._cnt_img += 1
        if self._cnt_img == 1:  # initialize the video writer
            fourcc = cv2.VideoWriter_fourcc(*'XVID')  # define the codec
            self._width = img.shape[1]
            self._height = img.shape[0]
            self._video_writer = cv2.VideoWriter(
                self._video_path, fourcc, self._framerate, (self._width, self._height))
        self._video_writer.write(img) 
Example #13
Source File: VidStab.py    From python_video_stab with MIT License 5 votes vote down vote up
def apply_transforms(self, input_path, output_path, output_fourcc='MJPG',
                         border_type='black', border_size=0, layer_func=None, show_progress=True, playback=False):
        """Apply stored transforms to a video and save output to file

        Use the transforms generated by ``VidStab.gen_transforms`` or ``VidStab.stabilize`` in stabilization process.
        This method is a wrapper for ``VidStab.stabilize`` with ``use_stored_transforms=True``;
        it is included for backwards compatibility.

        :param input_path: Path to input video to stabilize.
                           Will be read with ``cv2.VideoCapture``; see opencv documentation for more info.
        :param output_path: Path to save stabilized video.
                            Will be written with ``cv2.VideoWriter``; see opencv documentation for more info.
        :param output_fourcc: FourCC is a 4-byte code used to specify the video codec.
        :param border_type: How to handle negative space created by stabilization translations/rotations.
                            Options: ``['black', 'reflect', 'replicate']``
        :param border_size: Size of border in output.
                            Positive values will pad video equally on all sides,
                            negative values will crop video equally on all sides,
                            ``'auto'`` will attempt to minimally pad to avoid cutting off portions of transformed frames
        :param layer_func: Function to layer frames in output.
                           The function should accept 2 parameters: foreground & background.
                           The current frame of video will be passed as foreground,
                           the previous frame will be passed as the background
                           (after the first frame of output the background will be the output of
                           layer_func on the last iteration)
        :param show_progress: Should a progress bar be displayed to console?
        :param playback: Should the a comparison of input video/output video be played back during process?
        :return: Nothing is returned.  Output of stabilization is written to ``output_path``.

        >>> from vidstab.VidStab import VidStab
        >>> stabilizer = VidStab()
        >>> stabilizer.gen_transforms(input_path='input_video.mov')
        >>> stabilizer.apply_transforms(input_path='input_video.mov', output_path='stable_video.avi')
        """
        self.stabilize(input_path, output_path, smoothing_window=self._smoothing_window, max_frames=float('inf'),
                       border_type=border_type, border_size=border_size, layer_func=layer_func, playback=playback,
                       use_stored_transforms=True, show_progress=show_progress, output_fourcc=output_fourcc) 
Example #14
Source File: store_video.py    From scarecrow with GNU General Public License v3.0 5 votes vote down vote up
def run_after(self, res, ix, confidence, np_det_img):
        # TODO: SIGTERM handler
        # TODO: detection labels as *args
        logger.debug('StoreVideoPlugin run_after ix {} / buf {}'.format(ix, len(self.buffer)))
        if np_det_img is not None:
            img = np_det_img.astype(np.uint8)
            self.buffer.append(img)
        else:
            logger.warning('Store video frame is null?')

        if len(self.buffer) > self.buffer_size:
            dt = datetime.datetime.now().isoformat()
            vid_path = '{}/{}_{}'.format(self.video_path, dt, self.name)
            logger.info('Flushing video to {}'.format(vid_path))
            fourcc = cv2.VideoWriter_fourcc(*self.codec) #mp4v
            video = cv2.VideoWriter(
                vid_path, 
                fourcc, 
                self.fps, 
                (self.buffer[0].shape[1], self.buffer[0].shape[0]),
                True)
            for frame in self.buffer:
                video.write(frame)
            video.release()
            cv2.destroyAllWindows()
            # Clear buffer
            self.buffer = []
            # Save a separate key frame 
            img = Image.fromarray(np_det_img, 'RGB')
            thumb_path = '{}/{}_{}_thumb.jpg'.format(self.video_path, dt, ix)
            logger.info('Flushing thumbnail to {}'.format(thumb_path))
            img.save(thumb_path) 
Example #15
Source File: draw_detail_3D.py    From NoiseFace with MIT License 5 votes vote down vote up
def draw_video(prefix1, prefix2, ratio):
    draw_imgs(prefix1, ratio, mode=1)
    draw_imgs(prefix2, ratio, mode=2)

    fps = 25
    #size = (4800, 1800) 
    #size = (2400, 900) 
    size = (2000, 750) 
    videowriter = cv2.VideoWriter("./figures/demo_3D_distribution_noise-%d%%.avi" % ratio, cv2.cv.CV_FOURCC(*"MJPG"), fps, size)
    for _iter in xrange(1000, 200000+1, 1000):
        if not choose_iter(_iter, 1000):
            continue
        image_file1 = "./figures/%s_3D_dist_%d.jpg" % (prefix1, _iter)
        img1 = cv2.imread(image_file1)
        img1 = cv2.resize(img1, (1000, 750))##
        h1, w1, c1 = img1.shape

        image_file2 = "./figures/%s_3D_dist_%d.jpg" % (prefix2, _iter)
        img2 = cv2.imread(image_file2)
        img2 = cv2.resize(img2, (1000, 750))##
        h2, w2, c2 = img2.shape

        assert h1 == h2 and w1 == w2
        img = np.zeros((size[1], size[0], 3), dtype=img1.dtype)

        img[0:h1, 0:w1, :] = img1
        img[0:h1, w1:w1+w2, :] = img2
        videowriter.write(img) 
Example #16
Source File: images2video.py    From Realtime-Action-Recognition with MIT License 5 votes vote down vote up
def main(args):

    images_loader = ReadFromFolder(args.input_folder_path)
    video_writer = VideoWriter(args.output_video_path, args.framerate)
    img_displayer = ImageDisplayer()

    N = len(images_loader)
    i = 0
    while i < N:
        print("Processing {}/{}th image".format(i, N))
        img = images_loader.read_image()
        if i % args.sample_interval == 0:
            video_writer.write(img)
            img_displayer.display(img)
        i += 1 
Example #17
Source File: videoprocessing.py    From B-SOID with GNU General Public License v3.0 5 votes vote down vote up
def create_labeled_vid(labels, crit=3, counts=3, frame_dir=FRAME_DIR, output_path=SHORTVID_DIR):
    """
    :param labels: 1D array, labels from training or testing
    :param crit: scalar, minimum duration for random selection of behaviors, default 300ms
    :param counts: scalar, number of randomly generated examples, default 5
    :param frame_dir: string, directory to where you extracted vid images in LOCAL_CONFIG
    :param output_path: string, directory to where you want to store short video examples in LOCAL_CONFIG
    """
    images = [img for img in os.listdir(frame_dir) if img.endswith(".png")]
    sort_nicely(images)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    frame = cv2.imread(os.path.join(frame_dir, images[0]))
    height, width, layers = frame.shape
    rnges = []
    n, idx, lengths = repeatingNumbers(labels)
    idx2 = []
    for i, j in enumerate(lengths):
        if j >= crit:
            rnges.append(range(idx[i], idx[i] + j))
            idx2.append(i)
    for i in tqdm(range(0, len(np.unique(labels)))):
        a = []
        for j in range(0, len(rnges)):
            if n[idx2[j]] == i:
                a.append(rnges[j])
        try:
            rand_rnges = random.sample(a, counts)
            for k in range(0, len(rand_rnges)):
                video_name = 'group_{}_example_{}.mp4'.format(i, k)
                grpimages = []
                for l in rand_rnges[k]:
                    grpimages.append(images[l])
                video = cv2.VideoWriter(os.path.join(output_path, video_name), fourcc, 5, (width, height))
                for image in grpimages:
                    video.write(cv2.imread(os.path.join(frame_dir, image)))
                cv2.destroyAllWindows()
                video.release()
        except:
            pass
    return 
Example #18
Source File: VidStab.py    From python_video_stab with MIT License 5 votes vote down vote up
def _init_writer(self, output_path, frame_shape, output_fourcc, fps):
        # set output and working dims
        h, w = frame_shape

        # setup video writer
        self.writer = cv2.VideoWriter(output_path,
                                      cv2.VideoWriter_fourcc(*output_fourcc),
                                      fps, (w, h), True) 
Example #19
Source File: preprocess.py    From filmstrip with MIT License 5 votes vote down vote up
def extractROI(sourcePath, destPath, points, verbose=False):
    info = getInfo(sourcePath)
    # x, y, width, height = cv2.boundingRect(points)

    # print(x,y,width,height)/
    x = points[0][0]
    y = points[0][1]

    width = points[1][0] - points[0][0]
    height = points[1][1] - points[0][1]

    cap = cv2.VideoCapture(sourcePath)

    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    out = cv2.VideoWriter(destPath,
        fourcc,
        info["fps"],
        (width, height))

    ret = True
    while(cap.isOpened() and ret):
        ret, frame = cap.read()
        if frame is None:
            break

        roi = frame[y:y+height, x:x+width]

        out.write(roi)

        if verbose:
            cv2.imshow('frame', roi)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

    cap.release()
    out.release()
    cv2.destroyAllWindows()


# Groups a list in n sized tuples 
Example #20
Source File: video.py    From deepstar with BSD 3-Clause Clear License 5 votes vote down vote up
def create_one_video_file_from_many_image_files(image_paths, video_path):
    """
    This method creates one video file from many image files.

    :param function image_paths: The generator function that returns the paths
        to the image files.
    :param str video_path: The path to the video file.
    :rtype: bool
    """

    vw = None

    try:
        for image_path in image_paths():
            image = cv2.imread(image_path)
            if image is None:
                return False

            # Initialize VideoWriter based on dimensions of first image.
            if vw is None:
                height, width = image.shape[:2]

                vw = cv2.VideoWriter(video_path,
                                     cv2.VideoWriter_fourcc(*'mp4v'),
                                     30.0, (width, height))
                if vw is None:
                    return False

            vw.write(image)
    finally:
        if vw is not None:
            vw.release()

    return True 
Example #21
Source File: video.py    From deepstar with BSD 3-Clause Clear License 5 votes vote down vote up
def create_one_video_file_from_one_image_file(image_path, video_path,
                                              frame_count=1):
    """
    This method creates one video file from one image file.

    :param str image_path: The path to the image file.
    :param str video_path: The path to the video file.
    :param int frame_count: The image is added frame_count number of times to
        the video. The default value is 1.
    :rtype: bool
    """

    image = cv2.imread(image_path)
    if image is None:
        return False

    height, width = image.shape[:2]

    vw = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), 30.0,
                         (width, height))
    if vw is None:
        return False

    try:
        for _ in range(0, frame_count):
            vw.write(image)
    finally:
        vw.release()

    return True 
Example #22
Source File: video2video.py    From Photomosaic-generator with MIT License 5 votes vote down vote up
def main(opt):
    cap = cv2.VideoCapture(opt.input)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    if opt.fps == 0:
        fps = int(cap.get(cv2.CAP_PROP_FPS))
    else:
        fps = opt.fps
    out = cv2.VideoWriter(opt.output, cv2.VideoWriter_fourcc(*"XVID"), fps, (width, height))
    images, avg_colors = get_component_images(opt.pool, opt.stride)

    while cap.isOpened():
        flag, frame = cap.read()
        if not flag:
            break
        blank_image = np.zeros((height, width, 3), np.uint8)
        for i, j in product(range(int(width / opt.stride)), range(int(height / opt.stride))):
            partial_input_image = frame[j * opt.stride: (j + 1) * opt.stride,
                                  i * opt.stride: (i + 1) * opt.stride, :]
            partial_avg_color = np.sum(np.sum(partial_input_image, axis=0), axis=0) / (opt.stride ** 2)
            distance_matrix = np.linalg.norm(partial_avg_color - avg_colors, axis=1)
            idx = np.argmin(distance_matrix)
            blank_image[j * opt.stride: (j + 1) * opt.stride, i * opt.stride: (i + 1) * opt.stride, :] = images[idx]
        if opt.overlay_ratio:
            overlay = cv2.resize(frame, (int(width * opt.overlay_ratio), int(height * opt.overlay_ratio)))
            blank_image[height-int(height*opt.overlay_ratio):, width-int(width*opt.overlay_ratio):,:] = overlay
        out.write(blank_image)
    cap.release()
    out.release() 
Example #23
Source File: test_video_loader.py    From eva with Apache License 2.0 5 votes vote down vote up
def create_sample_video(self):
        try:
            os.remove('dummy.avi')
        except FileNotFoundError:
            pass

        out = cv2.VideoWriter('dummy.avi',
                              cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10,
                              (2, 2))
        for i in range(NUM_FRAMES):
            frame = np.array(np.ones((2, 2, 3)) * 0.1 * float(i + 1) * 255,
                             dtype=np.uint8)
            out.write(frame) 
Example #24
Source File: pic_to_vedio.py    From Siamese-RPN-tensorflow with MIT License 5 votes vote down vote up
def test(self):
        pre_box=[50.,50.,50.,50.]
        for step in range(self.reader.img_num):
            img,box_ori,img_p,box_p,offset,ratio=self.reader.get_data(frame_n=step,pre_box=pre_box)
            if step==0:
                fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
                img_h,img_w,_=img.shape
                videoWriter=cv2.VideoWriter(os.path.join(self.vedio_dir,self.vedio_name),fourcc,30,(img_w,img_h))
            else:
                videoWriter.write(img)
                cv2.imshow('img',img)
                cv2.waitKey(10)
        videoWriter.release()
        cv2.destroyAllWindows()
        print('vedio is saved in '+self.vedio_dir) 
Example #25
Source File: save_result_to_video.py    From SiamFC-tf with MIT License 5 votes vote down vote up
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() 
Example #26
Source File: yolo.py    From keras-yolo3-master with MIT License 5 votes vote down vote up
def detect_video(yolo, video_path, output_path=""):
    import cv2
    vid = cv2.VideoCapture(0)

    if not vid.isOpened():
        raise IOError("Couldn't open webcam or video")
    video_FourCC    = int(vid.get(cv2.CAP_PROP_FOURCC))
    video_fps       = vid.get(cv2.CAP_PROP_FPS)
    video_size      = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),
                        int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    isOutput = True if output_path != "" else False
    if isOutput:
        print("!!! TYPE:", type(output_path), type(video_FourCC), type(video_fps), type(video_size))
        out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)
    accum_time = 0
    curr_fps = 0
    fps = "FPS: ??"
    prev_time = timer()
    while True:
        return_value, frame = vid.read()
        image = Image.fromarray(frame)
        image = yolo.detect_image(image)
        result = np.asarray(image)
        curr_time = timer()
        exec_time = curr_time - prev_time
        prev_time = curr_time
        accum_time = accum_time + exec_time
        curr_fps = curr_fps + 1
        if accum_time > 1:
            accum_time = accum_time - 1
            fps = "FPS: " + str(curr_fps)
            curr_fps = 0
        cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=0.50, color=(255, 0, 0), thickness=2)
        cv2.namedWindow("result", cv2.WINDOW_NORMAL)
        cv2.imshow("result", result)
        if isOutput:
            out.write(result)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    yolo.close_session() 
Example #27
Source File: record_model.py    From DDRL with Apache License 2.0 5 votes vote down vote up
def record_model(model_path, video_name, length=120):
    player, gpl = get_player(videofile=video_name, length=length)
    video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'MJPG'), 30, gpl.get_shape())
    current_length = 0
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, model_path)

        while current_length < length * 30:
            player, gpl = get_player(videofile=video_name, length=length)
            gpl.set_video(video, current_length)
            spc = player.get_action_space()
            score = 0.
            isOver = False

            while not isOver:
                image = player.current_state()
                dist = sess.run(record_model.policy, feed_dict={record_model.state: [image]})[0]
                a = np.argmax(dist)
                if np.random.random() < 0.001:
                    act = spc.sample()

                r, isOver = player.action(a)
                score += r

            video = gpl.video
            current_length = gpl.current_length

    print("Saving video to : {}".format(video_name))
    video.release() 
Example #28
Source File: data.py    From Sorting_Visualization with MIT License 5 votes vote down vote up
def __init__(self, Length, time_interval=1, 
                                sort_title="Figure", 
                                is_resampling=False, 
                                is_sparse=False, 
                                record=False, 
                                sound=False, sound_interval=16,
                                fps=25):
        self.data = [x for x in range(Length)]
        if is_resampling:
            self.data = random.choices(self.data, k=Length)
        else:
            self.Shuffle()
        if is_sparse:
            self.data = [x if random.random() < 0.3 else 0 for x in self.data]

        self.length = Length

        self.SetTimeInterval(time_interval)
        self.SetSortType(sort_title)
        self.Getfigure()
        self.InitTime()

        self.record = record
        if record:
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            self.vdo_wtr = cv2.VideoWriter("%s.avi"%self.sort_title, fourcc, fps, (self.im_size, self.im_size), True)
        
        self.sound = sound
        if sound and pygame is not None:
            self.SetSoundInterval(sound_interval)
            self.GetSoundArray()

        self.Visualize() 
Example #29
Source File: videowriter.py    From pyimagevideo with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #30
Source File: YOLOtest.py    From Traffic_sign_detection_YOLO with MIT License 5 votes vote down vote up
def __init__(self,video=False):
        self.config = json.load(open('../config3.json'))
        self.video=video
        print(self.config)
        self.options = self.config['yoloConfig']
        self.tfnet = TFNet(self.options)
        self.predictThresh = 0.05
        self.getAnnotations()
        print(self.anotations_list)
        if self.video:
            # self.cap = cv2.VideoCapture(0)
            self.cap = cv2.VideoCapture('../../WPI_vdo.mov')
            self.out = cv2.VideoWriter('output.avi',-1, 20.0, (640,480))