c++ - 结构中的函数不做任何事情

标签 c++ opencv pointers struct

我有一个简单的结构来表示用于裁剪的图像左、上、右、下的百分比:

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 。当然,效果是 xy 以及都为零和 w == widthh == 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/

相关文章:

c++ - 添加选项以显示百分比时生成文件问题

python - 将 RGB 中的随机颜色分配到图像中

OpenCV垫CV_32FC1

python - 我无法让 OpenCV 中的 CV2.waitKey 正常工作。运行 waitKey 后代码没有响应

c++ - 检查两个 QSharedPointer 是否具有相同的数据

取消引用指向结构 vector 的指针时的c++段错误

c++ - 为什么 ValueType 的 std::any & operator= 不是有条件的 noexcept?

c++ - 为什么 'auto' 不尊重一元减号运算符?

c++ - C++中使用指针调用函数

c++ - 使用头文件中包含的函数时 undefined reference