i am trying to blend two "figures" in form of numpy nd arrays of dimensions (2000,2000,4) with RGBA colorcoding together. I implemented a smooth blending around a threshold value of one of the arrays. Now i need to improve the runtime of this code, since it should picture a live-view of two cameras. Does anybody has a suggestion how i could make this code faster? An example code is shown here:
import numpy as np
import matplotlib
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from time import time
import matplotlib.pyplot as plt
def generate_alpha_map(image: np.ndarray, threshold: float):
"""
generates an alpha map in the range of 20% above the threshold. The map has the same size as the
input image, all values below the threshold are 0, the 20% above the threshold are linear
interpolated on basis of the image values and everything above threshold + 20% is 1.
:param np.ndarray image: Signal image with values [0,1]
:param float threshold: Lower edge cutoff value [0,1]
:return np.ndarray: 2d map with 0 for all elements below cutoff, 1 for all elements above
threshold+0.2 and linear interpolation on basis of the measured data inbetween
"""
alpha = np.zeros_like(image, dtype=np.float)
alpha_mask = np.logical_and(image >= (1-threshold), image <= (1-threshold)+0.2)
alpha[alpha_mask] = np.interp(image[alpha_mask], ((1-threshold), (1-threshold)+0.2), (0, 1))
alpha[image > (1-threshold)+0.2] = 1
alpha[image < (1-threshold)] = 0
return alpha
cmap_1 = matplotlib.cm.get_cmap('Spectral')
cmap_2 = matplotlib.cm.get_cmap('jet')
colormap_threshold = 0.8
image1 = np.random.rand(2000,2000)
image2 = np.random.rand(2000,2000)
t0=time()
x, y = image2.shape
raw = np.ones([x, y, 4])
alpha = np.zeros_like(image2, dtype=np.float)
# Calculation of alpha map and smooth blending
alpha = generate_alpha_map(image2, colormap_threshold)
raw = cmap_1(image1) * (1-alpha[:, :, None]) \
+ cmap_2(image2) * (alpha[:, :, None])
t1=time()
print(t1-t0)
I tried to prevent using the matplotlib cmaps and calculate the three RGB colorchannels individually by a direct look-up-table. However, this results in the same runtime.