c - 查找像素的 xy 位置的函数

标签 c bitmap bmp

因为我之前的问题肯定不是很干净。分别我无法实现我的问题的确切解决方案。我一直在研究一个函数,该函数返回位于 X/Y 坐标中的像素的字节偏移量。为此,我有:

dword bmp_find_xy (dword xp, dword yp)
{
    dword w = 50; // to clarify thats the real widh of the sample image i use
    dword bpx = (3*8); // using 3*8 as a reminder.
    dword offset = (2+sizeof(BMP)+sizeof(DIB)); // this is the offset 54.
    dword pitch = w * 3; // determining the widh of pixels. Pitch variable
    dword row = w * 3; // determining the widh of pixels. Row variable.
    dword pixAddress; // result variable

    if(pitch % 4 != 0) pitch += 4 - (pitch % 4); // finding the pitch (row+padding)
    pixAddress = (offset) + pitch * yp + ((xp * bpx) / 8); // finding the address

    return pixAddress; 
}

所以问题不会像“我做错了什么/为什么我会收到奇怪的错误”。问题是..我做得对吗?在第一次测试中它似乎工作。但我有点不确定。一旦确认这是正确的方法..我将删除问题。

最佳答案

您的代码看起来为我提供了正确的结果。然而它本身是不一致的。

  • 在行 (yp) 寻址中,假设每个像素有 3 个字节。
  • 在 (xp) 寻址列中,假设每个像素有 3*8 位。

那么为什么在第一种情况下使用字节,在第二种情况下使用位呢?我认为代码会像这样更清晰:

dword width = 50; // image width
dword channels = 3; // number of color channels
dword bpp = 8; // depth in bits

dword single = (channels*bpp)/8; // size of a pixel in bytes
dword offset = (2+sizeof(BMP)+sizeof(DIB)); // this is the offset 54.
dword rowsize = width*single; // size of a row in memory
if (rowsize % 4 != 0)
    rowsize += 4 - (rowsize % 4); // account for padding

dword pixAddress; // result variable
pixAddress = offset + yp*rowsize + xp*single; // finding the address

return pixAddress; 

此外,您还可以从标题中读取宽度、 channel 和 bpp。

接下来,如果您首先获取一行中第一个像素的地址,然后让它遍历该行(而不是每次都重新计算整个事情),您的代码会更快。下面是对所有像素运行的典型任务的说明。请注意,我没有使用与此处原始问题相同的编码风格。

unsigned char maxGreen = 0;
for (int y = 0; y < height; y++) {
    unsigned char *row = bitmap.getRowPtr(y);
    for (int x = 0; x < width; x++) {
        unsigned char *pixel = row + bitmap.getColumnOffset(x);
        if (pixel[2] > maxGreen)
            maxGreen = pixel[2];
    }
}
// maxGreen holds the maximum value in the green channel observed in the image

如您所见,在此示例中,偏移量、填充等计算只需在 getRowPtr() 函数中每行执行一次。对于每个像素,我们只需要在 getColumnOffset() 函数中进行偏移计算(简单的乘法)。 当分解每个像素需要完成多少计算时,这会使示例更快。

最后,我永远不会自己编写代码来读取 BMP!为此使用库!

关于c - 查找像素的 xy 位置的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234223/

相关文章:

c - 尝试在结构上使用scanf时出现段错误

java - 我想将图像大小减小到 64 KiB 以保存在 mySql 数据库中

c++ - 如何用GDI+绘制透明BMP

python - 为什么 skimage.imread() 不返回我的 bmp 的 RGB 值?

php - 将 CRC 算法从 C 翻译成 PHP

c - 如何从字符串数组创建字符串 C

c - 写入和读取的数据在二进制文件中保持不变?

c# - 将位图数据提取到字节数组

java - 在Android中的Canvas上绘制圆外的位图(箭头)

c - 为什么在尝试向输入的 bmp 文件添加过滤器时我的代码段出现错误?