从bitmapData(NSBitmapImageRep)Cocoa中提取RGB数据

Arg*_*ium 2 cocoa image-processing objective-c

我正在开发一个需要比较两个图像的应用程序,以便查看它们之间的差异,并且应用程序会针对不同的图像重复执行此操作.所以我目前这样做的方法是将图像作为两个NSBitmapImageRep,然后使用colorAtX: y:函数来获取NSColor对象,然后检查RGB组件.但这种方法非常缓慢.因此,围绕互联网进行研究,我发现帖子说更好的方法是使用函数bitmapData获取位图数据,该函数返回unsigned char.对我来说不幸的是我不知道如何从这里进一步发展,我发现的帖子都没有告诉你如何从中获得每个像素的RGB分量bitmapData.所以目前我有:

 NSBitmapImageRep* imageRep = [self screenShot]; //Takes a screenshot of the content displayed in the nswindow
unsigned char *data = [imageRep bitmapData]; //Get the bitmap data

//What do I do here in order to get the RGB components?
Run Code Online (Sandbox Code Playgroud)

谢谢

use*_*321 5

-bitmapData点到RGB像素数据返回的指针.您必须查询图像代表以查看它所处的格式.您可以使用这种-bitmapFormat方法来告诉您数据是第一个还是最后一个(RGBA或ARGB),以及像素是整数还是浮点数.您需要检查每个像素的样本数量等.以下是文档.如果您对数据格式有更具体的问题,请发布这些问题,我们可以尝试帮助解答这些问题.

通常数据是非平面的,这意味着它只是交错的RGBA(或ARGB)数据.你可以像这样循环它(假设每通道8位,4通道数据):

int width = [imageRep pixelsWide];
int height = [imageRep pixelsHight];
int rowBytes = [imageRep bytesPerRow];
char* pixels = [imageRep bitmapData];
int row, col;
for (row = 0; row < height; row++)
{
    unsigned char* rowStart = (unsigned char*)(pixels + (row * rowBytes));
    unsigned char* nextChannel = rowStart;
    for (col = 0; col < width; col++)
    {
        unsigned char red, green, blue, alpha;

        red = *nextChannel;
        nextChannel++;
        green = *nextChannel;
        nextChannel++;
        // ...etc...
    }
}
Run Code Online (Sandbox Code Playgroud)