Sunday, October 28, 2007

OpenCV: get a sub image

IplImage* Sub_Image(IplImage *image, CvRect roi)
{
IplImage *result;
// set ROI, you may use following two funs:
//cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));

cvSetImageROI(image,roi);
// sub-image
result = cvCreateImage( cvSize(roi.width, roi.height), image->depth, image->nChannels );
cvCopy(image,result);
cvResetImageROI(image); // release image ROI
return result;
}

7 comments:

  1. Anonymous5:40 AM

    It's very intersting, but you can use more simple code such as:

    IplImage* src;
    IplImage* dst;
    cvRect rect;
    ...
    CvMat* mat = cvGetSubRect( (CvMat*)src, (CvMat*)dst, rect);

    OMA

    ReplyDelete
  2. Anonymous12:59 AM

    tq for both of you. I really need this code for my program.

    ReplyDelete
  3. Anonymous8:58 AM

    Be carefull! With the 2nd version there can happen some problems.

    I recoginzed some problems with accessing elements directly via image->imageData[]. I haven't explored what realy happens, but the some strange things happend.
    Version 1 works without problems.

    ReplyDelete
  4. Anonymous6:55 AM

    That's true, I had problems using the simplified version. Functions like cvClone Image will complain about images generated in that way. The other version worked very good!

    Thanks !

    ReplyDelete
  5. the second version (cvGetSubRect) does not allocate memory or copy any data like the first version. rather just sets up the header.

    ReplyDelete