title: Efficient blurring of image using a mask in python
body: <p>I need to blur specific areas of an image. I get the image and a mask depicting areas in the image that needs to be blurred. It works, but a bit slower than expected, given that I need to blur dozens of images.</p>
  
  <p>Here is the code I use:</p>
  
  <pre><code>def soft_blur_with_mask(image: np.ndarray, mask: np.ndarray) -&gt; np.ndarray:
      assert len(mask.shape) == 2, mask.shape
      # Create a blurred copy of the original image. This can take up to 1-2 seconds today, because the image is big (~5-10 Megapixels)
      blurred_image = cv2.GaussianBlur(image, (221, 221), sigmaX=20, sigmaY=20)
      image_height, image_width = image.shape[:2]
      mask = cv2.resize(mask.astype(np.uint8), (image_width, image_height), interpolation=cv2.INTER_NEAREST)
      # Blurring the mask itself to get a softer mask with no firm edges
      mask = cv2.GaussianBlur(mask.astype(np.float32), (11, 11), 10, 10)[:, :, None]
      mask = mask/255.0
  
      # Take the blurred image where the mask it positive, and the original image where the image is original
      return (mask * blurred_image + (1.0 - mask) * image).clip(0, 255.0).astype(np.uint8)
  </code></pre>