gpt4 book ai didi

python - (OpenCV 2.4.6) 将 Mat 的 roi header 复制到另一个 Mat 的 roi

转载 作者:行者123 更新时间:2023-11-30 17:35:19 25 4
gpt4 key购买 nike

我的问题是关于如何仅将 Mat 的 roi 的 header 复制到 Mat 的另一个 roi 以避免复制整个 Mat 的数据以节省计算时间。

例如,我的源 Mat 的 roi 为

Mat src(cv::Size(4,3),CV_32FC1);
for(int i=0;i<src.rows;i++){
for(int j=0;j<src.cols;j++){
src.ptr<float>(i)[j] = i*src.cols+j;
}
}
Mat src_roi = src(Rect(1,1,src.cols-2,src.rows-1));
cout << src << endl;
cout << src_roi << endl;

// = = = OUTPUT = = =
[0, 1, 2, 3;
4, 5, 6, 7;
8, 9, 10, 11]
[5, 6;
9, 10]

接下来,我希望结果如下所示,其中关键函数(func())为

Mat dst(cv::Size(src.cols*src.rows,1),CV_32FC1);
dst.setTo(-1);
Mat dst_roi = dst.colRange(2,2+src_roi.cols*src_roi.rows);
func(src_roi,dst_roi);
cout << dst << endl;
cout << dst_roi << endl;

// = = = OUTPUT = = =
[-1, -1, 5, 6, 9, 10, -1, -1, -1, -1, -1, -1]
[5, 6, 9, 10]

基本上, func() 可以通过以下方式实现,以简单地达到我的预期输出(计算时间在 Release模式下评估),

// A01 = = =
void func(const Mat &src,Mat &dst){
Mat ma = src.clone();
ma = ma.reshape(0,1);
ma.copyTo(dst);
}
// = = = Computation time = = =
0.414 seconds // when src's size is changed to 15000*15000

// A02 = = =
void func(const Mat &src,Mat &dst){
MatConstIterator_<float> it1 = src.begin<float>(), it1_end = src.end<float>();
MatIterator_<float> dst_it = dst.begin<float>();
for( ; it1 != it1_end; ++it1, ++dst_it ){
*dst_it = *it1;
}
}
// = = = Computation time = = =
0.508 seconds // when src's size is changed to 15000*15000

// A03 = = =
void func(const Mat &src,Mat &dst){
int count=0;
for(int i=0;i<src.rows;i++){
for(int j=0;j<src.cols;j++){
((float*)dst.data)[count++] = src.ptr<float>(i)[j];
}
}
}
// = = = Computation time = = =
0.269 seconds // when src's size is changed to 15000*15000

然而,它们都会复制整个矩阵,因此当 roi 很大时会花费很多时间。

因此,我希望有一种方法可以仅复制 header 或指针来达到相同的效果并节省所需的计算。或者其他能够满足我的期望的方式或想法。

最佳答案

因为在 func() 中,您将每个 elem 复制两次(首先是 src.clone() 和 copyTo()),所以
我想到的是通过直接将 elems 从 src 复制到 dst 来摆脱其中的一个:

void func(const Mat &src,Mat &dst){
MatConstIterator_<float> it1 = src.begin<float>(), it1_end = src.end<float>();
MatIterator_<float> dst_it = dst.begin<float>();

for( ; it1 != it1_end; ++it1, ++dst_it )
*dst_it = *it1;
}

您不必关心 src 和 dst 的大小,但它们必须具有相同数量的元素。

但坦率地说,我认为您无法避免该拷贝,因为 src 和 dst 具有不同的大小格式。您不能直接对 src_roi 执行 reshape(),因为它不是连续的。这就是您所期望的,因为您无法 reshape 一个矩阵,该矩阵是较大矩阵的一部分,在某些 roi 上更改其格式形状,而不是在整个矩阵中更改。我的意思是,如果 header 的大小格式不同,您不能告诉 opencv 仅复制 header roi。

关于python - (OpenCV 2.4.6) 将 Mat 的 roi header 复制到另一个 Mat 的 roi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com