13

OpenCV 函数cvtColor转换矩阵的颜色空间(例如从 RGB 到灰度)。该函数的 C++ 签名是

void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )

可以使用此函数将矩阵转换到位,即与src相同的对象dst吗?

cv::Mat mat = getColorImage();
cvtColor(mat, mat, CV_RGB2GRAY);

(我知道无论哪种方式,由于目标的通道数与源的通道数不同,它仍然需要为目标分配一个新的内存块。)

更一般地说,OpenCV API 中是否有一个约定来确定何时可以以这种方式使用函数?

4

3 回答 3

10

可能回答太晚了,但是我想说我不同意这里已经写的一些东西。
即使目标矩阵没有“相同数量的通道”,或者即使目标矩阵尚未创建,您也可以将相同的 Mat 放置为源和目标,没有问题。
OpenCV 程序员对其进行了彻底的设计。
此函数的所有用户必须注意源 Mat 的正确性,包括通道数和数据类型,并记住在函数调用之后它们可能会改变。

证明来自查看源代码,第 2406 行,只是cv::cvtColor(…)函数内部的第一行,

Mat src = _src.getMat();

被调用,然后创建 Mat dst(并且 dst=_dst=_scr)。
所以cv::cvtColor(…)在进行就地调用时,里面的情况如下:src指向旧矩阵,_src、_dst、dst都指向同一个新分配的矩阵,这将是目标矩阵。
这意味着比现在新变量 src 和 dst(不是来自函数调用 _src 和 _dst 的变量)已准备好传递给真正的转换函数。
函数void cv::cvtColor(…)完成后,src 被释放,_src、_dst 和 dst 都指向同一个 Mat,_dst 的 refcount 将变为 1。

于 2016-01-03T09:45:26.150 回答
3

If you have a look at the code here, you will see that on line 2420, a create is called on the matrix dst. This means the data section as well as the headers for this matrix is rewritten. So it might not be advisable to call this function with the same matrix in src and dst.

As for a convention in OpenCV, have a look at the InputArray and OutputArray, these seem to suggest that whenever function calls exist with these as data types of input and output, you should probably use different Mat variables.

于 2013-03-11T18:12:25.200 回答
2

dst它必须在调用后包含正确转换的矩阵的意义上就地工作cv::cvtColor。但是如果输入的通道数与输出的通道数不同,那么矩阵的数据将被重新分配。

如果您有一个dst在就地调用后没有正确转换图像的示例,请在http://code.opencv.orgcvtColor上将其作为错误提交

更一般地说,OpenCV API 中是否有一个约定来确定何时可以以这种方式使用函数?

没有这样的约定。但是您可以期望大多数基本图像处理功能都可以就地工作。因此,已知所有转换、过滤器、阈值、仿射/透视转换都支持就地调用。

于 2013-03-11T20:58:01.427 回答