我有一个简单的结构来表示用于裁剪的图像左、上、右、下的百分比:
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;
最佳答案
问题出在四行:
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;
关于c++ - 结构中的函数不做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34980936/