How to crop data from multi-dimensional(dims>2) mat?

Cropping from a normal-image(dims=2) can be easily used as follows:
Mat res=img(Rect(x,y,w,h))
But how to crop data from Mat (dism>2) which if from the output of net.forward() ?


This network is a segmentation network,I don’t know how to provide this network here.
But its output output dimension of this network is 4, which can be simulated in other ways:

cv::Mat img = cv::Mat::zeros(cv::Size(224, 224), CV_8UC3);
cv::Mat output;
cv::dnn::blobFromImage(img, output, 1 / 255.0, cv::Size(224, 224), cv::Scalar(0, 0, 0), true, false);
Rect crop_roi(20,20,40,40)
// cv::Mat res=output(crop_roi); //error crop way
//OpenCV(4.5.0) Error: Assertion failed (m.dims <= 2) in cv::Mat::Mat, file D:\opencv\ocv4.5.0\sources\modules\core\src\matrix.cpp, line 468

I can crop it easy by Python whih Numpy,but I don’t know how to do it with cpp.

1 Like

like that, except you pass a vector of Range objects

https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html#aa9bf4fcbb6e854a6db7b7254a205fac9

also note: there’s a cv::dnn::_Range too, which might be of interest to you: OpenCV: cv::dnn::_Range Struct Reference

1 Like

Thanks a lot, it worked!
At the same time, if needs clone() after range-crop. Otherwise, when you perform some operations on mat, you will get a memory non-continuous error.

cv::Mat img = cv::Mat::zeros(cv::Size(224, 224), CV_8UC3);
cv::Mat output;
cv::dnn::blobFromImage(img, output, 1 / 255.0, cv::Size(224, 224), cv::Scalar(0, 0, 0), true, false);
std::vector<Range> roi_rangs;
roi_rangs.push_back(Range(0, 1));
roi_rangs.push_back(Range::all());
roi_rangs.push_back(Range(y, y+h));  //row-major
roi_rangs.push_back(Range(x,x+w));
cv::Mat res= output(roi_rangs).clone(); //need clone

1 Like