Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blur content from a rectangle with Opencv

in the following rectangle function, rectangles are drawn.

// Draw the predicted bounding box
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
    //Draw a rectangle displaying the bounding box
    rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50),LINE_4);

    //bluring region
    cout << frame; 

    //Get the label for the class name and its confidence
    string label = format("%.2f", conf);
    if (!classes.empty())
    {
        CV_Assert(classId < (int)classes.size());
        label = classes[classId] + ":" + label;
    }

    //Display the label at the top of the bounding box
    int baseLine;
    Size labelSize = getTextSize(label, FONT_ITALIC, 0.5, 1, &baseLine);
    top = max(top, labelSize.height);
    putText(frame, label, Point(left, top), FONT_ITALIC, 0.5, Scalar(255, 255, 255), 1);
}

frame here is a multi-array of the image. Point(left, top) is the top-left point of the rectangle.
I would like to censor everything in this rectangle in the form of a blur. Since I come from Python programming, it is a bit difficult to define the array of these rectangles. It would be very nice if you could help me. Thank you very much and best regards.

like image 347
deptrai Avatar asked Sep 30 '19 08:09

deptrai


1 Answers

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!

like image 98
HansHirse Avatar answered Oct 01 '22 18:10

HansHirse