Пример #1
0
    def make_video(images, outvid=None, fps=5, size=None,
                   is_color=True, format="XVID"):
        """
        Create a video from a list of images.
        
        @param      outvid      output video
        @param      images      list of images to use in the video
        @param      fps         frame per second
        @param      size        size of each frame
        @param      is_color    color
        @param      format      see http://www.fourcc.org/codecs.php
        @return                 see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
 
        The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/.
        By default, the video will have the size of the first image.
        It will resize every image to this size before adding them to the video.
        """
        from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
        import os
        fourcc = VideoWriter_fourcc(*format)
        vid = None
        for image in images:
            if not os.path.exists(image):
                raise FileNotFoundError(image)
            img = imread(image)
            if vid is None:
                if size is None:
                    size = img.shape[1], img.shape[0]
                vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
            if size[0] != img.shape[1] and size[1] != img.shape[0]:
                img = resize(img, size)
            vid.write(img)
        vid.release()
        return vid        
Пример #2
0
    def extract_video(self):
        import cv2
        import numpy as np
        from cv2 import VideoWriter, VideoWriter_fourcc

        img_size = self.whole_game[0].shape[:-1]
        print(img_size)
        FPS = 10
        seconds = 10

        fourcc = VideoWriter_fourcc(*'MP42')
        num_file = len(os.listdir('./outputs'))
        level_name = 'level_1_map_05'  # must change to name of level
        path_to_save = os.path.join('./outputs', level_name + '.avi')
        video = VideoWriter(path_to_save, fourcc, float(FPS), img_size)

        draw = False
        for i, frame in enumerate(self.whole_game):
            print("Extract frame {}".format(i))
            frame = frame.transpose(1, 0, 2)
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
            video.write(frame)
            if random.randint(0, 100) < 30 and not draw:
                draw = True
                cv2.imwrite('map_01.png', frame)

        video.release()
        print("Extracted successfully.")
        print(self.cnt / 60 * 1000, self.score)
def save_vid(filename, image_stack, codec='MJPG', fps=30, **kwargs):
    """Saves image stack as a video file (better compression than gifs)
        Args:
        -----
            filename (str): path to savefile
            image_stack (np.ndarray): image stack in [z/t,x,y,c] format
            codec (str): opencv fourcc compatible codec, 4 char long str
    """

    fourcc = VideoWriter_fourcc(*codec)
    out = VideoWriter(filename, fourcc, fps, image_stack.shape[1:3][::-1],
                      **kwargs)

    # Rescale for video compatible format
    if not image_stack.dtype is np.uint8:
        image_stack = ((image_stack - image_stack.min()) /
                       (image_stack.max() - image_stack.min()) *
                       255).astype('uint8')
        # image_stack = np.clip(image_stack *255, 0,255).astype('uint8')

    for i in range(image_stack.shape[0]):
        if image_stack.shape[-1] == 1:
            out.write(cvtColor(image_stack[i], COLOR_GRAY2RGB))

        elif image_stack.shape[-1] == 3:
            out.write(image_stack[i])

        else:
            raise ValueError(
                f"Wrong number of channels for frame, should be 1 or 3, is {image_stack[i].shape[-1]}"
            )

    out.release()
def recreer_video(tab_video):
    print '--Suppression de bruit ...'
    # recuperer la table des images en supprimant les images etranges
    tab_sans_bruit = supprimer_bruit(tab_video)
    print '--Recherche de premier frame ...'
    tab_final = trouver_premier_frame(tab_sans_bruit)
    from cv2 import VideoWriter, imread, resize
    tab_final = tab_final[::-1]
    size = None
    fourcc = cv2.cv.CV_FOURCC(*'XVID')
    vid = None
    # recreer le video corriger avec le nom video_corrige.avi
    for i in range(0, len(tab_final) - 1):
        k = tab_final[i]
        img = imread('./frames/frame%d.jpg' % k)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter('./video_corrige.avi', fourcc, float(25), size,
                              True)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    print '*********** Video cree ***************'
    vid.release()
def video_from_folder(folder, output, fps):
    '''
    builds a video from all the .pngs in a folder
    IN: folder, output location, frames per second
    OUT: save location
    '''
    print("GETTING .PNG FROM:\t{}".format(folder))
    import os
    filenames = os.listdir(folder)

    for fichier in filenames[:]:  # filelist[:] makes a copy of filelist.
        if not (fichier.endswith(".png")):
            filenames.remove(fichier)

    from cv2 import VideoWriter, VideoWriter_fourcc, imread, destroyAllWindows

    print("CREATING VIDEO")
    fourcc = VideoWriter_fourcc(*'mp4v')
    vid = None
    for file in filenames:
        img = imread("{}/{}".format(folder, file))
        # now that we have an image we can setup vid
        if vid is None:
            size = img.shape[1], img.shape[0]
            print("SIZE:\t{}".format(size))
            # false for is_color
            vid = VideoWriter(output, fourcc, float(fps), size)

        vid.write(img)

    vid.release()
    destroyAllWindows()
    return output
Пример #6
0
class Processer:
    def __init__(self, input_file, output_file, FPS=30, max_count=-1):
        self.vidcap = VideoCapture(input_file)
        success, self.image = self.vidcap.read()
        self.width = int(self.vidcap.get(4))
        self.height = int(self.vidcap.get(3))
        fourcc = VideoWriter_fourcc(*'XVID')
        self.videoWriter = VideoWriter(output_file, fourcc, float(FPS),
                                       (self.height, self.width))
        self.max_count = max_count

    def run(self, proc_func, end_proc=None):
        count = 0
        success = True
        while success and (count < self.max_count or self.max_count == -1):
            result = proc_func(self.image, count, self.width, self.height)
            self.videoWriter.write(result)
            success, self.image = self.vidcap.read()
            print('Count:', count)
            count += 1

        if end_proc is not None:
            end_proc(self.videoWriter)
        self.videoWriter.release()
        self.vidcap.release()
        print('Total count:', count)
def make_video(outvid, images=None, fps=30, size=None,
               is_color=True, format="FMP4"):
    """
    Create a video from a list of images.
 
    @param      outvid      output video
    @param      images      list of images to use in the video
    @param      fps         frame per second
    @param      size        size of each frame
    @param      is_color    color
    @param      format      see http://www.fourcc.org/codecs.php
    @return                 see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
 
    The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/.
    By default, the video will have the size of the first image.
    It will resize every image to this size before adding them to the video.
    """
    from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
    fourcc = VideoWriter_fourcc(*format)
    vid = None
    for image in images:
        if not os.path.exists(image):
            raise FileNotFoundError(image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
    return vid
Пример #8
0
def jpg_to_video(char_image_path, FPS):
    video_fourcc = VideoWriter_fourcc(
        *"MP42")  # 设置视频编码器,这里使用使用MP42编码器,可以生成更小的视频文件
    char_img_path_list = [
        char_image_path + r'/{}.jpg'.format(i) for i in range(1, number + 1)
    ]  # 生成目标字符图片文件的路径列表
    char_img_test = Image.open(char_img_path_list[1]).size  # 获取图片的分辨率
    if not os.path.exists('video'):
        os.mkdir('video')
    video_writter = VideoWriter('video/new_char_video.avi', video_fourcc, FPS,
                                char_img_test)
    sum = len(char_img_path_list)
    count = 0
    for image_path in char_img_path_list:
        img = cv2.imread(image_path)
        video_writter.write(img)
        end_str = '100%'
        count = count + 1
        process_bar(count / sum,
                    start_str='',
                    end_str=end_str,
                    total_length=15)

    video_writter.release()
    print('\n')
    print('=======================')
    print('The video is finished!')
    print('=======================')
Пример #9
0
    def _write_frames_to_videofile(self, filename, path=None):
        '''Write frames to videofile
        '''
        # Init openCV VideoWriter
        fourcc = VideoWriter_fourcc(*self.options["codec"])
        if path is not None:
            filename_out = os.path.join(
                path, '{0}.{1}'.format(filename, self.options["container"]))
        else:
            filename_out = './{0}.{1}'.format(filename,
                                              self.options["container"])

        # print(filename_out)
        video = VideoWriter(
            filename_out,
            fourcc,
            float(self.options["fps"]),
            (self.options["image_width"], self.options["image_height"]),
            isColor=False
        )  # path, codec, fps, size. Note, the isColor the flag is currently supported on Windows only

        # Write frames to videofile frame-by-frame
        for index in np.arange(self.frames.shape[2]):
            video.write(self.frames[:, :, index])

        video.release()
Пример #10
0
    def create_video(radio: Radio):
        if not os.path.exists(Video.output_dir):
            print("Folder", Video.output_dir, 'does not exist. Creating...')
            os.makedirs(Video.output_dir)
        video = VideoWriter(Video.output_dir + os.sep + str(radio.radio_id) + '_temp.mp4', Video.fourcc, Video.fps, (Video.width, Video.height))
        clip_count = len(radio.timestamps) - 1
        for i in range(clip_count):
            if (radio.timestamps[i] not in radio.timeline.keys()):
                print(radio.timestamps[i], "has no corresponding image, load cover as backup")
                frame = Frame.create_cover(radio)
            else:
                frame = Frame.create_page(radio.timeline[radio.timestamps[i]], radio)
            frame_count = (radio.timestamps[i + 1] - radio.timestamps[i]) * Video.fps
            for j in range(frame_count):
                video.write(frame)
        video.release()

        video_clip = VideoFileClip(Video.output_dir + os.sep + str(radio.radio_id) + '_temp.mp4')
        print(video_clip.duration)
        audio_clip = AudioFileClip(os.sep.join(['.', 'cache', str(radio.radio_id), 'audio', radio.audio.local_name]))
        video_clip.audio = audio_clip
        if config['test']:
            video_clip = video_clip.subclip(0, min(200, video_clip.duration))
        video_clip.write_videofile(Video.output_dir +os.sep+ str(radio.radio_id)+" "+radio.title +".mp4", fps=Video.fps)
        print("{} finished!".format(radio.title))
        os.remove(Video.output_dir+os.sep+str(radio.radio_id)+'_temp.mp4')
Пример #11
0
def photo2video(videoName='./cache/output.mp4',
                fps=25,
                imgs='./cache/output_img'):
    '''将图片转换为视频,图片读取路径./cache/output_img.mp4,视频默认写入路径./movie/output.mp4,待合成图片默认文件夹路径./cache/output_img
    INPUTS
        videoName   视频写入路径
        fps         视频帧率
        imgs        待合成图片文件夹路径
    OUTPUTS
        None
    '''
    #获取图像分辨率
    img = cv2.imread(imgs + '/1.jpg')
    sp = img.shape
    height = sp[0]
    width = sp[1]
    size = (width, height)

    fourcc = VideoWriter_fourcc(*'mp4v')
    videoWriter = VideoWriter(videoName, fourcc, fps, size)
    photos = os.listdir(imgs)
    for photo in range(len(photos)):
        frame = cv2.imread(imgs + '/' + str(photo) + '.jpg')
        videoWriter.write(frame)
    videoWriter.release()
    #合成新生成的视频和音频
    if (os.path.exists('./movie/output.mkv')):
        os.remove('./movie/output.mkv')
    command = 'ffmpeg -i ./movie/output.mp4 -i ./cache/audio/audio.wav -c copy ./movie/output.mkv'
    subprocess.call(command,
                    shell=True,
                    stdout=open('/dev/null', 'w'),
                    stderr=subprocess.STDOUT)
    #os.remove('./cache/output.mp4')
    print('[*] 生成视频成功,路径为./cache/output.mkv')
Пример #12
0
def move_image_on_background(pattern, background):
    '''
    The function creates a video of the pattern moving horizontally over a given background

    Parameters:
    -----------
    pattern: <np.array, 35x35>
        The pattern supposed to move over the background
    background: <np.array, 260x346>
        A white background of the given size 
    '''
    fourcc = VideoWriter_fourcc(*'HFYU')
    video = VideoWriter('./videos/moving_pattern_for_sampling_exp.avi', fourcc, 30, (346, 260))
    background[112:147, 0:35] = pattern
    frame = background
    count = 0

    for _ in range(0, 346-34):

        cv2.imwrite("video_images/frame%04d.png" % count, cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB))
        video.write(cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB))
        shifted_frame =  np.roll(frame, 1, axis=1)
        frame = shifted_frame
        video.write(frame)
        count+=1

    cv2.destroyAllWindows()
    video.release()
Пример #13
0
def make_video(images, outvid=None, fps=30, size=None,
               is_color=True, format="x264"):
    # install on ubuntu:
    # sudo apt-get install ffmpeg x264 libx264-dev
    """
    Create a video from a list of images.
 
    @param      outvid      output video
    @param      images      list of images to use in the video
    @param      fps         frame per second
    @param      size        size of each frame
    @param      is_color    color
    @param      format      see http://www.fourcc.org/codecs.php
    @return                 see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
 
    The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/.
    By default, the video will have the size of the first image.
    It will resize every image to this size before adding them to the video.
    """
    fourcc = VideoWriter_fourcc(*format)
    vid = None
    for img in images:
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        img_ = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        vid.write(img_)
    vid.release()
    cv2.destroyAllWindows()
    return vid
Пример #14
0
def make_video(photos_path, video_path, video_name):
    cap = VideoCapture(v_path)
    fps = cap.get(CAP_PROP_FPS)
    cap.release()

    mkdir(video_path)

    images_cnt = jpgcount(photos_path)

    print(f'{images_cnt} imagenes')

    img = []

    # Cargar las imágenes
    for i in range(images_cnt):
        img.append(imread(photos_path + '/frame' + str(i) + '.jpg'))

    height, width, _ = img[1].shape

    # Inicializar el video
    video = VideoWriter(video_path + '/' + video_name + '.mp4',
                        VideoWriter_fourcc(*'MP4V'), fps, (width, height))

    print('Codificando video')

    # Insertar cada imagen
    for j in range(images_cnt):
        video.write(img[j])

    # Cerrar proceso
    destroyAllWindows()
    video.release()

    print('Video Codificado')
Пример #15
0
    def build_video_from_files(directory: str, filename: str, fps: int, size: tuple=None,
                         is_color: bool=True, format: str="XVID"):
        """
        Create a video from a folder of images, sorted by filename.
        By default, the video will have the size of the first image.
        It will resize every image to this size before adding them to the video.

        :param directory:   path to files
        :param filename:    name of video
        :param fps:         frames per second
        :param size:        video dimensions
        :param is_color:    colour video
        :param format:      see http://www.fourcc.org/codecs.php
        :return: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
        """
        fourcc = VideoWriter_fourcc(*format)
        vid = None

        for file in sorted(os.listdir(directory)):
            if not os.path.exists(file):
                raise FileNotFoundError(file)
            image = imread(file)
            if vid is None:
                if size is None:
                    size = image.shape[1], image.shape[0]
                vid = VideoWriter(filename, fourcc, fps, size, is_color)
            try:
                if size[0] != image.shape[1] and size[1] != image.shape[0]:
                    image = resize(image, size)
            except AttributeError:
                print(file)
            vid.write(image)
        vid.release()
        return vid
Пример #16
0
def generate_vid(dir_path,
                 vid_format='XVID',
                 outvid=None,
                 fps=25,
                 size=None,
                 is_color=True):
    from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize

    fourcc = VideoWriter_fourcc(*vid_format)
    # out = cv2.VideoWriter(video_name, fourcc, 20.0, (640,480))

    vid = None

    images = [str(p) for p in pathlib.Path(dir_path).iterdir()]
    natural_sort(images)

    for image in images:
        if not os.path.exists(image):
            raise Exception('Image path does not exist: %s' % image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
    return vid
Пример #17
0
def make_video(images, outvid=None, fps=5, size=None, is_color=True, format="XVID"):
    """
    Create a video from a list of images.
    @param      outvid      output video
    @param      images      list of images to use in the video
    @param      fps         frame per second
    @param      size        size of each frame
    @param      is_color    color
    @param      format      see http://www.fourcc.org/codecs.php
    """
    # fourcc = VideoWriter_fourcc(*format)
    # For opencv2 and opencv3:
    if int(cv2.__version__[0]) > 2:
        fourcc = cv2.VideoWriter_fourcc(*format)
    else:
        fourcc = cv2.cv.CV_FOURCC(*format)
    vid = None
    for image in images:
        assert os.path.exists(image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
Пример #18
0
    async def make_video_and_upload(self):
        outvid = self.OUTPUT_VIDEO_NAME
        fps = 24;
        size = (320, 240);
        is_color = 1;

        fourcc = VideoWriter_fourcc(*'XVID')
        vid = None
        images = []
        for i in range(0, self.max_count):
            images.append(self.VIDEO_IMAGES_FOLDER_NAME+"/image" + str(i) + ".jpg")

        for image in images:
            if not os.path.exists(image):
                raise FileNotFoundError(image)
            img = imread(image)
            if vid is None:
                if size is None:
                    size = img.shape[1], img.shape[0]
                vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
            if size[0] != img.shape[1] and size[1] != img.shape[0]:
                img = resize(img, size)
            vid.write(img)
        vid.release()

        self.insta.uploadVideo("video.avi", thumbnail=self.OUTPUT_IMAGE_NAME, caption="#memorieswithcozmo");
Пример #19
0
def draw_speed(video_path: str, speed_path: str, output_video: str) -> None:
    reader = VideoCapture(video_path)
    writer = VideoWriter(
        output_video,
        VideoWriter_fourcc(*"mp4v"),
        20,
        (640, 480),
    )
    data = loadtxt(speed_path, delimiter="\n", dtype="float32")

    frame_id = 0
    while reader.isOpened():
        ret, frame = reader.read()
        if not ret:
            break

        putText(
            frame,
            f"{data[frame_id]:0.3f}",
            (250, 420),
            FONT_HERSHEY_SIMPLEX,
            0.7,
            (255, 255, 255),
            2,
        )
        writer.write(frame)

        frame_id += 1
        if frame_id == data.shape[0]:
            break

    reader.release()
    writer.release()
Пример #20
0
    def make_video(outvid,
                   images=None,
                   fps=30,
                   size=None,
                   is_color=True,
                   format="AVC1"):
        """
        Create a video from a list of images.

        @param      outvid      output video
        @param      images      list of images to use in the video
        @param      fps         frame per second
        @param      size        size of each frame
        @param      is_color    color
        @param      format      see http://www.fourcc.org/codecs.php
        @return                 see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
        """
        from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
        fourcc = VideoWriter_fourcc(*format)
        vid = None
        print('len(images):', len(images))

        for image in images:
            if not os.path.exists(image):
                raise FileNotFoundError(image)
            img = imread(image)
            if vid is None:
                if size is None:
                    size = img.shape[1], img.shape[0]
                vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
            if size[0] != img.shape[1] and size[1] != img.shape[0]:
                img = resize(img, size)
            vid.write(img)
        vid.release()
        return vid
Пример #21
0
class VideoOutput():
    def __init__(self, opt):
        self.out_dir = os.path.join(opt.results_dir, opt.name,
                                    '%s_%s' % (opt.phase, opt.epoch))
        self.out_file = os.path.join(self.out_dir,
                                     opt.name + opt.phase + ".avi")
        self.writer = None

        if (os.path.exists(self.out_file)):
            os.remove(self.out_file)

    def writeFrame(self, visuals):

        i = 0
        for label, im_data in visuals.items():
            im = util.tensor2im(im_data)  #.transpose(2,1,0)

            if (i == 0):
                display = im
            else:
                display = np.concatenate((display, im), axis=1)
            i += 1

        #print(display.shape)
        if (self.writer == None):
            dims = display.shape[1], display.shape[0]
            self.writer = VideoWriter(self.out_file,
                                      VideoWriter_fourcc(*"XVID"), 30.0, dims,
                                      True)

        self.writer.write(cv2.cvtColor(display, cv2.COLOR_RGB2BGR))

    def close(self):
        self.writer.release()
Пример #22
0
def mri2vid(mri_data, dir_file, filename_no_ext, n_width, n_height,
            FramesPerSec):

    print(filename_no_ext + ' - MRI video started')

    output_file_no_ext = dir_file + filename_no_ext
    n_frames = len(mri_data)

    # compressed
    # fourcc = VideoWriter_fourcc(*'MP4V')

    # uncompressed 8-bit
    fourcc = VideoWriter_fourcc(*'Y800')
    video = VideoWriter(output_file_no_ext + '.avi', fourcc,
                        float(FramesPerSec), (n_width, n_height), 0)

    for n in range(n_frames):
        frame = np.uint8(255 * mri_data[n]).reshape(n_width, n_height, 1)

        video.write(frame)
        print('frame ', n, ' done', end='\r')

    video.release()

    print(filename_no_ext + ' - MRI video finished')
Пример #23
0
class Writer(WriterBase):
    def __init__(self,
                 file: str,
                 fourcc: Union[int, str, Iterable[str]],
                 fps: float,
                 frame_size: Tuple[int, int],
                 is_color: bool = True,
                 *args,
                 **kwargs):
        super(Writer, self).__init__(file, args, kwargs)
        self._fourcc: int = _fourcc(fourcc)
        self._fps: float = fps
        self._frame_size: Tuple[int, int] = frame_size
        self._is_color: bool = is_color
        self._stream: Optional[VideoWriter] = None

    def write_frame(self, frame: np.ndarray) -> None:
        self._stream.write(frame)
        self._position += 1

    def open(self, file: str = "", *args, **kwargs) -> None:
        if not self.closed:
            self.close()
        if file:
            self._file = file
        self._stream = VideoWriter(self._file, self._fourcc, self._fps,
                                   self._frame_size, self._is_color)
        self._closed = False

    def close(self) -> None:
        if not self.closed:
            self._stream.release()
            self._initialize_property()
Пример #24
0
def videoconvert(inp):
    capture = VideoCapture(inp)
    inp_ext = inp.split(".")
    fpsin = capture.get(CAP_PROP_FPS)
    count = 0
    success = 1
    while success:
        success, image = capture.read()
        if (success == False and image == None):
            pass
        else:
            imwrite("zzimg%d.jpg" % count, image)
            count += 1
    outfile = inp_ext[0] + '_output.mp4'
    fourcc = VideoWriter_fourcc(*'DIVX')
    fpsout = fpsin
    img = imread("zzimg0.jpg")
    height, width, layers = img.shape
    size = (width, height)
    out = VideoWriter(outfile, fourcc, fpsout, size, 0)
    for i in range(count):
        img = imread("zzimg%d.jpg" % i, 0)
        out.write(img)
    print(
        "Video Converted to Grayscale, Please check the folder for the output file: ",
        outfile)
    out.release()
    capture.release()

    return outfile
Пример #25
0
def save_out(output_path, out_matrix):
    out = VideoWriter(output_path, VideoWriter_fourcc(*'mp4v'), fps,
                      (out_matrix.shape[2], out_matrix.shape[1]))

    for frame in out_matrix:
        out.write(frame)
    out.release()
Пример #26
0
    def convert_frames_to_video(self, frame_array, debug_frame_array):
        """
            Takes list of frames and converts them to a video

            Parameters
            ----------
            frame_array : []
                Frames to be converted.
        """
        height, width, layers = frame_array[0].shape
        size = (width, height)
        date = time.strftime("%c")
        date = time.strftime("%Y-%m-%d %H:%M")
        path_out = str(date) + '_' + str(self.count)
        path_out = path_out.replace(" ", "_")
        path_out = path_out.replace(":", "")
        print(path_out)
        self.count += 1
        out = VideoWriter(path_out + '.avi', VideoWriter_fourcc('M', 'J', 'P', 'G'), self.fps, size)

        for i in range(len(frame_array)):
            out.write(frame_array[i])
        out.release()
        path_out = "debug-" + path_out + '_' + str(self.confidence)
        out = VideoWriter(path_out + '.avi', VideoWriter_fourcc('M', 'J', 'P', 'G'), self.fps, size)

        for i in range(len(debug_frame_array)):
            out.write(debug_frame_array[i])
        out.release()
        self.trigger = False
def images_to_video(filenames, output, fps):
    '''
    builds a video from a list of images
    IN: list of filenames for images, where to output, , frames per second
    OUT: filename for output video
    '''
    from cv2 import VideoWriter, VideoWriter_fourcc, imread, destroyAllWindows

    print("CREATING VIDEO")
    fourcc = VideoWriter_fourcc(*'mp4v')
    vid = None
    for file in filenames:
        img = imread(file)
        # now that we have an image we can setup vid
        if vid is None:
            size = img.shape[1], img.shape[0]
            print("SIZE:\t{}".format(size))
            # false for is_color
            vid = VideoWriter(output, fourcc, float(fps), size)

        vid.write(img)

    vid.release()
    destroyAllWindows()
    return output
Пример #28
0
def makeanimation():
    from cv2 import VideoWriter, VideoWriter_fourcc
    import glob

    # get width, heigth, frames
    f = open("./frames/0.ppm", "r")
    line0 = f.readline()
    line1 = f.readline().split(" ")
    width, height  = int(line1[0]), int(line1[1])
    frames = len(glob.glob("./frames/*.ppm"))
    FPS = 60

    fourcc = VideoWriter_fourcc(*'mp4v')
    video = VideoWriter('./fractal.mp4', fourcc, float(FPS), (width, height))
    frame = np.zeros((height, width, 3), dtype=np.uint8)

    for i in range(frames):
        f = open(f"./frames/{i}.ppm", "r")
        line0 = f.readline()
        line1 = f.readline()

        for x in range(height):
            for y in range(width):
                c = float(f.readline().split(" ")[0])%256
                frame[x, y] = [c, c, c]
        video.write(frame)
        print(f"Writing frame {i}")

    video.release()
    print("done")
Пример #29
0
def make_video(subs, outimg=None, fps=30, size=None,
               is_color=True, format="XVID"):
    fourcc = VideoWriter_fourcc(*format)
    vid = None
    total_frames=0
    subslist = [{"content":s.text, "start":to_deltatime(s.start), "end": to_deltatime(s.end)} for s in subs if len(s.text.strip()) >0]
    for (i, sub) in enumerate(subslist):
        image = paths[0][format_text(sub["content"])][0]
        if not os.path.exists(image):
            raise FileNotFoundError(image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter('video.mp4', fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)

        print(sub)
        if len(subslist) == i + 1:
            frames = int(sub["end"].total_seconds()*fps - total_frames)
        else:
            frames = int(subslist[i+1]["start"].total_seconds()*fps - total_frames)

        total_frames = frames + total_frames
        for i in range(frames):    
            vid.write(img)
    vid.release()
    return vid
Пример #30
0
class Video_writer():
    def __init__(self, videosource, fps, width, height, result):
        print("Initializing video writer.")
        self.audiofile = "tempaudio.mp3"
        self.videosource = videosource
        self.tempresult = "tempres.avi"
        try:
            if path.exists(self.tempresult):
                remove(self.tempresult)
        except WindowsError:
            print "Tempresult is being used"

        self.result = result
        fourcc = VideoWriter_fourcc(*'XVID')
        self.out = VideoWriter(self.tempresult, fourcc, fps,
                               (int(width), int(height)))

    def get_audio_clip(self):
        if path.exists(self.audiofile):
            remove(self.audiofile)
        mv.ffmpeg_extract_audio(self.videosource, self.audiofile)
        return

    def merge_audio_video(self):
        print("Merging audio and video.")
        self.get_audio_clip()
        mv.ffmpeg_merge_video_audio(self.tempresult, self.audiofile,
                                    self.result)
        remove(self.audiofile)

    def write_frame(self, frame):
        # test
        # if not self.start:
        #    self.start_window()
        #self.frame.DisplayNext(frame)
        #self.img.set_img(frame)
        #test

        #cv2.imshow('prototype',frame)
        self.out.write(frame)

    def finish_video(self, sound=True):
        print("Finishing video.")
        self.out.release()
        if sound:
            try:
                self.merge_audio_video()
            except:
                shutil.copy2(self.tempresult, self.result)
        else:
            shutil.copy2(self.tempresult, self.result)
        remove(self.tempresult)

    def quit(self):
        print("Quiting.")
        self.out.release()
        if path.exists(self.audiofile):
            remove(self.audiofile)
        if path.exists(self.tempresult):
            remove(self.tempresult)
Пример #31
0
def video_maker(images,
                outimg=None,
                fps=24,
                size=None,
                is_color=True,
                format="mp4v"):
    global overallTimeElapsed
    print("Overall Encryption time: %.2f" % overallTimeElapsed)
    fourcc = VideoWriter_fourcc(*format)
    vid = None
    outvid = './dirty_video.mp4'
    for image in images:
        if not os.path.exists(image):
            raise FileNotFoundError(image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
    print('Video Encrypted.')
    return vid
Пример #32
0
def make_video(images, output_path, fps=0.5, size=(640, 480), is_color=True):
    """
    Create a video from a list of images.
    """

    fourcc = VideoWriter_fourcc(*"XVID")
    vid = VideoWriter(output_path, fourcc, fps, size, is_color)
    for image in images:
        img = imread(image)
        vid.write(img)
    vid.release()
    return
Пример #33
0
class CV_Writer(object):
    """docstring for CV_Writer"""
    def __init__(self, file_loc,frame_rate,frame_size):
        super(CV_Writer, self).__init__()
        self.writer = VideoWriter(file_loc, VideoWriter_fourcc(*'DIVX'), float(frame_rate), frame_size)

    def write_video_frame(self, input_frame):
        self.writer.write(input_frame.img)


    def write_video_frame_yuv422(self, input_frame):
        raise NotImplementedError

    def release(self):
        self.writer.release()
Пример #34
0
def make_video(images, outvid=None, fps=5, size=None,
               is_color=True, format="XVID"):
    """
    Creates a video from a list of images.

    @param      outvid      output video
    @param      images      list of images to use in the video
    @param      fps         frames per second
    @param      size        size of each frame
    @param      is_color    color
    @param      format      see `fourcc <http://www.fourcc.org/codecs.php>`_
    @return                 `VideoWriter <http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/
                            py_gui/py_video_display/py_video_display.html>`_

    The function relies on `opencv <http://opencv-python-tutroals.readthedocs.org/en/latest/>`_.
    By default, the video will have the size of the first image.
    It will resize every image to this size before adding them to the video.
    The function does not use :epkg:`moviepy` but it is a
    a recommended module to do that.
    """
    if len(images) == 0:
        raise ValueError("no image to convert into a video")
    from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize  # pylint: disable=E0401
    fourcc = VideoWriter_fourcc(*format)
    vid = None
    for image in images:
        if not os.path.exists(image):
            raise FileNotFoundError(image)
        img = imread(image)
        if vid is None:
            if size is None:
                size = img.shape[1], img.shape[0]
            vid = VideoWriter(outvid, fourcc, float(fps), size, is_color)
        if size[0] != img.shape[1] and size[1] != img.shape[0]:
            img = resize(img, size)
        vid.write(img)
    vid.release()
    return vid
Пример #35
0
def captureTStamp(files, duration, cod,  fps=0, verbose=True):
    '''
    guarda por un tiempo en minutos (duration) el video levantado desde la
    direccion indicada en el archvo indicado. tambíen archivos con los time
    stamps de cada frame.
    
    files = [ur, saveVideoFile, saveDateFile, saveMillisecondFile]
    duration = time in mintes
    cod = codec
    fps = frames per second for video to be saved
    verbose = print messages to screen
    
    si fpscam=0 trata de llerlo de la captura. para fe hay que especificarla
    
    para opencv '2.4.9.1'
    
    Examples
    --------
    
    from cameraUtils import captureTStamp
    
    # para la FE
    duration = 1 # in minutes
    files = ['rtsp://192.168.1.48/live.sdp',
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/vca_test_tsFrame.txt"]
    fpsCam = 12
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fps=fpsCam)
    
    # %% para la PTZ
    duration = 0.2 # in minutes
    files = ["rtsp://192.168.1.49/live.sdp",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_video.avi",
             "/home/alumno/Documentos/sebaPhDdatos/ptz_test_tsFrame.txt"]  
    
    fpsCam = 20
    cod = 'XVID'
    
    captureTStamp(files, duration, cod, fpsCam)
    
    '''
    
    fcc = fourcc(cod[0],cod[1],cod[2],cod[3]) # Códec de video
    
    if verbose:
        print(files)
        print("Duration",duration,"minutes")
        print("fps",fps)
        print("codec",cod)
    
    # Inicializacion
    tFin = datetime.datetime.now() + datetime.timedelta(minutes=duration)
    
    ts = list()  # timestamp de la captura
    
    # abrir captura
    cap = VideoCapture(files[0])
    while not cap.isOpened():
        cap = VideoCapture(files[0])
    
    print("capture opened")
	# configurar writer
    w = int(cap.get(frame_width))
    h = int(cap.get(frame_height))
    if not fps:
        fps = cap.get(prop_fps)
    #para fe especificar los fps pq toma cualquier cosa con la propiedad
    
    out = VideoWriter(files[1], fcc, fps,( w, h), True)
    
    if verbose:
        print("capture open",cap.isOpened())
        print("frame size",w,h)
        print("output opened",out.isOpened())
    
    if not out.isOpened() or not cap.isOpened():
        out.release()
        cap.release()
        # exit function if unable to open cap or out
        return
    
    s0 = getsize(files[1]) # initial filesize before writing frame
    # Primera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("first frame captured")
    # Segunda captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("second frame captured")
    # Tercera captura
    ret, frame = cap.read()
    if ret:
        t = datetime.datetime.now()
        ts.append(t)
        out.write(frame)
        if verbose:
            print("third frame captured")
    
    s1 = getsize(files[1])  # size after saving 3 frames
    
    if s1==s0:
        out.release()
        cap.release()
        print("error when saving 3 frames, exiting")
        return 1 # error while saving first frame to file
    print(tFin)
    # loop
    while (t <= tFin):
        ret, frame = cap.read()
        
        if ret:
            t = datetime.datetime.now()
            ts.append(t)
            out.write(frame)
            if verbose:
                print(tFin,t)
                print("seconds elapsed",cap.get(pos_msec)/1000)
                print(frame.size)

    # end of loop
    
    # release and save
    out.release()
    cap.release()
    
    if verbose:
        print('loop exited, cap, out released, times saved to files')
        
    savetxt(files[2],ts, fmt= ["%s"])
    
    return 0  # success
Пример #36
0
    def run(self, show=False, save=False, tk_var_frame=None):
        if show:
            namedWindow('Movie')
            namedWindow('Tracking')
        if save:
            bgs = np.shape(self.background)
            fsize = (bgs[0], bgs[1]*2)
            writer = VideoWriter()
            writer.open(os.path.join(self.trial_dir,'%s_tracking_movie'%self.trial_name),self.fourcc,37.,frameSize=(fsize[1],fsize[0]),isColor=True)

        self.results['n_frames'] = 0
        consecutive_skips = 0
        while True:
            valid,frame = self.get_frame(self.mov,skip=self.resample-1)
            if not valid:
                break
            diff = absdiff(frame,self.background)
            _, diff = threshold(diff, self.diff_thresh, 1, THRESH_BINARY)
            diff = diff*self.rooms_mask
            edges = Canny(diff.astype(np.uint8), self.cth1, self.cth2)
            contours, hier = findContours(edges, RETR_EXTERNAL, CHAIN_APPROX_TC89_L1)
            contours = [c for c in contours if not any([pa.contains_point(contour_center(c)) for pa in self.paths_ignore])]
            if consecutive_skips>self.consecutive_skip_threshold:
                consecutive_skips=0
                possible = contours
            else:
                possible = [c for c in contours if dist(contour_center(c),self.last_center)<self.translation_max]
            
            if len(possible) == 0:
                center = self.last_center
                self.results['skipped'] += 1
                consecutive_skips+=1
                if self.path_l.contains_point(center):
                    self.results['left_assumed']+=1
                if self.path_r.contains_point(center):
                    self.results['right_assumed']+=1
                if self.path_c.contains_point(center):
                    self.results['middle_assumed']+=1
            else:
                chosen = possible[np.argmax([contourArea(c) for c in possible])]   
                center = contour_center(chosen)
                self.results['centers'].append(center)
                self.results['heat'][center[1],center[0]] += 1
                if self.path_l.contains_point(center):
                    self.results['left']+=1
                if self.path_r.contains_point(center):
                    self.results['right']+=1
                if self.path_c.contains_point(center):
                    self.results['middle']+=1
            self.results['centers_all'].append(center) 
            #display
            if show or save:
                showimg = np.copy(frame).astype(np.uint8)
                if self.path_l.contains_point(center):
                    color = (0,0,0)
                elif self.path_r.contains_point(center):
                    color = (255,255,255)
                else:
                    color = (120,120,120)
                circle(showimg, tuple(center), radius=10, thickness=5, color=color)
                if show:
                    cv2imshow('Movie',showimg)
                    cv2imshow('Tracking', diff)
                    waitKey(1)
            #/display
            if save:
                save_frame = np.zeros([fsize[0], fsize[1], 3],dtype=np.uint8)
                save_frame[:,:np.shape(frame)[1]] = cvtColor(showimg.astype(np.float32), CV_GRAY2RGB)
                save_frame[:,np.shape(frame)[1]:] = cvtColor((diff*255).astype(np.float32), CV_GRAY2RGB)
                writer.write(save_frame)
             
            self.results['n_frames'] += 1
            self.last_center = center
            if tk_var_frame != None:
                tk_var_frame[0].set('%i/%i'%(self.results['n_frames'], len(self.time)/float(self.resample) ))
                tk_var_frame[1].update()
            #pbar.update(self.results['n_frames'])
        #pbar.finish()
        if save:
            writer.release()
        self.end()
Пример #37
0
 def run(self, show=False, save=False, tk_var_frame=None, wait=1, start_pos='none'):
     #interfaces
     if show or save:
         fsize = (self.width*2, self.height)
         save_frame = np.zeros([self.height, self.width*2, 3], dtype=np.uint8)
     if show:
         namedWindow('Tracking')
     if save:
         writer = VideoWriter()
         writer.open(self.fh.make_path('tracking.avi'),self.fourcc,round(self.fs),frameSize=fsize,isColor=True)
     
     #run
     self.framei = 0
     self.pos = []
     self.t = []
     self.guess = []
     self.contour = []
     self.pct_xadj = []
     self.heat = np.zeros((self.height,self.width))
     consecutive_skips = 0
     if start_pos == 'x':
         start_pts = [self.xori_adj, self.xoli_adj]
     elif start_pos == 'y':
         start_pts = [self.yori_adj, self.yoli_adj]
     elif start_pos == 'z':
         start_pts = [self.zori_adj, self.zoli_adj]
     elif start_pos == 'c':
         start_pts = [self.zori, self.xori, self.yori]
     elif start_pos == 'none':
         start_pts = [self.zori, self.xori, self.yori]
         consecutive_skips = self.consecutive_skip_threshold+1
     self.last_center = np.mean(self.pts[np.array(start_pts)],axis=0).astype(int)
     self.last_contour = np.array([self.last_center])
     valid,frame,ts = self.get_frame(self.mov,skip=self.resample-1)
     while valid:
         possible,diff_raw = self.find_possible_contours(frame,consecutive_skips)
         self.pct_xadj.append(np.mean( diff_raw[self.xadj_idxs[:,0],self.xadj_idxs[:,1]]))
         
         if len(possible) == 0:
             center = self.last_center
             contour = self.last_contour
             self.guess.append(True)
             consecutive_skips+=1
         else:
             contour,center = self.choose_best_contour(possible)
             self.guess.append(False)
             consecutive_skips = 0
         self.pos.append(center)
         self.contour.append(contour)
         self.t.append(ts)
         self.heat[center[1],center[0]] += 1
         
         if show or save:
             lframe = self.label_frame(frame, center)
             save_frame[:,:self.width, :] = cvtColor(lframe.astype(np.float32), CV_GRAY2RGB)
             save_frame[:,self.width:, :] = cvtColor((self.diff*255).astype(np.float32), CV_GRAY2RGB)
         if show:
             self.show_frame(save_frame, wait=wait)
         if save:
             writer.write(save_frame)
          
         self.last_center = center
         self.last_contour = contour
         valid,frame,ts = self.get_frame(self.mov,skip=self.resample-1)
     
         if tk_var_frame != None:
             tk_var_frame[0].set('%i/%i'%(self.results['n_frames'], len(self.time)/float(self.resample) ))
             tk_var_frame[1].update()
     if save:
         writer.release()
     self.end()