我有一个简单的结构来表示图像的左,上,右,底部用于裁剪的百分比:
struct RoiRect {
unsigned int left;
unsigned int top;
unsigned int right;
unsigned int bottom;
bool isAllZero() {
return left == 0 && top == 0 && left == 0 && bottom == 0;
}
void getCvRect(cv::Size cvSize, cv::Rect &cvRect) {
int height = cvSize.height;
int width = cvSize.width;
int x = ((double)(left/height)*100);
int y = ((double)(top/height)*100);
int w = width - ((double)(right/width)*100);
int h = height - ((double)(bottom/width)*100);
cvRect.x = x;
cvRect.y = y;
cvRect.width = w;
cvRect.height = h;
}
};
我使用10,15,20,25之类的值初始化此结构。这意味着图像应从右侧裁剪10%,从顶部裁剪15%,依此类推。
在另一个类中,我将调用结构的getCvRect
并传入图像大小和原始cv::Rect
对象,以便上面的函数计算百分比并返回一个要裁剪的矩形图像:
//inside another function
cv::Rect rect; //rect to be calculated by getCvRect function of the struct
bool crop; //should crop or not? if all == zero then NOT!
if(!mRoiRect.isAllZero()) {
crop = true;
mRoiRect.getCvRect(mat.size(), rect);
}
但是所有的努力都是徒劳的!我传入一个大小作为第一个参数,我很确定图像大小是例如640x480 ...函数调用后的rect
对象显示640x480
...所以我的函数绝对没有。
我做错了什么,我该怎样做才能解决或更好地完成这项任务的更聪明方法?
正确的实施方式(对任何有兴趣的人)
int x = ((double) left / 100) * width;
int y = ((double) top / 100) * height;
int w = width - ((double) right / 100) * width;
int h = height - ((double) bottom / 100) * width;
答案 0 :(得分:3)
问题在于四行:
int x = ((double)(left/height)*100);
int y = ((double)(top/height)*100);
int w = width - ((double)(right/width)*100);
int h = height - ((double)(bottom/width)*100);
这里left/height
等...都使用整数除法,然后结果被转换为double。当然,效果是x
和y
以及零和w == width
以及h == height
。你打算写的很可能是
int x = ((double) left)/height*100;
int y = ((double) top)/height*100;
int w = width - ((double) right)/width*100;
int h = height - ((double) bottom)/width*100;
答案 1 :(得分:1)
我使用的示例函数可能对改进代码有用
Rect shrinkRect(Rect rect, int width_percent, int height_percent)
{
if (width_percent > 100) width_percent = 100;
if (height_percent > 100) height_percent = 100;
Rect newrect;
newrect.width = (rect.width * width_percent) / 100;
newrect.height = (rect.height * height_percent) / 100;
newrect.x = rect.x + (rect.width - newrect.width) / 2;
newrect.y = rect.y + (rect.height - newrect.height) / 2;
return newrect;
}
用法:假设您有Rect r = Rect(0,0,100,100)
你想缩小你的直率%20
Rect shrinkedRect = shrinkRect(r, 80, 80)
shrinkedRect是(10,10,80,80)
您可以为width_percent
和height_percent