# Is there a way to prevent rounding in opencv matrix divison

I have an integer matrix and I want to perform an integer division on it. But opencv always rounds the result. I know I can divide each element manually but I want to know is there a better way for this or not?

Mat c = (Mat_ <int> (1,3) << 80,71,64 );
cout << c/8 << endl;

// result
//[10, 9, 8]

// desired result
//[10, 8, 8]

edit retag close merge delete

Don't use integers to perform division. Instead, convert your Mat to another type such as double or float, perform division and then re-convert to integer (is you need integers at the end) through operations like round, ceil or floor.

( 2015-06-16 04:01:23 -0500 )edit

Sort by ยป oldest newest most voted

May be you can use divide

class EuclideanDivision{
int q;
public :
EuclideanDivision(int x){q=x;};
void operator ()(int &pixel, const int * position) const {
pixel = pixel/q;}
};

void main(void)
{
Mat c = (Mat_ <int>(1, 3) << 80, 71, 64);
Mat d=c.clone();
d.forEach<int>(EuclideanDivision(8));
cout << "result using c/8 "<<c / 8 << endl;
cout << "result using forEach "<<d << endl;
// result
//[10, 9, 8]
// desired result
//[10, 8, 8]
}

more

I don't think that solves the rounding problem working with ints

( 2015-06-16 04:02:10 -0500 )edit

You are right. That's solve nothing! I am lucky I have written may be

Mat c = (Mat_ <int> (1,3) << 80,71,64 );
Mat d;
cout<<"c/8="<<c/8<<endl;
divide(c,8.0,d,1,-1);
cout << "divide(c,8.0,d,1,-1) d="<<d << endl;
cout<<"saturate_cast<int>(71/8 ="<<saturate_cast<int>(71/8)<<endl;
divide(c,8,d,1,CV_32F);
Mat e;
d.convertTo(e,CV_16S);;
cout <<"divide(c,8,d,1,CV_32F); d.convertTo(e,CV_16S);"<<e<<endl;


So except a loop I don't know an opencv answer.

( 2015-06-16 08:06:08 -0500 )edit

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2015-06-15 02:32:53 -0500

Seen: 815 times

Last updated: Oct 25 '16