我正在查看图像处理算法袖珍手册 ( http://adaptiveart.eecs.umich.edu/2011/wp-content/uploads/2011/09/The-pocket-handbook-of-image-processing-algorithms-in-C.pdf ),我偶然发现了这段代码(如下)。
谁能帮我理解
*(Im->Data + (x)*Im->Cols + (y))
它在 pdf 第 33 页。
#define pix(Im,x,y) \
*(Im->Data + (x)*Im->Cols + (y))
/* Compute and return area for objects */
int area(struct Image *In, int x1, int y1, int x2, int y2, unsigned char ObjVal){
long i, j, rows;
int area_value = 0;
for(i=x1; i<=x2; ++i)
for(j=y1; j<=y2; ++j){
if(pix(In,i,j)==ObjVal)++area_value;
}
return(area_value);
}
最佳答案
Im
是指向 Image 结构的指针
Im->Data
指向缓冲区。我们称它为 buffer
Im->Cols
表示列数。 num_columns
buffer + x * num_columns + y
指向像素
顺便说一下,这是一种非常低效的遍历图像的方法,因为您要计算每个点的位置。
那里已经有一个 2 for 循环。使用这个宏没有意义。您可以轻松地使用单个指针并进行调整。
类似这样的东西会更有效率(我还没有测试过):
int area(struct Image *In, int x1, int y1, int x2, int y2, unsigned char ObjVal)
{
int area_value = 0;
unsigned char *p = Im->Data + x1 * Im->Cols + y1; // Move to the first pixel
int adj = In->Cols - (x2-x1) // How much for the start of next row
for(int i=x1; i<=x2; ++i, p += adj )
{
for(int j=y1; j<=y2; ++j, ++p)
{
if (*p == ObjVal) ++area_value;
}
}
return area_value;
}
关于c++ - 图像处理算法代码,解释指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776918/