Ask Your Question
0

Is there a way to prevent rounding in opencv matrix divison

asked 2015-06-15 02:32:53 -0600

updated 2020-02-24 06:22:03 -0600

LBerger gravatar image

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 flag offensive close merge delete

Comments

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.

LorenaGdL gravatar imageLorenaGdL ( 2015-06-16 04:01:23 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2015-06-15 04:15:19 -0600

LBerger gravatar image

updated 2016-10-25 05:03:35 -0600

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]
}
edit flag offensive delete link more

Comments

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

LorenaGdL gravatar imageLorenaGdL ( 2015-06-16 04:02:10 -0600 )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.

LBerger gravatar imageLBerger ( 2015-06-16 08:06:08 -0600 )edit

Question Tools

2 followers

Stats

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

Seen: 994 times

Last updated: Oct 25 '16