How to blackout a specific area in an image using OpenCV

OpenCV is a free, open-source, cross-platform, C++ library for image processing and computer vision with Python and Java bindings. It incorporates many inbuilt functions to execute tasks like face detection, object tracking, landmark detection, and much more.

Blackout specific part of an image

It is extremely important to censor sensitive information or black out unwanted areas of your photos or screenshots before confidently sharing them. It helps avoid the challenges brought on by improperly disclosing private information.

Application

Let’s walk through some of the most useful applications of this feature:

  • Hiding the number plate of a car in a photo.

  • Masking unbidden people from selfies.

  • Redacting private information like SSN or credit card number in a scanned document.

Note: It is always cautious to protect certain types of information like Protected Health Information (PHI) or any type of Personal Identifying Information (PII).

Example

Take an example where we need to blackout the middle area of an image.

We can achieve this by creating a white-filled image, the same as the input, with a black-filled rectangle on it as a mask to blackout the specific area of an image. Executing bitwise AND operation on the mask and the input image will give us the image with the middle part as blackout.

Let’s implement the code to blackout the middle area of the input image.

import cv2
import numpy as np
import os
#Load the selected image
img = cv2.imread('__ed_input.png')
#Get the image shape and show its dimensions
h,w = img.shape[:2]
print('Image Dimensions: height={}, width={}'.format(h, w))
# Define a black mask
mask = np.zeros_like(img)
#Flip the mask color to white
mask[:, :] = [255, 255, 255]
# Draw a black filled rectangle on top of the mask to
# hide a specific area
start_point = ((w//2),(h//2))
end_point = ((w//2 + 100),(h//2 + 100))
color = (0,0,0)
mask = cv2.rectangle(mask, start_point, end_point, color, -1)
#mask = 1 - mask
# Apply the mask to image
result = cv2.bitwise_and(img,mask)
# save the processed image and mask
output_path = '/usercode/output'
cv2.imwrite(os.path.join(output_path,'img_masked.png'), result)

Explanation

  • Lines 1–3: We import the required Python libraries.

  • Line 12: We created a black mask filled with zeros having the same shape and type as the input image.

  • Lines 14–21: We flipped the mask color to white and draw a black-filled area on the mask.

  • Line 24: We executed a bitwise_and operation on the mask and input image to filter out the relevant image part to be displayed.

  • Lines 27–28: We used the cv2.imwrite() function to display the resulting processed image.

Free Resources