C++ 如何从 Mat 变量编辑/读取 OpenCv 中的像素值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9974946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to edit/read pixel values in OpenCv from Mat variable?
提问by Ravi Upadhyay
I am looking for an efficient way for editing/reading pixels from Mat (or Mat3b) variable.
我正在寻找一种从 Mat(或 Mat3b)变量编辑/读取像素的有效方法。
I have used :-
我用过了 :-
Image.at<Vec3b>(i,j)
but it seems to be very slow.
但它似乎很慢。
I also used this:-
我也用过这个:-
A.data[A.channels()*A.cols*i + j + 0]
but the problem I am facing with this is when I run this loop
但我面临的问题是当我运行这个循环时
for(i=0; j<A.rows; i++){
for(j=0; j<A.cols; j++){
A.data[A.channels()*A.cols*i + j + 0] = 0;
A.data[A.channels()*A.cols*i + j + 1] = 0;
A.data[A.channels()*A.cols*i + j + 2] = 0;
}
}
only a portion of image is blackened.
只有一部分图像变黑。
回答by sietschie
Hereyou can see some of the possibilities for fast element access.
在这里,您可以看到快速元素访问的一些可能性。
But if you want to do it your way, you need to add a bracket. Otherwise you index computation is not correct:
但是,如果您想按照自己的方式进行操作,则需要添加一个括号。否则你的索引计算不正确:
for(int i=0; i<A.rows; i++){
for(int j=0; j<A.cols; j++){
A.data[A.channels()*(A.cols*i + j) + 0] = 0;
A.data[A.channels()*(A.cols*i + j) + 1] = 0;
A.data[A.channels()*(A.cols*i + j) + 2] = 0;
}
}
But the layout of the memory is not guaranteed to be contiguous due to padding. So according to thisyou should rather use a formula like this:
但是由于填充的原因,不能保证内存的布局是连续的。所以根据this你应该使用这样的公式:
for(int i=0; i<A.rows; i++){
for(int j=0; j<A.cols; j++){
A.data[A.step[0]*i + A.step[1]* j + 0] = 0;
A.data[A.step[0]*i + A.step[1]* j + 1] = 0;
A.data[A.step[0]*i + A.step[1]* j + 2] = 0;
}
}
回答by Eric
This is one of the most efficient way for editing/reading pixels from cv::Mat. Create pointer to a row (of specific channel if needed)
这是从 cv::Mat 编辑/读取像素的最有效方法之一。创建指向行(如果需要,特定通道)的指针
for(int i=0; i<A.rows;i++){
uchar* rowi = A.ptr/*<uchar>*/(i);
for(int j=0; j<A.cols; j++){
doProcessOnPixel(rowi[j]);
}
}