How to draw a rectangle in opencv dynamically according to image width and height?

Java Player picture Java Player · May 17, 2012 · Viewed 14.3k times · Source

i want to draw a rectangle in opencv according to the image width and height (i.e. i don't want to give a static values to cvRectangle) i want to draw a rectangle which covers most of the region of any image big or small in other words i want to draw the biggest rectangle in each image,thanks

Answer

Larry Cinnabar picture Larry Cinnabar · May 17, 2012

May be, you'd like to use percentage dimensions?

IplImage *img=cvLoadImage(fileName,CV_LOAD_IMAGE_COLOR);

int imageWidth  = img->width;
int imageHeight = img->height;
int imageSize   = img->nSize;

int ratio     = 90; // our ROI will be 90% of our input image

int roiWidth  = (int)(imageWidth*ratio/100);
int roiHeight = (int)(imageHeight*ratio/100);

// offsets from image borders
int dw = (int) (imageWidth-roiWidth)/2;
int dh = (int) (imageHeight-roiHeight)/2;

cvRectangle(img,
            cvPoint(dw,dh),                     // South-West point 
            cvPoint(roiWidth+dw, roiHeight+dh), // North-East point
            cvScalar(0, 255, 0, 0), 
            1, 8, 0);

cvSetImageROI(img,cvRect(dw,dh,roiWidth,roiHeight));

So, now, If you set ratio = 90, and your input image is 1000x1000 pixels, than your ROI will be 900x900 pixels and it will be in the center of your image.