Humam Helfawi
Humam Helfawi

Reputation: 20264

Dividing cv::Mat by a number using integer division

In OpenCV if cv::Mat (CV_8U) was divided by a number (int) the result will be rounded to the nearest number for example:

cv::Mat temp(1, 1, CV_8UC1, cv::Scalar(5));
temp /= 3;
std::cout <<"OpenCV Integer Division:" << temp;
std::cout << "\nNormal Integer Division:" << 5 / 3;

The result is:

OpenCV Integer Division: 2

Normal Integer Division: 1

It is obvious that OpenCV does not use integer division even if the type of the cv::Mat is CV_8U.

My questions are:

My current solution is:

for (size_t r = 0; r < temp.rows; r++){
    auto row_ptr = temp.ptr<uchar>(r);
    for (size_t c = 0; c < temp.cols; c++){
        row_ptr[c] /= 3;
    }
}

Upvotes: 4

Views: 2234

Answers (2)

Humam Helfawi
Humam Helfawi

Reputation: 20264

The solution I used to solve it is: (depending on @Afshine answer and @Miki comment):

if (frame.isContinuous()){
    for(int i = 0; i < frame.total(); i++){
       frame.data[i]/=3;
    }
}
else{
    for (size_t r = 0; r < frame.rows; r++){
        auto row_ptr = frame.ptr<uchar>(r);
        for (size_t c = 0; c < 3 * frame.cols; c++){
            row_ptr[c] /= 3;
        }
    }
}

Upvotes: 0

Afshin
Afshin

Reputation: 392

firstly : the overloaded operator for Division does the operation by converting the elements of matrix into double. it originally uses multiplication operator as: Mat / a =Mat * (1/a). secondly : a very easy way exists to do this by one small for loop:

   for(int i=0;i<temp.total();i++)
        ((unsigned char*)temp.data)[i]/=3;

Upvotes: 1

Related Questions