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

14,439

Solution 1

i have tried that and it works well

IplImage *img=cvLoadImage(fileName,CV_LOAD_IMAGE_COLOR);
             int imageWidth=img->width-150;
             int imageHeight=img->height-150;
             int imageSize=img->nSize;
             cvRectangle(img,cvPoint(imageWidth,imageHeight), cvPoint(50, 50),cvScalar(0, 255, 0, 0),1,8,0);
             cvSetImageROI(img,cvRect(50,50,(imageWidth-50),(imageHeight-50))); 

Solution 2

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.

Share:
14,439
Eslam Hamdy
Author by

Eslam Hamdy

Senior engineer with +9 years experience in java ecosystem, have one plus year experience in crafting and managing agile teams, has a passion for nature, mountain biking, swimming, traveling, tensegrity and coding.

Updated on June 04, 2022

Comments

  • Eslam Hamdy
    Eslam Hamdy almost 2 years

    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