如何在openCV中修改部分多维矩阵
How to modify part of the multi-dimensional matrix in openCV?
我想使用openCV修改多维矩阵的一部分。基本上我想实现与在Matlab中编写的相同:
A = zeros(5,5,25);
A(:,:,1) = some_matrix1;
A(:,:,2) = some_matrix2;
我不确定我是否应该使用具有25通道的5x5矩阵或具有单通道的5x5x25矩阵。下面是我的尝试:
int dim[3] = { 5,5,25 };
Mat A(3, dim, CV_32FC(1), Scalar::all(0));
A(Range::all(),Range::all(),0) = some_matrix;
但是我似乎只能在两个维度上使用Range。或者
Mat A(5, 5, CV_32FC(25), Scalar::all(0));
A(Range::all(),Range::all())[0] = some_matrix;
但是在这种情况下,我不知道如何访问通道。你能帮我一下吗?
OpenCV针对2D矩阵进行了优化。多维矩阵将工作,但相当低效和难以访问。
这个示例代码将向您展示如何从3D矩阵中写入和读取值:
#include <opencv2opencv.hpp>
using namespace cv;
int main()
{
int sizes[] = { 5, 5, 25 };
Mat data(3, sizes, CV_32F);
Mat1f some_matrix(sizes[0], sizes[1]);
randu(some_matrix, 0.f, 100.f); // some random values
// Init data with each plane a constant increasing value
for (int z = 0; z < data.size[2]; ++z)
{
// Set each z-plane to some scalar value
Range ranges[] = { Range::all(), Range::all(), Range(z, z + 1) };
data(ranges) = data.size[2] - z;
}
// Set the n-th z-plane to some_matrix
int z = 0;
for (int r = 0; r < sizes[0]; ++r)
{
for (int c = 0; c < sizes[1]; ++c)
{
data.at<float>(r, c, z) = some_matrix(r, c);
}
}
// Access all slices along z dimension
for (int z = 0; z < data.size[2]; ++z)
{
Range ranges[] = { Range::all(), Range::all(), Range(z, z + 1) };
Mat slice3d(data(ranges).clone()); // with clone slice is continuous, but still 3d
Mat slice(2, &data.size[0], data.type(), slice3d.data);
}
return 0;
}
然而,将5x5x25 3D矩阵存储为std::vector<Mat>
更容易和实用,其中vector
的长度为25,并且每个矩阵都是2D 5x5。
查看代码:
#include <opencv2opencv.hpp>
using namespace cv;
int main()
{
int sizes[] = { 5, 5, 25 };
vector<Mat> data(sizes[2]);
// Init data with each plane a constant increasing value
for (int z = 0; z < sizes[2]; ++z)
{
data[z] = Mat(sizes[0], sizes[1], CV_32F, float(sizes[2] - z));
}
Mat1f some_matrix(sizes[0], sizes[1]);
randu(some_matrix, 0.f, 100.f); // some random values
// Set the n-th z-plane to some_matrix
int z = 0;
data[z] = some_matrix;
return 0;
}
这段代码可以从通道访问像素,您可以尝试一下。
int dim[3] = { 5,5,25 };
Mat A(3, dim, CV_32FC1, Scalar::all(0));
for (int m = 0; m < 5; m++)
{
for (int n = 0; n < 5; n++)
{
for (int a = 0; a < 25; a++) // no of channels
{
cout << A.at<cv::Vec3f>(m,n)[a] << endl;
}
}
}
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有没有办法修改'operator->',以便'z->im'返回复数的虚部
- FFTW和OpenCV的C++接口,Mat输出中的实部和虚部
- cv::findContours 正在修改源图像 OpenCV 2.3
- 如何在 openCV 中修改 cv::Mat 的像素数据
- OpenCV检测手部和比较图像
- 修改OpenCV随机树分类器
- OpenCV:如何修改OpenCV的一个组件
- 使用 OpenCV 修改图像时 RGB 值错误
- 我需要修改 Sobel 内核以进行对角线边缘检测.OpenCV和C++
- 如何使用 opencv c++ 从手部轮廓中提取 LBP 特征
- 如何索引和修改OpenCV矩阵
- 使用OpenCV进行手部检测
- 如何在openCV中修改部分多维矩阵
- OpenCV手部检测
- OpenCV手部识别
- 使用OpenCV进行眼部检测(从"Scream's mask"检测眼图)
- OpenCV程序在修改数组时崩溃
- 如何修改这个python opencv程序来从阈值图像中获取xy坐标