This function performs the Horn-Schunck algorithm and returns the estimated optical flow. It is assumed that the input images are grayscale and normalized to be in [0, 1]. Parameters: image0: First image of the sequence image1: Second image of the sequence a
(
image0: np.ndarray,
image1: np.ndarray,
num_iter: SupportsIndex,
alpha: float | None = None,
)
| 59 | |
| 60 | |
| 61 | def horn_schunck( |
| 62 | image0: np.ndarray, |
| 63 | image1: np.ndarray, |
| 64 | num_iter: SupportsIndex, |
| 65 | alpha: float | None = None, |
| 66 | ) -> tuple[np.ndarray, np.ndarray]: |
| 67 | """ |
| 68 | This function performs the Horn-Schunck algorithm and returns the estimated |
| 69 | optical flow. It is assumed that the input images are grayscale and |
| 70 | normalized to be in [0, 1]. |
| 71 | |
| 72 | Parameters: |
| 73 | image0: First image of the sequence |
| 74 | image1: Second image of the sequence |
| 75 | alpha: Regularization constant |
| 76 | num_iter: Number of iterations performed |
| 77 | |
| 78 | Returns: estimated horizontal & vertical flow |
| 79 | |
| 80 | >>> np.round(horn_schunck(np.array([[0, 0, 2], [0, 0, 2]]), \ |
| 81 | np.array([[0, 2, 0], [0, 2, 0]]), alpha=0.1, num_iter=110)).\ |
| 82 | astype(np.int32) |
| 83 | array([[[ 0, -1, -1], |
| 84 | [ 0, -1, -1]], |
| 85 | <BLANKLINE> |
| 86 | [[ 0, 0, 0], |
| 87 | [ 0, 0, 0]]], dtype=int32) |
| 88 | """ |
| 89 | if alpha is None: |
| 90 | alpha = 0.1 |
| 91 | |
| 92 | # Initialize flow |
| 93 | horizontal_flow = np.zeros_like(image0) |
| 94 | vertical_flow = np.zeros_like(image0) |
| 95 | |
| 96 | # Prepare kernels for the calculation of the derivatives and the average velocity |
| 97 | kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25 |
| 98 | kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25 |
| 99 | kernel_t = np.array([[1, 1], [1, 1]]) * 0.25 |
| 100 | kernel_laplacian = np.array( |
| 101 | [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] |
| 102 | ) |
| 103 | |
| 104 | # Iteratively refine the flow |
| 105 | for _ in range(num_iter): |
| 106 | warped_image = warp(image0, horizontal_flow, vertical_flow) |
| 107 | derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x) |
| 108 | derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y) |
| 109 | derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t) |
| 110 | |
| 111 | avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian) |
| 112 | avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian) |
| 113 | |
| 114 | # This updates the flow as proposed in the paper (Step 12) |
| 115 | update = ( |
| 116 | derivative_x * avg_horizontal_velocity |
| 117 | + derivative_y * avg_vertical_velocity |
| 118 | + derivative_t |