hetsch - 9 months ago 55

Python Question

What I want to achieve is to programmatically create a two-dimensional color ramp represented by a 256x256 matrix of color values. The expected result can be seen in the attached image. What I have for a starting point are the 4 corner colors of the matrix from which the remaining 254 colors inbetween should be interpolated. While I had some success for interpolating the colors for one axis, the two-dimensional calculation provides me some bad headaches. While the image seems to have a non-linear color gradient, I would be happy with a linear one.

If you could give me some hints how to do this with numpy or other tools I`ll be more than thankful.

Answer

Here's a super short solution using the zoom function from `scipy.ndimage`

. I define a 2x2 RGB image with the intial colors (here random ones) and simply zoom it to 256x256, `order=1`

makes the interpolation linear. Here is the code :

```
import numpy as np
import matplotlib.pyplot as plt
im=(np.random.rand(2,2,3)*255).astype(np.uint8)
from scipy.ndimage.interpolation import zoom
zoomed=zoom(im,(128,128,1),order=1)
plt.subplot(121)
plt.imshow(im,interpolation='nearest')
plt.subplot(122)
plt.imshow(zoomed,interpolation='nearest')
plt.show()
```

Output:

Source (Stackoverflow)