srina
srina

Reputation: 31

How to crop an Image using CvRect in Open CV.

I want to crop an image of 1176*640 to save the ROI of 1176*400 size. I am using the following snippet to acheive bit I am still getting the original image as output.

IplImage *CMyFunction::ROI(IplImage *pImage, CvRect ROI)
{
   IplImage *mROI = cvCreateImage(cvGetSize(*pImage), IPL_DEPTH_8U, 1);
   cvSetImageROI(pImage, rect_ROI); 
   cvCopy(pImage, mROI);
   cvResetImageROI(pImage);
   return mROI;
}

Upvotes: 2

Views: 851

Answers (2)

srina
srina

Reputation: 31

I understood that the pointer when leaves the function is no longer stable and declared a new IplImage* outside of the function and pass it as a parameter which proved to be efficient.

IplImage *CMyFunction::ROI(IplImage *pImage, CvRect ROI, IplImage* FinalImage)

Upvotes: 1

Haris
Haris

Reputation: 14053

For cvCopy() the source and destination should be same size and type, that is the parameter like width, height, depth, and number of channel should be equal for both image. In your case you can change your code either like

   IplImage *mROI = cvCreateImage(cvGetSize(pImage), pImage->depth, pImage->nChannels); //create dest with same size as source
   cvSetImageROI(pImage, rect_ROI); //Set roi on source
   cvSetImageROI(mROI, rect_ROI);  //set roi on dest
   cvCopy(pImage, mROI); 
   cvResetImageROI(pImage);
   cvResetImageROI(mROI);

or

IplImage *mROI = cvCreateImage(cvSize(rect_ROI.width,rect_ROI.height), pImage->depth, pImage->nChannels); // create an image of size as rect
cvSetImageROI(pImage, rect_ROI); //set roi on source
cvCopy(pImage, mROI);
cvResetImageROI(pImage);

Upvotes: 1

Related Questions