Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking out a specific region in OpenCV Python

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. enter image description here

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.

enter image description here

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- enter image description here

Is there any way of getting the right result for the blue ROI?

like image 258
Sourav Avatar asked Dec 29 '25 14:12

Sourav


1 Answers

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. enter image description here

like image 163
Sourav Avatar answered Jan 02 '26 10:01

Sourav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!