有没有办法防止在 opencv 矩阵除法中四舍五入

Is there a way to prevent rounding in opencv matrix divison

本文关键字:除法 四舍五入 opencv 有没有      更新时间:2023-10-16

我有一个整数矩阵,我想对它执行整数除法。但是opencv总是对结果进行四舍五入。我知道我可以手动划分每个元素,但我想知道是否有更好的方法?

Mat c = (Mat_ <int> (1,3) << 80,71,64 );
cout << c/8 << endl;
// result
//[10, 9, 8]
// desired result
//[10, 8, 8]

与@GPPK的可选方法类似,您可以通过以下方式破解它:

Mat tmp, dst;
c.convertTo(tmp, CV_64F);
tmp = tmp / 8 - 0.5;            // simulate to prevent rounding by -0.5
tmp.convertTo(dst, CV_32S);
cout << dst;

问题是使用ints,你不能用小数点ints所以我不确定你期望如何不四舍五入。

您在这里确实有两个选择,我认为如果不使用这些选项之一,您将无法做到这一点

  1. 您有一个数学上正确的int矩阵除法[10, 9, 8]
  2. 旋转你自己的除法函数,以便给你你想要的结果。

选项 2:

伪代码:

Create a double matrix
perform the division to get the output [10.0, 8.875, 8.0]
strip away any numbers after a decimal point [10.0, 8.0, 8.0]
(optional) write these values back to a int matrix
(result) [10, 8, 8]