November 27, 2022

Masking out a specific region in OpenCV Python

I was making the whole process complex. There is a very straight forward and simple answer.

import numpy as np
import cv2
import matplotlib.pyplot as plt

# create a polygons using all outer corners of the ROI
external_poly = np.array( [[[1458,1440],[0,1440],[0,0],[2560,0],[2560,740], [1940,60], [1453,60]]], dtype=np.int32 )
im = cv2.imread("original.png", 1)
cv2.fillPoly( im , external_poly, (0,0,0) )
cv2.imwrite("output.jpg", im) 

This method creates a polygon that takes everything outside ROI and fills the polygon with black color.

Leave a Reply

Your email address will not be published. Required fields are marked *