<p>Opencv矩阵遵循与numpy数组完全不同的范式,因此您将无法利用numpy允许的广播和其他索引功能。你知道吗</p>
<p>在特殊的情况下,OpenCV甚至不支持三维矩阵,这是因为OpenCV对计算机视觉的特殊性。如果您绝对需要使用opencv矩阵,请创建一个大小为<code>sum(array.shape)</code>的一维opencv矩阵,并将所有数据按C顺序填充,那么您仍然可以对任意维度使用通用索引公式:</p>
<pre><code>cv::Mat your_mat = /*what ever data for your flattened matrix assuming double,*/
vector<int> dimensions = {/*what ever your dimensions are, in this case 1, 17, 17, 5, 5*/};
vector<int> nd_index = {/*what ever indexes you are trying to access, assuming x, y, z, ... order, not C order*/};
int accumulated_frame_size = 1;
int linear_index = 0;
for(int dim_idx = 0; dim_idx < dimensions.size(); ++dim_idx){
linear_index += nd_index[dim_idx] * accumulated_frame_size;
accumulated_frame_size *= nd_index[dim_idx];
}
//the value for that index.
std::cout << your_mat.at<double>(linear_idx) << "\n";
</code></pre>
<p>当然要注意的是,除非它完全是基于元素的,否则您可能想要对它进行操作的大部分内容可能都不会起作用。你知道吗</p>
<p>既然你想做一些具体的事情,我们可以做得更好。我们的数组中的第一个单维度不存在,因为我们用C++来扁平化,所以不需要用{{CD2}}下标。仔细想想,<code>subarray[:,:,:,4]</code>实际上只是每5个元素偏移量的第4个索引,仅此而已。为了提取这些信息,我们首先计算要提取多少元素,然后将它们输入到另一个矩阵中。你知道吗</p>
<pre><code>int extract_count = 17 * 17 * 5; //all dimensions before indexed dimension.
int final_dim_size = 5;
int extract_index = 4;
cv::Mat extracted_mat(1,extract_count,CV_64F);
for(int i = 0; i< extract_count ; ++i){
extracted_mat.at<double>(i) = your_mat.at<double>(i*final_dim_size + extract_index);
}
</code></pre>
<p>Numpy所做的是在内部将所有索引转换为类似的操作。你知道吗</p>