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.
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.
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).
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 cv2import numpy as npimport os#Load the selected imageimg = cv2.imread('__ed_input.png')#Get the image shape and show its dimensionsh,w = img.shape[:2]print('Image Dimensions: height={}, width={}'.format(h, w))# Define a black maskmask = np.zeros_like(img)#Flip the mask color to whitemask[:, :] = [255, 255, 255]# Draw a black filled rectangle on top of the mask to# hide a specific areastart_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 imageresult = cv2.bitwise_and(img,mask)# save the processed image and maskoutput_path = '/usercode/output'cv2.imwrite(os.path.join(output_path,'img_masked.png'), result)
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.