给定一个包含 4*4 元素的垫子,如下所示:
[1,2,3,4
5,6,7,8
9,10,11,12
13,14,15,16
]
我想删除每一行的特定像素,这意味着删除 [0,0] [1,1] [2,0]
[3,1] 位置元素,成为
[2,3,4
5,7,8
10,11,12
13,15,16
]
注意:Mat 的大小改变了。
问题:有没有一种有效的方法来进行这些操作?
最佳答案
我想唯一可行的选择是逐个像素地复制矩阵并忽略不需要的像素,因为它们散落在源矩阵的不同行和列中,因此没有单行代码。
std::vector<int> indices = { 0, 1, 0, 1 };
cv::Mat dest_mat(source_mat.rows, source_mat.cols - 1, source_mat.type());
int idx = 0;
int dest_col = 0;
for (int i = 0; i < source_mat.rows; ++i)
{
int* dest_row = dest_mat.ptr<int>(i);
const int* source_row = source_mat.ptr<int>(i);
dest_col = 0;
for (int j = 0; j < source_mat.cols; ++j)
{
if (j != indices[idx])
{
dest_row[dest_col] = source_row[j];
++dest_col;
}
else
++idx;
}
}
上面的代码假设每一行都包含一个不需要的像素,因为我就是这样理解你的任务的。您可能需要调整 ptr<>()
以便其类型适合您实际使用的类型。
关于C++/opencv : how to delete specific path pixels in efficient way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44794678/