split 将始终复制数据,因为它正在创建新矩阵。
处理红色通道的最简单方法是使用split 和merge:
Mat3b img(10,10,Vec3b(1,2,3));
vector<Mat1b> planes;
split(img, planes);
// Work on red plane
planes[2](2,3) = 5;
merge(planes, img);
请注意,merge 不会分配任何新内存,因此如果您对 split 没问题,那么没有任何理由不调用 merge。
您始终可以直接在 R 通道上工作:
Mat3b img(10,10,Vec3b(1,2,3));
// Work on red channel, [2]
img(2,3)[2] = 5;
如果要节省split使用的内存,可以直接在红色通道上工作,但是比较麻烦:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat3b img(10,10,Vec3b(1,2,3));
// Create a column matrix header with red plane unwound
// No copies here
Mat1b R = img.reshape(1, img.rows*img.cols).colRange(2, 3);
// Work on red plane
int r = 2;
int c = 3;
// You need to access by index, not by (row, col).
// This will also modify img
R(img.rows * r + c) = 5;
return 0;
}
您可以通过仅将红色通道复制到新矩阵中来找到一个很好的折衷方案(避免也为其他通道分配空间),然后将结果复制回原始图像:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat3b img(10,10,Vec3b(1,2,3));
// Allocate space only for red channel
Mat1b R(img.rows, img.cols);
for (int r=0; r<img.rows; ++r)
for(int c=0; c<img.cols; ++c)
R(r, c) = img(r, c)[2];
// Work on red plane
R(2,3) = 5;
// Copy back into img
for (int r = 0; r<img.rows; ++r)
for (int c = 0; c<img.cols; ++c)
img(r, c)[2] = R(r,c);
return 0;
}
感谢@sturkmen 审核答案