justinzane
justinzane

Reputation: 1987

c++ OpenCV How to apply filter to sub rect of Mat?

This question is similar, but never was answered: OpenCV filtering part of an image

I'm using opencv2 and c++. I have a Mat, say 300x200, and I want to blur only the area in the rectangle with top-left = 50,50 size=100,50. I've been wading through the example and docs on opencv.org, but I cannot determine how to filter, or perform other operations on only a sub-rect from a Mat.

Code in question is below, where surf is an SDL_Surface and rect is an SDL_Rect (int x,y,w,h). The line with the creation of Mat src_mat from the surface is fine as it works well elsewhere. This compiles, but gives the following error.

{ // Extra scoping used for the surface_lock.
    using namespace cv;
    surface_lock surf_lock(surf);

    //int rows, int cols, int type, void* data, size_t step=AUTO_STEP
    Mat src_mat = Mat(surf->h, surf->w, CV_8UC4, src->pixels, Mat::AUTO_STEP);
    Mat cropmat(src_mat, Rect(rect.y, rect.y + rect.h, rect.x, rect.x + rect.w));

    blur(crop_mat, crop_mat, Size((depth + 1), (depth + 1)), Point(-1,-1));
}

error:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /build/opencv/src/opencv-2.4.6.1/modules/core/src/matrix.cpp, line 323
terminate called after throwing an instance of 'cv::Exception'
  what():  /build/opencv/src/opencv-2.4.6.1/modules/core/src/matrix.cpp:323: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat

Upvotes: 1

Views: 6352

Answers (1)

berak
berak

Reputation: 39796

a subrect is a Mat, too.

Mat larger; 
Mat roi(larger, Rect(50,50,100,50));

// apply whatever algo on 'roi'
blur( roi,roi, cv::Size(5,5) );

Upvotes: 3

Related Questions