gpt4 book ai didi

cocoa - 从 NSImage 获取像素和颜色

转载 作者:行者123 更新时间:2023-12-03 16:05:00 24 4
gpt4 key购买 nike

我创建了一个 NSImage 对象,理想情况下想确定它包含多少个像素颜色。这可能吗?

最佳答案

此代码将 NSImage 渲染到 CGBitmapContext 中:

- (void)updateImageData {

if (!_image)
return;

// Dimensions - source image determines context size

NSSize imageSize = _image.size;
NSRect imageRect = NSMakeRect(0, 0, imageSize.width, imageSize.height);

// Create a context to hold the image data

CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);

CGContextRef ctx = CGBitmapContextCreate(NULL,
imageSize.width,
imageSize.height,
8,
0,
colorSpace,
kCGImageAlphaPremultipliedLast);

// Wrap graphics context

NSGraphicsContext* gctx = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:NO];

// Make our bitmap context current and render the NSImage into it

[NSGraphicsContext setCurrentContext:gctx];
[_image drawInRect:imageRect];

// Calculate the histogram

[self computeHistogramFromBitmap:ctx];

// Clean up

[NSGraphicsContext setCurrentContext:nil];
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
}

给定位图上下文,我们可以直接访问原始图像数据,并计算每个颜色 channel 的直方图:

- (void)computeHistogramFromBitmap:(CGContextRef)bitmap {

// NB: Assumes RGBA 8bpp

size_t width = CGBitmapContextGetWidth(bitmap);
size_t height = CGBitmapContextGetHeight(bitmap);

uint32_t* pixel = (uint32_t*)CGBitmapContextGetData(bitmap);

for (unsigned y = 0; y < height; y++)
{
for (unsigned x = 0; x < width; x++)
{
uint32_t rgba = *pixel;

// Extract colour components
uint8_t red = (rgba & 0x000000ff) >> 0;
uint8_t green = (rgba & 0x0000ff00) >> 8;
uint8_t blue = (rgba & 0x00ff0000) >> 16;

// Accumulate each colour
_histogram[kRedChannel][red]++;
_histogram[kGreenChannel][green]++;
_histogram[kBlueChannel][blue]++;

// Next pixel!
pixel++;
}
}
}

@end

我已经发布了一个完整的项目,一个 Cocoa 示例应用程序,其中包括上述内容。

关于cocoa - 从 NSImage 获取像素和颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1994082/

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