How to crop a CvMat in OpenCV?
I have an image converted in a CvMat
Matrix say CVMat source
. Once I get a region of interest from source
I want the rest of the algorithm to be applied to that region of interest only. For that I think I will have to somehow crop the source
matrix which I am unable to do so. Is there a method or a function that could crop a CvMat
Matrix and return another cropped CvMat
matrix? thanks.
Solution 1:
OpenCV has region of interest functions which you may find useful. If you are using the cv::Mat
then you could use something like the following.
// You mention that you start with a CVMat* imagesource
CVMat * imagesource;
// Transform it into the C++ cv::Mat format
cv::Mat image(imagesource);
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedImage = image(myROI);
Documentation for extracting sub image
Solution 2:
I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-
Mat cropedImage = fullImage(Rect(X,Y,Width,Height));
Solution 3:
To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :
cv::Mat source = getYourSource();
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);
cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);