Python cv2.VideoWriter_fourcc() Examples

The following are 30 code examples of cv2.VideoWriter_fourcc(). 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: video.py    From Advanced-Deep-Learning-with-Keras with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: yolov3_object_tracking.py    From keras-yolov3-KF-objectTracking with MIT License 6 votes vote down vote up
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
    
    # 图片变视频 
Example #7
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 #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: 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 #10
Source File: Main.py    From bjtu_BinocularCameraRecord with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: utils.py    From ActionAI with GNU General Public License v3.0 6 votes vote down vote up
def source_capture(source):
    source = int(source) if source.isdigit() else source
    cap = cv2.VideoCapture(source)

    fourcc_cap = cv2.VideoWriter_fourcc(*'MJPG')
    cap.set(cv2.CAP_PROP_FOURCC, fourcc_cap)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, cfg.w)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, cfg.h)
    return cap 
Example #12
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 #13
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 #14
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 #15
Source File: Writers.py    From PyKinectTk with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, fps=30.0):

        fourcc    = VideoWriter_fourcc(*"XVID")
        self.path = path
        self.data = writer(self.path, fourcc, fps, (1920,1080)) 
Example #16
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=5, 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 b, i in enumerate(tqdm(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 #17
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 #18
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 #19
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 #20
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 #21
Source File: enrollment.py    From libfaceid with MIT License 5 votes vote down vote up
def save_video(saveVideo, out, resolution, filename):
    if saveVideo == True:
        print("video recording ended!")
        out.release()
        out = None
        saveVideo = False
    else:
        print("video recording started...")
        print("Press space key to stop recording!")
        fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
        (h, w) = resolution
        out = cv2.VideoWriter(filename, fourcc, 12, (w, h))
        saveVideo = True
    return saveVideo, out

# inner 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
Source File: motion_driven_recorder.py    From pynvr with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #29
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 #30
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()