gpt4 book ai didi

c++ - 在opencv中划分两个矩阵

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:52 27 4
gpt4 key购买 nike

我想对两个 opencv CV_32S 矩阵(A 和 B)执行逐元素除法。

当 B 不为 0 时,我希望 C = A/B,否则为 0。

但我不确定是否理解 opencv 文档:

http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#divide

它说:

When src2(I) is zero, dst(I) will also be zero. Different channels of multi-channel arrays are processed independently.

Note Saturation is not applied when the output array has the depth CV_32S. You may even get result of an incorrect sign in the case of overflow.

saturate() 有什么作用?我可以安全地将 divide(A,B,C) 与 CV_32S 矩阵一起使用吗? divide() 与/运算符有何不同?

===== 测试后编辑 =====

我的测试表明/运算符完全符合我的要求:当 B != 0 时 C = A/B,否则为 0。

最佳答案

因此,operator/cv::divide 实际上应该是一样的,除了运算符将返回一个矩阵表达式,其计算被延迟。最后,operator/ 也会调用 cv::divide,如 e 所示。 G。对于一个简单的案例 here .特别是结果应该是相等的。

尽管如此,结果还是令人惊讶。使用两个整数矩阵进行除法,结果就像在浮点运算中完成的一样,后跟 round to nearest integer。更喜欢偶数(另见 nearbyint() )。例如,使用两个 6x6 整数矩阵,您将得到

0/0 == 0    1/0 == 0    2/0 == 0    3/0 == 0    4/0 == 0    5/0 == 0
0/1 == 0 1/1 == 1 2/1 == 2 3/1 == 3 4/1 == 4 5/1 == 5
0/2 == 0 1/2 == 0 2/2 == 1 3/2 == 2 4/2 == 2 5/2 == 2
0/3 == 0 1/3 == 0 2/3 == 1 3/3 == 1 4/3 == 1 5/3 == 2
0/4 == 0 1/4 == 0 2/4 == 0 3/4 == 1 4/4 == 1 5/4 == 1
0/5 == 0 1/5 == 0 2/5 == 0 3/5 == 1 4/5 == 1 5/5 == 1

注意 div-by-0-equals-0 (正如您在文档中所述),但也要注意 rounding (四舍五入)和tie-break-1-2同时 tie-break-3-2 (平分平局)。


注意:两个浮点类型矩阵没有定义任何特殊行为,而是在除以零的情况下计算为 -inf、nan 或 inf。当您除以两个浮点矩阵但请求整数结果时,这甚至成立。在这种情况下,-inf、nan 和 inf 将转换为最小值,这可能是一个错误(或者只是 OpenCV 未定义)。


整数除法代码div.cpp(用g++ -std=c++11 div.cpp -o div -lopencv_core编译):

#include <opencv2/opencv.hpp>
#include <iostream>
#include <cstdint>

int main() {
cv::Mat i1(6,6,CV_32S);
cv::Mat i2(6,6,CV_32S);
for (int y = 0; y < i1.rows; ++y) {
for (int x = 0; x < i1.cols; ++x) {
i1.at<int32_t>(y, x) = x;
i2.at<int32_t>(y, x) = y;
}
}

cv::Mat q;
cv::divide(i1, i2, q);
// q = i1 / i2;

for (int y = 0; y < q.rows; ++y) {
for (int x = 0; x < q.cols; ++x)
std::cout << x << "/" << y << " == " << q.at<int32_t>(y, x) << "\t";
std::cout << std::endl;
}

return 0;
}

关于c++ - 在opencv中划分两个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20975420/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com