将numpy切片转换为Opencv c++M

2024-05-08 13:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个数组,其形状为(1,17,17,5,5)。我需要得到这个数组的子数组:

subarray = array[0]
subarray = subarray[:,:,:,4]
现在我需要用OpenCV来在C++中编写相同的代码。 如何获得子阵列?有没有一种简单的方法可以像Numpy一样切割垫子?你知道吗


Tags: 方法代码numpy数组arrayopencv形状subarray
2条回答

最后我用cv::Range得到了我需要的子数组

std::vector<cv::Range> ranges;
ranges.push_back(cv::Range(0, 1));
ranges.push_back(cv::Range::all());
ranges.push_back(cv::Range::all());
ranges.push_back(cv::Range::all());
ranges.push_back(cv::Range(4, 5));

cv::Mat subarray = array(ranges);

它不会改变数组的维数,但确保我只查看我感兴趣的数据。你知道吗

Opencv矩阵遵循与numpy数组完全不同的范式,因此您将无法利用numpy允许的广播和其他索引功能。你知道吗

在特殊的情况下,OpenCV甚至不支持三维矩阵,这是因为OpenCV对计算机视觉的特殊性。如果您绝对需要使用opencv矩阵,请创建一个大小为sum(array.shape)的一维opencv矩阵,并将所有数据按C顺序填充,那么您仍然可以对任意维度使用通用索引公式:

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";

当然要注意的是,除非它完全是基于元素的,否则您可能想要对它进行操作的大部分内容可能都不会起作用。你知道吗

既然你想做一些具体的事情,我们可以做得更好。我们的数组中的第一个单维度不存在,因为我们用C++来扁平化,所以不需要用{{CD2}}下标。仔细想想,subarray[:,:,:,4]实际上只是每5个元素偏移量的第4个索引,仅此而已。为了提取这些信息,我们首先计算要提取多少元素,然后将它们输入到另一个矩阵中。你知道吗

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);
}

Numpy所做的是在内部将所有索引转换为类似的操作。你知道吗

相关问题 更多 >

    热门问题