22

I'm very new to OpenCV (started using it two days ago), I'm trying to cut a hand image from a depth image got from Kinect, I need the hand image for gesture recognition. I have the image as a cv::Mat type. My questions are:

  1. Is there a way to convert cv::Mat to cvMat so that I can use cvGetSubRect method to get the Region of interest?
  2. Are there any methods in cv::Mat that I can use for getting the part of the image?

I wanted to use IplImage but I read somewhere that cv::Mat is the preferred way now.

Stonz2
  • 6,306
  • 4
  • 44
  • 64
vprasad
  • 1,451
  • 3
  • 13
  • 17

2 Answers2

47

You can use the overloaded function call operator on the cv::Mat:

cv::Mat img = ...;
cv::Mat subImg = img(cv::Range(0, 100), cv::Range(0, 100));

Check the OpenCV documentation for more information and for the overloaded function that takes a cv::Rect. Note that using this form of slicing creates a new matrix header, but does not copy the data.

Alessandro Jacopson
  • 18,047
  • 15
  • 98
  • 153
Michael Koval
  • 8,207
  • 5
  • 42
  • 53
  • 2
    Thanks for the answer! I tried the Range but it gave me a runtime error but the cv::Rect() worked just fine! – vprasad Jul 04 '11 at 01:49
  • Could you edit your question with the `cv::Range` code that failed? Also, please accept my answer if it was helpful. – Michael Koval Jul 04 '11 at 04:19
  • 3
    cv:Range gave me runtime error, but cv::Rect worked like a charm! thanks! – Froyo Sep 19 '12 at 17:42
  • Yes it seems to be using Rect. Check http://jayrambhia.wordpress.com/2012/09/20/roi-bounding-box-selection-of-mat-images-in-opencv/ for an example. – Fanglin Oct 23 '14 at 03:31
22

Maybe an other approach could be:

//Create the rectangle
cv::Rect roi(10, 20, 100, 50);
//Create the cv::Mat with the ROI you need, where "image" is the cv::Mat you want to extract the ROI from
cv::Mat image_roi = image(roi)

I hope this can help.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30