Blur content from a rectangle with Opencv

The way to go is setting up a corresponding region of interest (ROI) by using cv::Rect. Since you already have your top left and bottom right locations as cv::Points, you get this more or less for free. Afterwards, just use - for example - cv::GaussianBlur only on that ROI. Using the C++ API, this approach works for a lot of OpenCV methods.

The code is quite simple, see the following snippet:

// (Just use your frame instead.)
cv::Mat image = cv::imread("path/to/your/image.png");

// Top left and bottom right cv::Points are already defined.
cv::Point topLeft = cv::Point(60, 40);
cv::Point bottomRight = cv::Point(340, 120);

// Set up proper region of interest (ROI) using a cv::Rect from the two cv::Points.
cv::Rect roi = cv::Rect(topLeft, bottomRight);

// Only blur image within ROI.
cv::GaussianBlur(image(roi), image(roi), cv::Size(51, 51), 0);

For some exemplary input like this

Input

the above code generates the following output:

Output

Hope that helps!


Here is the Python equivalent to @HansHirse's answer. The idea is the same except we use Numpy slicing to obtain the ROI

import cv2

# Read in image
image = cv2.imread('1.png')

# Create ROI coordinates
topLeft = (60, 40)
bottomRight = (340, 120)
x, y = topLeft[0], topLeft[1]
w, h = bottomRight[0] - topLeft[0], bottomRight[1] - topLeft[1]

# Grab ROI with Numpy slicing and blur
ROI = image[y:y+h, x:x+w]
blur = cv2.GaussianBlur(ROI, (51,51), 0) 

# Insert ROI back into image
image[y:y+h, x:x+w] = blur

cv2.imshow('blur', blur)
cv2.imshow('image', image)
cv2.waitKey()

Tags:

C++

Arrays

Opencv