gpt4 book ai didi

Bradski & Kaehler 的 "Learning OpenCV"中的 const float union ptr 示例 3-9

转载 作者:行者123 更新时间:2023-11-30 15:45:09 26 4
gpt4 key购买 nike

在 Gary Bradski 和 Adrian Kaehler 的“Learning OpenCV”中,有一个关于 CvMat 矩阵结构的部分,其中包含以下示例代码(示例 3-9:对单 channel 矩阵中的所有元素求和)

float sum( const CvMat* mat ) { 

float s = 0.0f;
for(int row=0; row<mat->rows; row++ ) {
const float* ptr = (const float *)(mat->data.ptr + row * mat->step);
for(int col=0; col<mat->cols; col++ ) {
s += *ptr++;
}
}
return( s );
}

关于这段代码,有几件事我不明白,但它们可能是我多年不使用 C 的结果,而不是 OpenCV 问题。

  1. 为什么是const?由于 ptr 在函数中稍后递增,我不明白为什么将其声明为 const

  2. 为什么是.ptr?作者指出,“在计算矩阵中的指针时,请记住矩阵元素 data 是一个 union 。因此,在取消引用该指针时,必须在为了获得正确的指针类型。”那么为什么不使用类型为 float* 的 union 成员 fl ,这样代码行将是

    float* ptr = mat->data.fl + row * mat->step;

而不是采用 uchar* 类型的 ptr 并需要额外的转换?

最佳答案

Why const? Since ptr is incremented later in the function I do not understand why it is declared const.

因为const不是指针,而是它指向的对象。您所讨论的内容将写为 float *const ptr,但如您所见,ptr 并未这样声明。

Why .ptr?

因为 union 体的大小可能与float不同。想象一下这个数组:

               union *          union *           union *         union *
+0 +1 +2 +3 (correct)
+----------------+----------------+----------------+
union boundaries: | union | union | union |
+----------------+----------------+----------------+
float boundaries: | float |junk| float |junk| float |junk|
+----------------+----------------+----------------+
^ ^ ^ ^ ^
float * float * float * float * float *
+0 +1 +2 +3 +4
^--------- these are all wrong ----------^

如果您获得指向第一个 float 的指针并对其应用指针算术,如果 union 大于 float.

关于Bradski & Kaehler 的 "Learning OpenCV"中的 const float union ptr 示例 3-9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19206627/

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