Exemplo n.º 1
0
def adam_spanbaauer(video_pth: str, debug: bool = False):
    if os.path.exists('../.cache/default_stable_video.avi'):
        print("Cached Video")
        out = cv2.VideoCapture('../.cache/default_stable_video.avi')

    else:
        # Using defaults
        stabilizer = VidStab()
        stabilizer.stabilize(input_path=video_pth,
                             output_path='../.cache/default_stable_video.avi')

        # Using a specific keypoint detector
        stabilizer = VidStab(kp_method='ORB')
        stabilizer.stabilize(input_path=video_pth,
                             output_path='../.cache/ORB_stable_video.avi')

        # Using a specific keypoint detector and customizing keypoint parameters
        stabilizer = VidStab(kp_method='FAST',
                             threshold=42,
                             nonmaxSuppression=False)
        stabilizer.stabilize(input_path=video_pth,
                             output_path='../.cache/FAST_stable_video.avi')

        out = cv2.VideoCapture('../.cache/default_stable_video.avi')

        if debug:
            stabilizer.plot_trajectory()
            plt.show()

            stabilizer.plot_transforms()
            plt.show()
    generate_frames(out, "adam")
    def test_kp_options(self):
        stabilizer = VidStab(kp_method='FAST', threshold=42, nonmaxSuppression=False)
        self.assertFalse(stabilizer.kp_detector.getNonmaxSuppression(), 'FAST kp non-max suppression flag')
        self.assertEqual(stabilizer.kp_detector.getThreshold(), 42, 'FAST kp custom threshold')

        with self.assertRaises(TypeError) as err:
            VidStab(kp_method='FAST', fake='fake')
        self.assertTrue(isinstance(err.exception, TypeError), 'reject bad kwargs')
Exemplo n.º 3
0
def test_kp_options():
    stabilizer = VidStab(kp_method='FAST', threshold=42, nonmaxSuppression=False)
    assert not stabilizer.kp_detector.getNonmaxSuppression()
    assert stabilizer.kp_detector.getThreshold() == 42

    with pytest.raises(TypeError) as err:
        VidStab(kp_method='FAST', fake='fake')

    assert 'invalid keyword argument' in str(err.value)
 def __init__(self, directory, file_name):
     """Initialise variables and start stabilising"""
     self.directory = directory
     self.file = file_name
     self.new_file = file_name[:-4]
     self.stabiliser = VidStab()
     self.stabilise_video()
Exemplo n.º 5
0
    def test_trajectory_transform_values(self):
        # input_vid = 'https://s3.amazonaws.com/python-vidstab/ostrich.mp4'
        input_vid = local_vid
        base_url = 'https://s3.amazonaws.com/python-vidstab'
        stabilizer = VidStab()

        for window in [15, 30, 60]:
            stabilizer.gen_transforms(input_path=input_vid,
                                      smoothing_window=window)

            transform_file = '{}/ostrich_transforms_{}.pickle'.format(
                base_url, window)
            trajectory_file = '{}/ostrich_trajectory_{}.pickle'.format(
                base_url, window)
            smooth_trajectory_file = '{}/ostrich_smooth_trajectory_{}.pickle'.format(
                base_url, window)

            with urlopen(transform_file) as f:
                expected_transforms = pickle.load(f)
            with urlopen(trajectory_file) as f:
                expected_trajectory = pickle.load(f)
            with urlopen(smooth_trajectory_file) as f:
                expected_smooth_trajectory = pickle.load(f)

            self.assertTrue(
                np.allclose(stabilizer.transforms, expected_transforms))
            self.assertTrue(
                np.allclose(stabilizer.trajectory, expected_trajectory))
            self.assertTrue(
                np.allclose(stabilizer.smoothed_trajectory,
                            expected_smooth_trajectory))
Exemplo n.º 6
0
    def test_video_dep_funcs_run(self):
        # just tests to check functions run
        # input_vid = 'https://s3.amazonaws.com/python-vidstab/trunc_video.avi'
        input_vid = local_trunc_vid

        stabilizer = VidStab()
        stabilizer.gen_transforms(input_vid,
                                  smoothing_window=1,
                                  show_progress=True)

        self.assertEqual(stabilizer.smoothed_trajectory.shape,
                         stabilizer.trajectory.shape,
                         'trajectory/transform obj shapes')
        self.assertEqual(stabilizer.transforms.shape,
                         stabilizer.trajectory.shape,
                         'trajectory/transform obj shapes')

        with tempfile.TemporaryDirectory() as tmpdir:
            output_vid = '{}/test_output.avi'.format(tmpdir)
            try:
                stabilizer.apply_transforms(input_vid, output_vid)
            except Exception as e:
                self.fail("stabilizer.apply_transforms ran into {}".format(e))

            try:
                stabilizer.stabilize(input_vid, output_vid, smoothing_window=1)
            except Exception as e:
                self.fail("stabilizer.stabilize ran into {}".format(e))
Exemplo n.º 7
0
def test_trajectory_transform_values():
    for window in [15, 30, 60]:
        stabilizer = VidStab(processing_max_dim=float('inf'))
        stabilizer.stabilize(input_path=OSTRICH_VIDEO, output_path='stable.avi', smoothing_window=window)

        pickle_test_transforms(stabilizer, 'pickled_transforms')

        check_transforms(stabilizer, is_cv4=imutils.is_cv4())
Exemplo n.º 8
0
def test_trajectory_transform_values():
    for window in [15, 30, 60]:
        stabilizer = VidStab()
        stabilizer.gen_transforms(input_path=OSTRICH_VIDEO,
                                  smoothing_window=window)

        pickle_test_transforms(stabilizer, 'pickled_transforms')

        check_transforms(stabilizer, is_cv4=imutils.is_cv4())
Exemplo n.º 9
0
def test_writer_reset():
    path_1 = 'stable_1.avi'
    path_2 = 'stable_2.avi'
    stabilizer = VidStab()
    stabilizer.stabilize(OSTRICH_VIDEO, path_1, max_frames=16, smoothing_window=1)
    stabilizer.stabilize(OSTRICH_VIDEO, path_2, max_frames=16, smoothing_window=1)

    assert os.path.exists(path_1)
    assert os.path.exists(path_2)
Exemplo n.º 10
0
def video_stabilizer(input_video_filepath, output_video_filepath):
    # input_video_filepath = glob.glob('/home/afarahani/Projects/output/*')
    # output_video_filepath = '/home/afarahani/Projects/stab_output/'
    for video_path in input_video_filepath:
        head, tail = os.path.split(video_path)
        stabilizer = VidStab()
        # black borders
        stabilizer.stabilize(input_path=video_path, 
                             output_path=output_video_filepath+tail, 
                             border_type='black')
Exemplo n.º 11
0
 def __init__(self, camera, camera_rasp, show_image):
     self.LAT_LONG = [0.0, 0.0, 0.0, 0.0]
     self.LIMIT = 6
     self.DISTANCE = 15
     self.SIZE = 480
     self.CODE, self.READ_CODE = '', ''
     self.CAMERA = camera
     self.show_image = show_image
     self.camera_rasp = camera_rasp
     self.stabilizer = VidStab()
Exemplo n.º 12
0
def stabilize_video():
    stabilizer = VidStab()
    stabilizer.stabilize(input_path='static/Uploads/file.mp4',
                         output_path='static/Output/stable_video.avi')

    stabilizer.plot_trajectory()
    plt.savefig('static/img/plot_trajectory.png')

    stabilizer.plot_transforms()
    plt.savefig('static/img/plot_transforms.png')
    return ('________________Completed convertion_____________')
Exemplo n.º 13
0
def main(original_video_file, stabilized_video_file):

    stabilizer = VidStab()
    stabilizer.stabilize(input_path=original_video_file,
                         output_path=stabilized_video_file)

    stabilizer.plot_trajectory()
    plt.show()

    stabilizer.plot_transforms()
    plt.show()
    def run(self):
        for vid in self.vids:
            out_vid = os.path.join(self.output_path, os.path.basename(vid))
            if os.path.isfile(out_vid):
                continue

            try:
                stabilizer = VidStab()
                stabilizer.stabilize(input_path=vid, output_path=out_vid)
            except:
                print ("error in ", vid)
                shutil.copy(vid, out_vid)
    def __init__(self, directory, file_name):
        """
        Initialise variables and call the function to stabilise the specified video.
        :param directory: the directory where the video file to stabilise is located
        :param file_name: the mp4 video file's name
        """
        self.directory = directory
        self.file = file_name
        self.new_file = file_name[:-4]

        self.stabiliser = VidStab()
        self.stabilise_video()
Exemplo n.º 16
0
def test_video_dep_funcs_run():
    # just tests to check functions run
    stabilizer = VidStab()
    stabilizer.gen_transforms(TRUNCATED_OSTRICH_VIDEO, smoothing_window=2, show_progress=True)

    assert stabilizer.smoothed_trajectory.shape == stabilizer.trajectory.shape
    assert stabilizer.transforms.shape == stabilizer.trajectory.shape

    with tempfile.TemporaryDirectory() as tmpdir:
        output_vid = '{}/test_output.avi'.format(tmpdir)
        stabilizer.apply_transforms(TRUNCATED_OSTRICH_VIDEO, output_vid)
        stabilizer.stabilize(TRUNCATED_OSTRICH_VIDEO, output_vid, smoothing_window=2)
Exemplo n.º 17
0
def stabilize_video(source, video, destination_folder):
    input_video_path = source + '/' + video
    output_file_path = destination_folder + "/" + \
        os.path.basename(video).split('.')[-2] + "_stabilized.mp4"

    print("Video to be stabilized:" + input_video_path)

    stabilizer = VidStab(kp_method='FAST')
    stabilizer.stabilize(input_path=input_video_path,
                         output_path=output_file_path,
                         border_type='black')

    print("Output file is ready: " + output_file_path)
Exemplo n.º 18
0
def test_invalid_input_path():
    stabilizer = VidStab(kp_method='FAST',
                         threshold=42,
                         nonmaxSuppression=False)
    with pytest.raises(FileNotFoundError) as err:
        stabilizer.gen_transforms("fake_input_path.mp4")

    assert "fake_input_path.mp4 does not exist" in str(err.value)

    with pytest.raises(FileNotFoundError) as err:
        stabilizer.stabilize("fake_input_path.mp4", "output.avi")

    assert "fake_input_path.mp4 does not exist" in str(err.value)
def test_max_frames():
    max_frames = 16
    with tempfile.TemporaryDirectory() as tmpdir:
        output_path = '{}/stable_1.avi'.format(tmpdir)

        stabilizer = VidStab()
        stabilizer.stabilize(OSTRICH_VIDEO,
                             output_path,
                             max_frames=max_frames,
                             smoothing_window=1)

        output_frame_count = imutils.video.count_frames(output_path)
        assert max_frames == output_frame_count
def test_output_fps():
    force_fps = 10
    with tempfile.TemporaryDirectory() as tmpdir:
        output_vid = '{}/test_output.avi'.format(tmpdir)

        stabilizer = VidStab()
        stabilizer.stabilize(OSTRICH_VIDEO,
                             output_vid,
                             max_frames=16,
                             smoothing_window=1,
                             output_fps=force_fps)

        output_fps = cv2.VideoCapture(output_vid).get(cv2.CAP_PROP_FPS)
        assert force_fps == output_fps
Exemplo n.º 21
0
def test_trajectory_transform_values():
    for window in [15, 30, 60]:
        stabilizer = VidStab()
        stabilizer.gen_transforms(input_path=ostrich_video,
                                  smoothing_window=window)

        pickle_test_transforms(stabilizer, 'pickled_transforms')

        unpickled_transforms = download_pickled_transforms(
            window, cv4=imutils.is_cv4())

        assert np.allclose(stabilizer.transforms, unpickled_transforms[0])
        assert np.allclose(stabilizer.trajectory, unpickled_transforms[1])
        assert np.allclose(stabilizer.smoothed_trajectory,
                           unpickled_transforms[2])
Exemplo n.º 22
0
def test_stabilize_frame():
    # Init stabilizer and video reader
    stabilizer = VidStab(processing_max_dim=float('inf'))
    vidcap = cv2.VideoCapture(OSTRICH_VIDEO)

    window_size = 30
    while True:
        _, frame = vidcap.read()

        # Pass frame to stabilizer even if frame is None
        stabilized_frame = stabilizer.stabilize_frame(
            input_frame=frame, smoothing_window=window_size, border_size=10)

        if stabilized_frame is None:
            break

    check_transforms(stabilizer, is_cv4=imutils.is_cv4())
Exemplo n.º 23
0
def test_invalid_input_path():
    stabilizer = VidStab(kp_method='FAST', threshold=42, nonmaxSuppression=False)
    with pytest.raises(FileNotFoundError) as err:
        stabilizer.gen_transforms('fake_input_path.mp4')

    assert 'fake_input_path.mp4 does not exist' in str(err.value)

    with pytest.raises(FileNotFoundError) as err:
        stabilizer.stabilize('fake_input_path.mp4', 'output.avi')

    assert 'fake_input_path.mp4 does not exist' in str(err.value)

    with pytest.raises(ValueError) as err:
        tmp_file = tempfile.NamedTemporaryFile(suffix='.mp4')
        with pytest.warns(UserWarning, match='No progress bar will be shown'):
            stabilizer.stabilize(tmp_file.name, 'output.avi')

    assert 'First frame is None' in str(err.value)
Exemplo n.º 24
0
def lambda_handler(event, context):
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'],
                                    encoding='utf-8')

    if VIDSTAB_ERROR is not None:
        raise VIDSTAB_ERROR

    try:
        in_path = download_file(bucket, key)
        out_path = "/tmp/out_{}".format(key)
        head_response = s3.head_object(Bucket=bucket, Key=key)
        size = head_response['ContentLength']
        content_type = head_response['ContentType']
        if size <= MAX_SIZE:
            # Do the stabilization
            if content_type[0:5] == "video":
                stabilizer = VidStab(kp_method=KP_METHOD)
                if BORDER_TYPE == "black":
                    stabilizer.stabilize(input_path=in_path,
                                         output_path=out_path,
                                         border_type=BORDER_TYPE,
                                         border_size=BORDER_SIZE)
                else:
                    stabilizer.stabilize(input_path=in_path,
                                         output_path=out_path,
                                         border_type=BORDER_TYPE)
                return upload_file(OUTPUT_BUCKET, key, out_path)
            else:
                raise IOError("Object {} from bucket {} ".format(key, bucket) +
                              "is not a video.")
        else:
            raise IOError("Object {} from bucket {} ".format(key, bucket) +
                          "exceeds max allowable size for stabilization.")

    except IOError as e:
        logger.exception("IOError occurred during lambda handling")
        raise e
    except Exception as e:
        logger.exception(
            "Error processing object {} from bucket {}. ".format(key, bucket) +
            "Make sure your object and bucket exist and your bucket is in the same region as this function."
        )
        raise e
Exemplo n.º 25
0
def test_invalid_input_path():
    stabilizer = VidStab(kp_method='FAST',
                         threshold=42,
                         nonmaxSuppression=False)
    with pytest.raises(FileNotFoundError) as err:
        stabilizer.gen_transforms("fake_input_path.mp4")

    assert "fake_input_path.mp4 does not exist" in str(err.value)

    with pytest.raises(FileNotFoundError) as err:
        stabilizer.stabilize("fake_input_path.mp4", "output.avi")

    assert "fake_input_path.mp4 does not exist" in str(err.value)

    with pytest.raises(ValueError) as err:
        tmp_file = tempfile.NamedTemporaryFile(suffix=".mp4")
        stabilizer.stabilize(tmp_file.name, "output.avi")

    assert "First frame is None" in str(err.value)
def test_writer_reset():
    with tempfile.TemporaryDirectory() as tmpdir:
        path_1 = '{}/stable_1.avi'.format(tmpdir)
        path_2 = '{}/stable_2.avi'.format(tmpdir)

        stabilizer = VidStab()
        stabilizer.stabilize(OSTRICH_VIDEO,
                             path_1,
                             max_frames=16,
                             smoothing_window=1)
        stabilizer.stabilize(OSTRICH_VIDEO,
                             path_2,
                             max_frames=16,
                             smoothing_window=1)

        assert os.path.exists(path_1)
        assert os.path.exists(path_2)

        imutils.video.count_frames(path_1)
Exemplo n.º 27
0
def test_video_dep_funcs_run():
    # just tests to check functions run
    stabilizer = VidStab()
    stabilizer.gen_transforms(local_trunc_vid, smoothing_window=2, show_progress=True)

    assert stabilizer.smoothed_trajectory.shape == stabilizer.trajectory.shape
    assert stabilizer.transforms.shape == stabilizer.trajectory.shape

    with tempfile.TemporaryDirectory() as tmpdir:
        output_vid = '{}/test_output.avi'.format(tmpdir)
        try:
            stabilizer.apply_transforms(local_trunc_vid, output_vid)
        except Exception as e:
            pytest.fail("stabilizer.apply_transforms ran into {}".format(e))

        try:
            stabilizer.stabilize(local_trunc_vid, output_vid, smoothing_window=2)
        except Exception as e:
            pytest.fail("stabilizer.stabilize ran into {}".format(e))
Exemplo n.º 28
0
def vidstab(input_path,
            output_path,
            kp_method='GFTT',
            smoothing_window=30,
            border_type='black',
            border_size=0):
    # stabilizer = VidStab(kp_method='FAST', threshold=42, nonmaxSuppression=False)  # Using different parameters
    stabilizer = VidStab(kp_method=kp_method)  # Default
    stabilizer.stabilize(input_path=input_path,
                         output_path=output_path,
                         smoothing_window=smoothing_window,
                         border_type=border_type,
                         border_size=border_size)

    stabilizer.plot_trajectory()
    plt.show()

    stabilizer.plot_transforms()
    plt.show()
    return
Exemplo n.º 29
0
def test_resize():
    # Init stabilizer and video reader
    max_dim = 30
    stabilizer = VidStab(processing_max_dim=max_dim)
    assert stabilizer.processing_max_dim == max_dim

    # noinspection PyProtectedMember
    assert stabilizer._processing_resize_kwargs == {}

    vidcap = cv2.VideoCapture(OSTRICH_VIDEO)

    _, frame = vidcap.read()
    _ = stabilizer.stabilize_frame(input_frame=frame, smoothing_window=1)

    _, frame = vidcap.read()
    stabilized_frame = stabilizer.stabilize_frame(input_frame=frame, smoothing_window=1)

    assert stabilized_frame.shape == (446, 876, 3)
    assert max(stabilizer.prev_gray.shape) <= max_dim

    # noinspection PyProtectedMember
    assert stabilizer._processing_resize_kwargs == {'width': max_dim}
Exemplo n.º 30
0
def test_stabilize_frame():
    # Init stabilizer and video reader
    stabilizer = VidStab()
    vidcap = cv2.VideoCapture(ostrich_video)

    window_size = 30
    while True:
        grabbed_frame, frame = vidcap.read()

        # Pass frame to stabilizer even if frame is None
        stabilized_frame = stabilizer.stabilize_frame(
            input_frame=frame, smoothing_window=window_size, border_size=10)

        if stabilized_frame is None:
            break

    unpickled_transforms = download_pickled_transforms(window_size,
                                                       cv4=imutils.is_cv4())

    assert np.allclose(stabilizer.transforms, unpickled_transforms[0])
    assert np.allclose(stabilizer.trajectory, unpickled_transforms[1])
    assert np.allclose(stabilizer.smoothed_trajectory, unpickled_transforms[2])