如何根据图像的宽度和高度动态地在opencv中绘制一个矩形?

时间:2012-05-16 23:58:03

标签: c image-processing opencv roi

我想根据图像的宽度和高度在opencv中绘制一个矩形(即我不想给cvRectangle提供静态值)我想绘制一个覆盖大部分区域的矩形任何大或小的图像换句话说我想在每个图像中绘制最大的矩形,谢谢

2 个答案:

答案 0 :(得分:1)

可能是,您想使用百分比尺寸?

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));

所以,现在,如果你设置比率= 90,输入图像是1000x1000像素,那么你的ROI将是900x900像素,它将位于图像的中心。

答案 1 :(得分:1)

我试过了,效果很好

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)));