Convex Combinations
Learn about convex combinations by implementing an interesting example of morphing.
We'll cover the following
A convex combination is simply a special case of linear combinations. In particular, for convex linear combinations:
- Each scalar is greater than .
- The sum must be equal to .
For example, for vectors and , a possible convex combination is , whereas isn’t a valid convex combination.
Formal definition
Let be a set of scalars and be a set of objects with addition and scalar multiplication (over ) defined. The linear combination is a convex combination of the objects if and .
An interesting example
Using a series of convex combinations, we can transform an
Explanation
Let’s look at how we’re able to make the transformation of images above:
Step 1: We take two equal-sized images with similar backgrounds to seamlessly transform one image into the other. These images are shown in the figure above.
Step 2: We represent those two images in matrices, say A and B.
Step 3: We create a convex combination of these matrices, such as . We know that because it’s a convex combination, the and the sum of .
Step 4: Initially, is set to zero. So, the above equation yields , which is equal to A. This can also be seen in the figure below. For , we get the first image corresponding to A.
Step 5: We slowly start to increase . Therefore, the components of the first image (which corresponds to matrix A) gradually decrease, whereas the second image’s components (matrix B) increase in equal proportions.
Step 6: We continue to display the result of our transformation until the first image is completely transformed into the second image. That is, becomes equal to 1. The figure below shows these transformations of images from to .
Do it yourself
This section provides the complete code of the example above. We invite you to change the code to your liking. For instance, you can increase or decrease the speed or number of the convex transformation steps. You can even use pictures of your friends and see them transform.
The code below generates convex combinations of and .
import numpy as npimport matplotlib.pyplot as plt# Reading the two imagesI = plt.imread('young.png')J = plt.imread('aged.png')# Selecting number of intermediate combinations and creating subplotsn = 5fig, ax = plt.subplots(1, n, figsize=(50, 25))# Generating convex combinations and plotting themfor i, alpha in zip(np.arange(n), np.linspace(0, 1, n)):im = (1-alpha)*I + alpha*Jax[i].imshow(im, cmap='bone');ax[i].axis('off')ax[i].set_title(str(np.round(alpha, 2)))
💡 Launch the app and then hit the Run button or press shift+enter inside the Jupyter notebook to execute the given code. Please wait till the output Out[1]: appears.
The application below regenerates the animation available at the start of this lesson. You can edit the code if you want to.