opencvopencv-mat

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

  • 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