如何编辑/读取OpenCv中的像素值从Mat变量? [英] How to edit/read pixel values in OpenCv from Mat variable?
问题描述
我在寻找一种用于从Mat(或Mat3b)变量编辑/读取像素的有效方法。
I am looking for an efficient way for editing/reading pixels from Mat (or Mat3b) variable.
我使用过: -
Image.at<Vec3b>(i,j)
但似乎很慢。
我也用这个: -
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.
推荐答案
这里你可以看到快速元素访问的一些可能性。
Here you 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 this you should rather use a formula like 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;
}
}
这篇关于如何编辑/读取OpenCv中的像素值从Mat变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!