在c++中加速对带有指针的数组的访问
Speeding up access to a array with pointers in C++
我正在尝试快速图像阈值函数。目前我做的是:
void threshold(const cv::Mat &input, cv::Mat &output, uchar threshold) {
int rows = input.rows;
int cols = input.cols;
// cv::Mat for result
output.create(rows, cols, CV_8U);
if(input.isContinuous()) { //we have to make sure that we are dealing with a continues memory chunk
const uchar* p;
for (int r = 0; r < rows; ++r) {
p = input.ptr<uchar>(r);
for (int c = 0; c < cols; ++c) {
if(p[c] >= threshold)
//how to access output faster??
output.at<uchar>(r,c) = 255;
else
output.at<uchar>(r,c) = 0;
}
}
}
}
我知道at()
函数相当慢。我怎样才能更快地设置输出,或者换句话说,如何将我从输入到输出得到的指针联系起来?
您认为at
作为c++标准库为几个容器文档,执行范围检查并抛出越界,但这不是标准库,而是OpenCV。
根据cv::Mat::at文档:
模板方法返回对指定数组元素的引用。为了提高性能,索引范围检查只在Debug配置中执行。
所以你可能会想,没有范围检查
比较源代码中的cv::Mat::at
和cv::Mat::ptr
,我们可以看到它们几乎相同。
所以cv::Mat::ptr<>(row)和
一样昂贵return (_Tp*)(data + step.p[0] * y);
而cv::Mat::at<>(行,列)和:
一样昂贵return ((_Tp*)(data + step.p[0] * i0))[i1];
您可能希望直接使用cv::Mat::ptr
,而不是每列调用cv::Mat::at
,以避免进一步重复data + step.p[0] * i0
操作,自己执行[i1]
。
你可以这样做:
/* output.create and stuff */
const uchar* p, o;
for (int r = 0; r < rows; ++r) {
p = input.ptr<uchar>(r);
o = output.ptr<uchar>(r); // <-----
for (int c = 0; c < cols; ++c) {
if(p[c] >= threshold)
o[c] = 255;
else
o[c] = 0;
}
}
作为旁注,你不应该也不应该检查cv::Mat::isContinuous
在这里,差距是从一行到另一行,你正在采取指针到单行,所以你不需要处理矩阵差距。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空