0

I am dealing with a problem that consists alpha blending of two images. I am using basic OpenCV functions. For every image, I create a mask using inRange and GaussianBlur. Then, I use that mask to blend two images. You can see the blend function below.

def blend(foreground, background, alpha, batch_size):
    # Convert uint8 to float
    foreground = foreground.astype(float)
    background = background.astype(float)

    # Normalize the alpha mask to keep intensity between 0 and 1
    alpha = alpha.astype(float)/255

    # Multiply the foreground with the alpha matte
    foreground = cv2.multiply(alpha, foreground)

    # Multiply the background with ( 1 - alpha )
    background = cv2.multiply(1.0 - alpha, background)

    # Add the masked foreground and background.
    outImage = cv2.add(foreground, background)

    return outImage

The mask creation function is:

def create_mask(image):
    # Convert image to int version and generate one channelled mask
    hsv_range_min = (0, 0, 0)
    hsv_range_max = (4, 4, 4)

    mask = cv2.inRange(image, hsv_range_min, hsv_range_max)
    mask = cv2.bitwise_not(mask)
    mask = cv2.GaussianBlur(mask, (0, 0), sigmaX=2, sigmaY=2, borderType = cv2.BORDER_DEFAULT)
    mask = skimage.exposure.rescale_intensity(mask, in_range=(127.5,255), out_range=(0, 255))

    # Convert mask to its three channelled equivalent
    new_mask = np.zeros_like(image)
    new_mask[:,:,0] = mask
    new_mask[:,:,1] = mask
    new_mask[:,:,2] = mask

    return new_mask

My question is how to speed up all these processes. I thought maybe I can use batch processing but it is not working as I assumed.

Thank you for your time.

nuwanda
  • 21
  • 2
  • "make it faster" doesn't work infinitely often. you need to come up with numbers that quantify the execution speed of your code. and you need to say what size of input you're working with. and you need to profile your code, meaning to time each line of program code. – Christoph Rackwitz May 09 '22 at 13:51
  • You could try using Numpy to do the blending in one step. `outImage = np.where(mask=alpha, foreground, background)` – fmw42 May 09 '22 at 15:39

0 Answers0