I have an image of a cow farm. In the image, there are two regions of interest (ROI). Out of each ROI, I want everything to be black.

The coordinates of each corner of the ROIs are -
1= [0, 1440]
2= [0, 1087]
3= [977, 80]
4= [1925, 67]
5= [2560, 800]
6= [2560, 1440]
7= [1465, 1440]
8= [1455,60]
I am using the following codes to mask out the red region and make everything black out of the ROI.
import cv2, numpy as np
original_frame = cv2.imread("original.jpg")
frame = original_frame.copy()
# pts - location of the corners of the roi
pts = np.array([[0, 1450], [0, 1087], [977, 80], [1925, 67], [2560, 800], [2560, 1440]])
(x,y,w,h) = cv2.boundingRect(pts)
pts = pts - pts.min(axis=0)
mask = np.zeros(original_frame.shape, np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
result = cv2.bitwise_and(original_frame, mask)
cv2.imwrite("out.jpg", result)
The result is quite good but still covers some extra region on the top.

If I try to mask out blue region by changing the
pts = np.array([[1455,60], [1925, 67], [2560, 800], [2560, 1440],[1465, 1440] ])
I am getting a completely wrong result-

Is there any way of getting the right result for the blue ROI?
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. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With