简体   繁体   English

使用整数除法将cv :: Mat除以数字

[英]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: 在OpenCV中,如果cv::Mat (CV_8U)除以数字( int ),结果将四舍五入到最接近的数字,例如:

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 OpenCV整数部门:2

Normal Integer Division: 1 正常整数分部:1

It is obvious that OpenCV does not use integer division even if the type of the cv::Mat is CV_8U . 很明显,即使cv::Mat的类型是CV_8U ,OpenCV也不使用整数除法。

My questions are: 我的问题是:

  • Why? 为什么? Is not supposed for integers to be divided as integers. 不应该将整数划分为整数。 Why this strange behaviour of OpenCV? 为什么这个OpenCV的奇怪行为?
  • Can I obtain integer division without iterating pixel by pixel and dividing it? 我可以获得整数除法而无需逐像素迭代并除以它吗?

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;
    }
}

firstly : the overloaded operator for Division does the operation by converting the elements of matrix into double. 首先:Division的重载运算符通过将matrix的元素转换为double来执行操作。 it originally uses multiplication operator as: Mat / a =Mat * (1/a). 它最初使用乘法运算符:Mat / a = Mat *(1 / a)。 secondly : a very easy way exists to do this by one small for loop: 其次:通过一个小的for循环存在一种非常简单的方法:

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

The solution I used to solve it is: (depending on @Afshine answer and @Miki comment): 我用来解决它的解决方案是:(取决于@Afshine答案和@Miki评论):

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM