OpenCV掩码操作,c中的元素赋值++

2024-09-30 01:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据matB的值将mat matA的每个像素分配给某个值,我的代码是一个嵌套的for循环:

clock_t begint=clock();
for(size_t i=0; i<depthImg.rows; i++){
    for(size_t j=0; j<depthImg.cols; j++){
        datatype px=depthImg.at<datatype>(i, j);
        if(px==0)
            depthImg.at<datatype>(i, j)=lastDepthImg.at<datatype>(i, j);
    }
}
cout<<"~~~~~~~~time: "<<clock()-begint<<endl;

而640*480尺寸的垫子大约需要40~70ms。在

我可以在python numpy中使用花哨的索引轻松地完成这项工作:

^{pr2}$

这比我的手写循环要快得多。在

那么opencvc++api中有这样的操作吗?在


Tags: 代码forsize像素atrowscolsdatatype
2条回答
<>在C++代码中,在每个函数调用函数的像素中,传递两个索引,这些索引被转换成一个扁平索引,执行类似{^ }之类的操作。在

我的C++技巧大多缺乏,但是使用this作为模板,我猜你可以尝试一些类似的方法,这应该去掉大部分开销:

MatIterator_<datatype> it1 = depthImg.begin<datatype>(),
                       it1_end = depthImg.end<datatype>();
MatConstIterator_<datatype> it2 = lastDepthImg.begin<datatype>();

for(; it1 != it1_end; ++it1, ++it2) {
    if (*it1 == 0) {
        *it1 = *it2;
    }
}
<>我无法复制你的计时结果在我的机器上,你的C++代码在我的机器下运行1ms。然而,每当您有缓慢的迭代时,at<>()应该立即受到怀疑。OpenCV有一个tutorial on iterating through images,我建议这样做。在

不过,对于你描述的手术,还有更好的方法。Mat::copyTo()允许掩码操作:

lastDepthImg.copyTo(depthImg, depthImg == 0);

这比嵌套循环解决方案更快(大约是速度的2倍)和可读性。此外,它还可能受益于诸如SSE之类的硬件优化。在

相关问题 更多 >

    热门问题