从像素值获得RGB通道没有任何库

Get RGB Channels From Pixel Value Without Any Library

本文关键字:通道 任何库 RGB 像素      更新时间:2023-10-16

无需任何库即可从像素值获取RGB通道
我试图获得我从图像中读取的每个像素的RGB通道。我使用getchar从图像中读取每个字节。所以在网上搜索了一下之后,我发现了BMP的颜色数据从36字节开始,我知道每个通道是8位,整个RGB是8位的红色,8位的绿色和8位的蓝色。我的问题是如何从像素值中提取它们?
例如:

pixel = getchar(image);

我能做些什么来提取这些通道?另外,我在JAVA上看到了这个例子,但不知道如何在c++上实现它:

int rgb[] = new int[] {
(argb >> 16) & 0xff, //red
(argb >>  8) & 0xff, //green
(argb      ) & 0xff  //blue
};

我猜argb是我之前提到的"像素"变量。
谢谢。

假设它被编码为ABGR,并且每个像素有一个整数值,这应该可以做到:

int r = color & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 16) & 0xff;
int a = (color >> 24) & 0xff;

当读取单个字节时,它取决于格式的端序。由于有两种可能的方式,这当然总是不一致的,所以我将两种方式都写下来,读取作为伪函数完成:

RGBA:

int r = readByte();
int g = readByte();
int b = readByte();
int a = readByte();

ABGR:

int a = readByte();
int b = readByte();
int g = readByte();
int r = readByte();

如何编码取决于你的文件格式是如何布局的。我也见过BGRA和ARGB命令和平面RGB(每个通道是一个宽度x高度字节的单独缓冲区)。

看起来维基百科对BMP文件的样子有一个很好的概述:http://en.wikipedia.org/wiki/BMP_file_format

因为它看起来有点复杂,我强烈建议使用一个库而不是自己编写。