Cropping and copying an image using cvSetImageROI

Firstly,OpenCv provides you many ways to initialize an IplImage.We will look at two such ways

  • cvCreateImage
  • cvCloneImage
  • cvCopy
Though these may seem very easy,but actually its very tricky .
So lets come to the usage of cvCreateImage.
IplImage *img1 ,*img2;
img1=cvCreateImage(cvSize(640,480),8, 3 );
This is similar to creation of a “canvas” in photoshop .
cvCopy()–>Copies an image from to another
cvCloneImage–>clones an image.
Details given below
now lets us assume we already have an image img and we wish to crop it a region of res “640*480”.
IplImage* img = cvLoadImage(“your path name”);
Step 1:
Set the Region of Interest.ROI is the region that you will be working.All processing done after this will only be done on the ROI.The other remaining parts of the image will be left “as-is” .
Step 2:Create a Blank canvas to copy in.
img1=cvCreateImage(cvSize(640,480),img->depth, 3 );
Use cvCreateImage(cvGetSize(img),img1->depth, 1 ); if you do not know the size of the original image
Step 3:
Now the obvious logic will be to apply “cvCopy” ,since I have already stated that all further processing will be done on the ROI.
You have successfully cropped the image.
Sometimes you don’t need to “Crop” an image.At some later point you may wish to get the original unaffected parts of an image.
Let me explain with an example
setting ROI of an image
After some processing we may think  that we need to copy the entire image to another Iplimage.One process would be to remove the ROI using
copying and then again applying the ROI.This would mean recalculating the ROI which is not at all optimal.So we have
cvCloneImage() .

Contrary to cvCopy() ,cvCloneImage() is always applied to the whole image .The entire image gets copied along with its ROI.So if we display img1 only the portion “640 *480” will be visible.At first the effect may be the same as “cropping” ,but if we use

cvResetImageROI(img2) we will get the entire image.

The code is pretty easy,inCase you want it ,you can contact me.

4 responses to “Cropping and copying an image using cvSetImageROI

  1. thats great, and appreciable work done, first time i am getting ROI very clearly, please continue your struggle, so that more people could get benefits from your effort.

  2. Hey for my final year project i need the code.moreupon i am making it on android.can you tell me if there are any function tgat can help in crop an image

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s